repo stringlengths 5 67 | path stringlengths 4 218 | func_name stringlengths 0 151 | original_string stringlengths 52 373k | language stringclasses 6 values | code stringlengths 52 373k | code_tokens listlengths 10 512 | docstring stringlengths 3 47.2k | docstring_tokens listlengths 3 234 | sha stringlengths 40 40 | url stringlengths 85 339 | partition stringclasses 3 values |
|---|---|---|---|---|---|---|---|---|---|---|---|
nats-io/go-nats | nats.go | SetDisconnectHandler | func (nc *Conn) SetDisconnectHandler(dcb ConnHandler) {
if nc == nil {
return
}
nc.mu.Lock()
defer nc.mu.Unlock()
nc.Opts.DisconnectedCB = dcb
} | go | func (nc *Conn) SetDisconnectHandler(dcb ConnHandler) {
if nc == nil {
return
}
nc.mu.Lock()
defer nc.mu.Unlock()
nc.Opts.DisconnectedCB = dcb
} | [
"func",
"(",
"nc",
"*",
"Conn",
")",
"SetDisconnectHandler",
"(",
"dcb",
"ConnHandler",
")",
"{",
"if",
"nc",
"==",
"nil",
"{",
"return",
"\n",
"}",
"\n",
"nc",
".",
"mu",
".",
"Lock",
"(",
")",
"\n",
"defer",
"nc",
".",
"mu",
".",
"Unlock",
"(",
")",
"\n",
"nc",
".",
"Opts",
".",
"DisconnectedCB",
"=",
"dcb",
"\n",
"}"
] | // Handler processing
// SetDisconnectHandler will set the disconnect event handler. | [
"Handler",
"processing",
"SetDisconnectHandler",
"will",
"set",
"the",
"disconnect",
"event",
"handler",
"."
] | 36d30b0ba7aa260ae25b4f3d312b2a700106fd78 | https://github.com/nats-io/go-nats/blob/36d30b0ba7aa260ae25b4f3d312b2a700106fd78/nats.go#L854-L861 | train |
nats-io/go-nats | nats.go | SetReconnectHandler | func (nc *Conn) SetReconnectHandler(rcb ConnHandler) {
if nc == nil {
return
}
nc.mu.Lock()
defer nc.mu.Unlock()
nc.Opts.ReconnectedCB = rcb
} | go | func (nc *Conn) SetReconnectHandler(rcb ConnHandler) {
if nc == nil {
return
}
nc.mu.Lock()
defer nc.mu.Unlock()
nc.Opts.ReconnectedCB = rcb
} | [
"func",
"(",
"nc",
"*",
"Conn",
")",
"SetReconnectHandler",
"(",
"rcb",
"ConnHandler",
")",
"{",
"if",
"nc",
"==",
"nil",
"{",
"return",
"\n",
"}",
"\n",
"nc",
".",
"mu",
".",
"Lock",
"(",
")",
"\n",
"defer",
"nc",
".",
"mu",
".",
"Unlock",
"(",
")",
"\n",
"nc",
".",
"Opts",
".",
"ReconnectedCB",
"=",
"rcb",
"\n",
"}"
] | // SetReconnectHandler will set the reconnect event handler. | [
"SetReconnectHandler",
"will",
"set",
"the",
"reconnect",
"event",
"handler",
"."
] | 36d30b0ba7aa260ae25b4f3d312b2a700106fd78 | https://github.com/nats-io/go-nats/blob/36d30b0ba7aa260ae25b4f3d312b2a700106fd78/nats.go#L864-L871 | train |
nats-io/go-nats | nats.go | SetDiscoveredServersHandler | func (nc *Conn) SetDiscoveredServersHandler(dscb ConnHandler) {
if nc == nil {
return
}
nc.mu.Lock()
defer nc.mu.Unlock()
nc.Opts.DiscoveredServersCB = dscb
} | go | func (nc *Conn) SetDiscoveredServersHandler(dscb ConnHandler) {
if nc == nil {
return
}
nc.mu.Lock()
defer nc.mu.Unlock()
nc.Opts.DiscoveredServersCB = dscb
} | [
"func",
"(",
"nc",
"*",
"Conn",
")",
"SetDiscoveredServersHandler",
"(",
"dscb",
"ConnHandler",
")",
"{",
"if",
"nc",
"==",
"nil",
"{",
"return",
"\n",
"}",
"\n",
"nc",
".",
"mu",
".",
"Lock",
"(",
")",
"\n",
"defer",
"nc",
".",
"mu",
".",
"Unlock",
"(",
")",
"\n",
"nc",
".",
"Opts",
".",
"DiscoveredServersCB",
"=",
"dscb",
"\n",
"}"
] | // SetDiscoveredServersHandler will set the discovered servers handler. | [
"SetDiscoveredServersHandler",
"will",
"set",
"the",
"discovered",
"servers",
"handler",
"."
] | 36d30b0ba7aa260ae25b4f3d312b2a700106fd78 | https://github.com/nats-io/go-nats/blob/36d30b0ba7aa260ae25b4f3d312b2a700106fd78/nats.go#L874-L881 | train |
nats-io/go-nats | nats.go | SetClosedHandler | func (nc *Conn) SetClosedHandler(cb ConnHandler) {
if nc == nil {
return
}
nc.mu.Lock()
defer nc.mu.Unlock()
nc.Opts.ClosedCB = cb
} | go | func (nc *Conn) SetClosedHandler(cb ConnHandler) {
if nc == nil {
return
}
nc.mu.Lock()
defer nc.mu.Unlock()
nc.Opts.ClosedCB = cb
} | [
"func",
"(",
"nc",
"*",
"Conn",
")",
"SetClosedHandler",
"(",
"cb",
"ConnHandler",
")",
"{",
"if",
"nc",
"==",
"nil",
"{",
"return",
"\n",
"}",
"\n",
"nc",
".",
"mu",
".",
"Lock",
"(",
")",
"\n",
"defer",
"nc",
".",
"mu",
".",
"Unlock",
"(",
")",
"\n",
"nc",
".",
"Opts",
".",
"ClosedCB",
"=",
"cb",
"\n",
"}"
] | // SetClosedHandler will set the reconnect event handler. | [
"SetClosedHandler",
"will",
"set",
"the",
"reconnect",
"event",
"handler",
"."
] | 36d30b0ba7aa260ae25b4f3d312b2a700106fd78 | https://github.com/nats-io/go-nats/blob/36d30b0ba7aa260ae25b4f3d312b2a700106fd78/nats.go#L884-L891 | train |
nats-io/go-nats | nats.go | SetErrorHandler | func (nc *Conn) SetErrorHandler(cb ErrHandler) {
if nc == nil {
return
}
nc.mu.Lock()
defer nc.mu.Unlock()
nc.Opts.AsyncErrorCB = cb
} | go | func (nc *Conn) SetErrorHandler(cb ErrHandler) {
if nc == nil {
return
}
nc.mu.Lock()
defer nc.mu.Unlock()
nc.Opts.AsyncErrorCB = cb
} | [
"func",
"(",
"nc",
"*",
"Conn",
")",
"SetErrorHandler",
"(",
"cb",
"ErrHandler",
")",
"{",
"if",
"nc",
"==",
"nil",
"{",
"return",
"\n",
"}",
"\n",
"nc",
".",
"mu",
".",
"Lock",
"(",
")",
"\n",
"defer",
"nc",
".",
"mu",
".",
"Unlock",
"(",
")",
"\n",
"nc",
".",
"Opts",
".",
"AsyncErrorCB",
"=",
"cb",
"\n",
"}"
] | // SetErrorHandler will set the async error handler. | [
"SetErrorHandler",
"will",
"set",
"the",
"async",
"error",
"handler",
"."
] | 36d30b0ba7aa260ae25b4f3d312b2a700106fd78 | https://github.com/nats-io/go-nats/blob/36d30b0ba7aa260ae25b4f3d312b2a700106fd78/nats.go#L894-L901 | train |
nats-io/go-nats | nats.go | processUrlString | func processUrlString(url string) []string {
urls := strings.Split(url, ",")
for i, s := range urls {
urls[i] = strings.TrimSpace(s)
}
return urls
} | go | func processUrlString(url string) []string {
urls := strings.Split(url, ",")
for i, s := range urls {
urls[i] = strings.TrimSpace(s)
}
return urls
} | [
"func",
"processUrlString",
"(",
"url",
"string",
")",
"[",
"]",
"string",
"{",
"urls",
":=",
"strings",
".",
"Split",
"(",
"url",
",",
"\",\"",
")",
"\n",
"for",
"i",
",",
"s",
":=",
"range",
"urls",
"{",
"urls",
"[",
"i",
"]",
"=",
"strings",
".",
"TrimSpace",
"(",
"s",
")",
"\n",
"}",
"\n",
"return",
"urls",
"\n",
"}"
] | // Process the url string argument to Connect.
// Return an array of urls, even if only one. | [
"Process",
"the",
"url",
"string",
"argument",
"to",
"Connect",
".",
"Return",
"an",
"array",
"of",
"urls",
"even",
"if",
"only",
"one",
"."
] | 36d30b0ba7aa260ae25b4f3d312b2a700106fd78 | https://github.com/nats-io/go-nats/blob/36d30b0ba7aa260ae25b4f3d312b2a700106fd78/nats.go#L905-L911 | train |
nats-io/go-nats | nats.go | Connect | func (o Options) Connect() (*Conn, error) {
nc := &Conn{Opts: o}
// Some default options processing.
if nc.Opts.MaxPingsOut == 0 {
nc.Opts.MaxPingsOut = DefaultMaxPingOut
}
// Allow old default for channel length to work correctly.
if nc.Opts.SubChanLen == 0 {
nc.Opts.SubChanLen = DefaultMaxChanLen
}
// Default ReconnectBufSize
if nc.Opts.ReconnectBufSize == 0 {
nc.Opts.ReconnectBufSize = DefaultReconnectBufSize
}
// Ensure that Timeout is not 0
if nc.Opts.Timeout == 0 {
nc.Opts.Timeout = DefaultTimeout
}
// Check first for user jwt callback being defined and nkey.
if nc.Opts.UserJWT != nil && nc.Opts.Nkey != "" {
return nil, ErrNkeyAndUser
}
// Check if we have an nkey but no signature callback defined.
if nc.Opts.Nkey != "" && nc.Opts.SignatureCB == nil {
return nil, ErrNkeyButNoSigCB
}
// Allow custom Dialer for connecting using DialTimeout by default
if nc.Opts.Dialer == nil {
nc.Opts.Dialer = &net.Dialer{
Timeout: nc.Opts.Timeout,
}
}
if err := nc.setupServerPool(); err != nil {
return nil, err
}
// Create the async callback handler.
nc.ach = &asyncCallbacksHandler{}
nc.ach.cond = sync.NewCond(&nc.ach.mu)
if err := nc.connect(); err != nil {
return nil, err
}
// Spin up the async cb dispatcher on success
go nc.ach.asyncCBDispatcher()
return nc, nil
} | go | func (o Options) Connect() (*Conn, error) {
nc := &Conn{Opts: o}
// Some default options processing.
if nc.Opts.MaxPingsOut == 0 {
nc.Opts.MaxPingsOut = DefaultMaxPingOut
}
// Allow old default for channel length to work correctly.
if nc.Opts.SubChanLen == 0 {
nc.Opts.SubChanLen = DefaultMaxChanLen
}
// Default ReconnectBufSize
if nc.Opts.ReconnectBufSize == 0 {
nc.Opts.ReconnectBufSize = DefaultReconnectBufSize
}
// Ensure that Timeout is not 0
if nc.Opts.Timeout == 0 {
nc.Opts.Timeout = DefaultTimeout
}
// Check first for user jwt callback being defined and nkey.
if nc.Opts.UserJWT != nil && nc.Opts.Nkey != "" {
return nil, ErrNkeyAndUser
}
// Check if we have an nkey but no signature callback defined.
if nc.Opts.Nkey != "" && nc.Opts.SignatureCB == nil {
return nil, ErrNkeyButNoSigCB
}
// Allow custom Dialer for connecting using DialTimeout by default
if nc.Opts.Dialer == nil {
nc.Opts.Dialer = &net.Dialer{
Timeout: nc.Opts.Timeout,
}
}
if err := nc.setupServerPool(); err != nil {
return nil, err
}
// Create the async callback handler.
nc.ach = &asyncCallbacksHandler{}
nc.ach.cond = sync.NewCond(&nc.ach.mu)
if err := nc.connect(); err != nil {
return nil, err
}
// Spin up the async cb dispatcher on success
go nc.ach.asyncCBDispatcher()
return nc, nil
} | [
"func",
"(",
"o",
"Options",
")",
"Connect",
"(",
")",
"(",
"*",
"Conn",
",",
"error",
")",
"{",
"nc",
":=",
"&",
"Conn",
"{",
"Opts",
":",
"o",
"}",
"\n",
"if",
"nc",
".",
"Opts",
".",
"MaxPingsOut",
"==",
"0",
"{",
"nc",
".",
"Opts",
".",
"MaxPingsOut",
"=",
"DefaultMaxPingOut",
"\n",
"}",
"\n",
"if",
"nc",
".",
"Opts",
".",
"SubChanLen",
"==",
"0",
"{",
"nc",
".",
"Opts",
".",
"SubChanLen",
"=",
"DefaultMaxChanLen",
"\n",
"}",
"\n",
"if",
"nc",
".",
"Opts",
".",
"ReconnectBufSize",
"==",
"0",
"{",
"nc",
".",
"Opts",
".",
"ReconnectBufSize",
"=",
"DefaultReconnectBufSize",
"\n",
"}",
"\n",
"if",
"nc",
".",
"Opts",
".",
"Timeout",
"==",
"0",
"{",
"nc",
".",
"Opts",
".",
"Timeout",
"=",
"DefaultTimeout",
"\n",
"}",
"\n",
"if",
"nc",
".",
"Opts",
".",
"UserJWT",
"!=",
"nil",
"&&",
"nc",
".",
"Opts",
".",
"Nkey",
"!=",
"\"\"",
"{",
"return",
"nil",
",",
"ErrNkeyAndUser",
"\n",
"}",
"\n",
"if",
"nc",
".",
"Opts",
".",
"Nkey",
"!=",
"\"\"",
"&&",
"nc",
".",
"Opts",
".",
"SignatureCB",
"==",
"nil",
"{",
"return",
"nil",
",",
"ErrNkeyButNoSigCB",
"\n",
"}",
"\n",
"if",
"nc",
".",
"Opts",
".",
"Dialer",
"==",
"nil",
"{",
"nc",
".",
"Opts",
".",
"Dialer",
"=",
"&",
"net",
".",
"Dialer",
"{",
"Timeout",
":",
"nc",
".",
"Opts",
".",
"Timeout",
",",
"}",
"\n",
"}",
"\n",
"if",
"err",
":=",
"nc",
".",
"setupServerPool",
"(",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"nc",
".",
"ach",
"=",
"&",
"asyncCallbacksHandler",
"{",
"}",
"\n",
"nc",
".",
"ach",
".",
"cond",
"=",
"sync",
".",
"NewCond",
"(",
"&",
"nc",
".",
"ach",
".",
"mu",
")",
"\n",
"if",
"err",
":=",
"nc",
".",
"connect",
"(",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"go",
"nc",
".",
"ach",
".",
"asyncCBDispatcher",
"(",
")",
"\n",
"return",
"nc",
",",
"nil",
"\n",
"}"
] | // Connect will attempt to connect to a NATS server with multiple options. | [
"Connect",
"will",
"attempt",
"to",
"connect",
"to",
"a",
"NATS",
"server",
"with",
"multiple",
"options",
"."
] | 36d30b0ba7aa260ae25b4f3d312b2a700106fd78 | https://github.com/nats-io/go-nats/blob/36d30b0ba7aa260ae25b4f3d312b2a700106fd78/nats.go#L914-L967 | train |
nats-io/go-nats | nats.go | currentServer | func (nc *Conn) currentServer() (int, *srv) {
for i, s := range nc.srvPool {
if s == nil {
continue
}
if s == nc.current {
return i, s
}
}
return -1, nil
} | go | func (nc *Conn) currentServer() (int, *srv) {
for i, s := range nc.srvPool {
if s == nil {
continue
}
if s == nc.current {
return i, s
}
}
return -1, nil
} | [
"func",
"(",
"nc",
"*",
"Conn",
")",
"currentServer",
"(",
")",
"(",
"int",
",",
"*",
"srv",
")",
"{",
"for",
"i",
",",
"s",
":=",
"range",
"nc",
".",
"srvPool",
"{",
"if",
"s",
"==",
"nil",
"{",
"continue",
"\n",
"}",
"\n",
"if",
"s",
"==",
"nc",
".",
"current",
"{",
"return",
"i",
",",
"s",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"-",
"1",
",",
"nil",
"\n",
"}"
] | // Return the currently selected server | [
"Return",
"the",
"currently",
"selected",
"server"
] | 36d30b0ba7aa260ae25b4f3d312b2a700106fd78 | https://github.com/nats-io/go-nats/blob/36d30b0ba7aa260ae25b4f3d312b2a700106fd78/nats.go#L993-L1003 | train |
nats-io/go-nats | nats.go | selectNextServer | func (nc *Conn) selectNextServer() (*srv, error) {
i, s := nc.currentServer()
if i < 0 {
return nil, ErrNoServers
}
sp := nc.srvPool
num := len(sp)
copy(sp[i:num-1], sp[i+1:num])
maxReconnect := nc.Opts.MaxReconnect
if maxReconnect < 0 || s.reconnects < maxReconnect {
nc.srvPool[num-1] = s
} else {
nc.srvPool = sp[0 : num-1]
}
if len(nc.srvPool) <= 0 {
nc.current = nil
return nil, ErrNoServers
}
nc.current = nc.srvPool[0]
return nc.srvPool[0], nil
} | go | func (nc *Conn) selectNextServer() (*srv, error) {
i, s := nc.currentServer()
if i < 0 {
return nil, ErrNoServers
}
sp := nc.srvPool
num := len(sp)
copy(sp[i:num-1], sp[i+1:num])
maxReconnect := nc.Opts.MaxReconnect
if maxReconnect < 0 || s.reconnects < maxReconnect {
nc.srvPool[num-1] = s
} else {
nc.srvPool = sp[0 : num-1]
}
if len(nc.srvPool) <= 0 {
nc.current = nil
return nil, ErrNoServers
}
nc.current = nc.srvPool[0]
return nc.srvPool[0], nil
} | [
"func",
"(",
"nc",
"*",
"Conn",
")",
"selectNextServer",
"(",
")",
"(",
"*",
"srv",
",",
"error",
")",
"{",
"i",
",",
"s",
":=",
"nc",
".",
"currentServer",
"(",
")",
"\n",
"if",
"i",
"<",
"0",
"{",
"return",
"nil",
",",
"ErrNoServers",
"\n",
"}",
"\n",
"sp",
":=",
"nc",
".",
"srvPool",
"\n",
"num",
":=",
"len",
"(",
"sp",
")",
"\n",
"copy",
"(",
"sp",
"[",
"i",
":",
"num",
"-",
"1",
"]",
",",
"sp",
"[",
"i",
"+",
"1",
":",
"num",
"]",
")",
"\n",
"maxReconnect",
":=",
"nc",
".",
"Opts",
".",
"MaxReconnect",
"\n",
"if",
"maxReconnect",
"<",
"0",
"||",
"s",
".",
"reconnects",
"<",
"maxReconnect",
"{",
"nc",
".",
"srvPool",
"[",
"num",
"-",
"1",
"]",
"=",
"s",
"\n",
"}",
"else",
"{",
"nc",
".",
"srvPool",
"=",
"sp",
"[",
"0",
":",
"num",
"-",
"1",
"]",
"\n",
"}",
"\n",
"if",
"len",
"(",
"nc",
".",
"srvPool",
")",
"<=",
"0",
"{",
"nc",
".",
"current",
"=",
"nil",
"\n",
"return",
"nil",
",",
"ErrNoServers",
"\n",
"}",
"\n",
"nc",
".",
"current",
"=",
"nc",
".",
"srvPool",
"[",
"0",
"]",
"\n",
"return",
"nc",
".",
"srvPool",
"[",
"0",
"]",
",",
"nil",
"\n",
"}"
] | // Pop the current server and put onto the end of the list. Select head of list as long
// as number of reconnect attempts under MaxReconnect. | [
"Pop",
"the",
"current",
"server",
"and",
"put",
"onto",
"the",
"end",
"of",
"the",
"list",
".",
"Select",
"head",
"of",
"list",
"as",
"long",
"as",
"number",
"of",
"reconnect",
"attempts",
"under",
"MaxReconnect",
"."
] | 36d30b0ba7aa260ae25b4f3d312b2a700106fd78 | https://github.com/nats-io/go-nats/blob/36d30b0ba7aa260ae25b4f3d312b2a700106fd78/nats.go#L1007-L1027 | train |
nats-io/go-nats | nats.go | pickServer | func (nc *Conn) pickServer() error {
nc.current = nil
if len(nc.srvPool) <= 0 {
return ErrNoServers
}
for _, s := range nc.srvPool {
if s != nil {
nc.current = s
return nil
}
}
return ErrNoServers
} | go | func (nc *Conn) pickServer() error {
nc.current = nil
if len(nc.srvPool) <= 0 {
return ErrNoServers
}
for _, s := range nc.srvPool {
if s != nil {
nc.current = s
return nil
}
}
return ErrNoServers
} | [
"func",
"(",
"nc",
"*",
"Conn",
")",
"pickServer",
"(",
")",
"error",
"{",
"nc",
".",
"current",
"=",
"nil",
"\n",
"if",
"len",
"(",
"nc",
".",
"srvPool",
")",
"<=",
"0",
"{",
"return",
"ErrNoServers",
"\n",
"}",
"\n",
"for",
"_",
",",
"s",
":=",
"range",
"nc",
".",
"srvPool",
"{",
"if",
"s",
"!=",
"nil",
"{",
"nc",
".",
"current",
"=",
"s",
"\n",
"return",
"nil",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"ErrNoServers",
"\n",
"}"
] | // Will assign the correct server to nc.current | [
"Will",
"assign",
"the",
"correct",
"server",
"to",
"nc",
".",
"current"
] | 36d30b0ba7aa260ae25b4f3d312b2a700106fd78 | https://github.com/nats-io/go-nats/blob/36d30b0ba7aa260ae25b4f3d312b2a700106fd78/nats.go#L1030-L1043 | train |
nats-io/go-nats | nats.go | setupServerPool | func (nc *Conn) setupServerPool() error {
nc.srvPool = make([]*srv, 0, srvPoolSize)
nc.urls = make(map[string]struct{}, srvPoolSize)
// Create srv objects from each url string in nc.Opts.Servers
// and add them to the pool.
for _, urlString := range nc.Opts.Servers {
if err := nc.addURLToPool(urlString, false, false); err != nil {
return err
}
}
// Randomize if allowed to
if !nc.Opts.NoRandomize {
nc.shufflePool()
}
// Normally, if this one is set, Options.Servers should not be,
// but we always allowed that, so continue to do so.
if nc.Opts.Url != _EMPTY_ {
// Add to the end of the array
if err := nc.addURLToPool(nc.Opts.Url, false, false); err != nil {
return err
}
// Then swap it with first to guarantee that Options.Url is tried first.
last := len(nc.srvPool) - 1
if last > 0 {
nc.srvPool[0], nc.srvPool[last] = nc.srvPool[last], nc.srvPool[0]
}
} else if len(nc.srvPool) <= 0 {
// Place default URL if pool is empty.
if err := nc.addURLToPool(DefaultURL, false, false); err != nil {
return err
}
}
// Check for Scheme hint to move to TLS mode.
for _, srv := range nc.srvPool {
if srv.url.Scheme == tlsScheme {
// FIXME(dlc), this is for all in the pool, should be case by case.
nc.Opts.Secure = true
if nc.Opts.TLSConfig == nil {
nc.Opts.TLSConfig = &tls.Config{MinVersion: tls.VersionTLS12}
}
}
}
return nc.pickServer()
} | go | func (nc *Conn) setupServerPool() error {
nc.srvPool = make([]*srv, 0, srvPoolSize)
nc.urls = make(map[string]struct{}, srvPoolSize)
// Create srv objects from each url string in nc.Opts.Servers
// and add them to the pool.
for _, urlString := range nc.Opts.Servers {
if err := nc.addURLToPool(urlString, false, false); err != nil {
return err
}
}
// Randomize if allowed to
if !nc.Opts.NoRandomize {
nc.shufflePool()
}
// Normally, if this one is set, Options.Servers should not be,
// but we always allowed that, so continue to do so.
if nc.Opts.Url != _EMPTY_ {
// Add to the end of the array
if err := nc.addURLToPool(nc.Opts.Url, false, false); err != nil {
return err
}
// Then swap it with first to guarantee that Options.Url is tried first.
last := len(nc.srvPool) - 1
if last > 0 {
nc.srvPool[0], nc.srvPool[last] = nc.srvPool[last], nc.srvPool[0]
}
} else if len(nc.srvPool) <= 0 {
// Place default URL if pool is empty.
if err := nc.addURLToPool(DefaultURL, false, false); err != nil {
return err
}
}
// Check for Scheme hint to move to TLS mode.
for _, srv := range nc.srvPool {
if srv.url.Scheme == tlsScheme {
// FIXME(dlc), this is for all in the pool, should be case by case.
nc.Opts.Secure = true
if nc.Opts.TLSConfig == nil {
nc.Opts.TLSConfig = &tls.Config{MinVersion: tls.VersionTLS12}
}
}
}
return nc.pickServer()
} | [
"func",
"(",
"nc",
"*",
"Conn",
")",
"setupServerPool",
"(",
")",
"error",
"{",
"nc",
".",
"srvPool",
"=",
"make",
"(",
"[",
"]",
"*",
"srv",
",",
"0",
",",
"srvPoolSize",
")",
"\n",
"nc",
".",
"urls",
"=",
"make",
"(",
"map",
"[",
"string",
"]",
"struct",
"{",
"}",
",",
"srvPoolSize",
")",
"\n",
"for",
"_",
",",
"urlString",
":=",
"range",
"nc",
".",
"Opts",
".",
"Servers",
"{",
"if",
"err",
":=",
"nc",
".",
"addURLToPool",
"(",
"urlString",
",",
"false",
",",
"false",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"}",
"\n",
"if",
"!",
"nc",
".",
"Opts",
".",
"NoRandomize",
"{",
"nc",
".",
"shufflePool",
"(",
")",
"\n",
"}",
"\n",
"if",
"nc",
".",
"Opts",
".",
"Url",
"!=",
"_EMPTY_",
"{",
"if",
"err",
":=",
"nc",
".",
"addURLToPool",
"(",
"nc",
".",
"Opts",
".",
"Url",
",",
"false",
",",
"false",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"last",
":=",
"len",
"(",
"nc",
".",
"srvPool",
")",
"-",
"1",
"\n",
"if",
"last",
">",
"0",
"{",
"nc",
".",
"srvPool",
"[",
"0",
"]",
",",
"nc",
".",
"srvPool",
"[",
"last",
"]",
"=",
"nc",
".",
"srvPool",
"[",
"last",
"]",
",",
"nc",
".",
"srvPool",
"[",
"0",
"]",
"\n",
"}",
"\n",
"}",
"else",
"if",
"len",
"(",
"nc",
".",
"srvPool",
")",
"<=",
"0",
"{",
"if",
"err",
":=",
"nc",
".",
"addURLToPool",
"(",
"DefaultURL",
",",
"false",
",",
"false",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"}",
"\n",
"for",
"_",
",",
"srv",
":=",
"range",
"nc",
".",
"srvPool",
"{",
"if",
"srv",
".",
"url",
".",
"Scheme",
"==",
"tlsScheme",
"{",
"nc",
".",
"Opts",
".",
"Secure",
"=",
"true",
"\n",
"if",
"nc",
".",
"Opts",
".",
"TLSConfig",
"==",
"nil",
"{",
"nc",
".",
"Opts",
".",
"TLSConfig",
"=",
"&",
"tls",
".",
"Config",
"{",
"MinVersion",
":",
"tls",
".",
"VersionTLS12",
"}",
"\n",
"}",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"nc",
".",
"pickServer",
"(",
")",
"\n",
"}"
] | // Create the server pool using the options given.
// We will place a Url option first, followed by any
// Server Options. We will randomize the server pool unless
// the NoRandomize flag is set. | [
"Create",
"the",
"server",
"pool",
"using",
"the",
"options",
"given",
".",
"We",
"will",
"place",
"a",
"Url",
"option",
"first",
"followed",
"by",
"any",
"Server",
"Options",
".",
"We",
"will",
"randomize",
"the",
"server",
"pool",
"unless",
"the",
"NoRandomize",
"flag",
"is",
"set",
"."
] | 36d30b0ba7aa260ae25b4f3d312b2a700106fd78 | https://github.com/nats-io/go-nats/blob/36d30b0ba7aa260ae25b4f3d312b2a700106fd78/nats.go#L1051-L1099 | train |
nats-io/go-nats | nats.go | addURLToPool | func (nc *Conn) addURLToPool(sURL string, implicit, saveTLSName bool) error {
if !strings.Contains(sURL, "://") {
sURL = fmt.Sprintf("%s://%s", nc.connScheme(), sURL)
}
var (
u *url.URL
err error
)
for i := 0; i < 2; i++ {
u, err = url.Parse(sURL)
if err != nil {
return err
}
if u.Port() != "" {
break
}
// In case given URL is of the form "localhost:", just add
// the port number at the end, otherwise, add ":4222".
if sURL[len(sURL)-1] != ':' {
sURL += ":"
}
sURL += defaultPortString
}
var tlsName string
if implicit {
curl := nc.current.url
// Check to see if we do not have a url.User but current connected
// url does. If so copy over.
if u.User == nil && curl.User != nil {
u.User = curl.User
}
// We are checking to see if we have a secure connection and are
// adding an implicit server that just has an IP. If so we will remember
// the current hostname we are connected to.
if saveTLSName && hostIsIP(u) {
tlsName = curl.Hostname()
}
}
s := &srv{url: u, isImplicit: implicit, tlsName: tlsName}
nc.srvPool = append(nc.srvPool, s)
nc.urls[u.Host] = struct{}{}
return nil
} | go | func (nc *Conn) addURLToPool(sURL string, implicit, saveTLSName bool) error {
if !strings.Contains(sURL, "://") {
sURL = fmt.Sprintf("%s://%s", nc.connScheme(), sURL)
}
var (
u *url.URL
err error
)
for i := 0; i < 2; i++ {
u, err = url.Parse(sURL)
if err != nil {
return err
}
if u.Port() != "" {
break
}
// In case given URL is of the form "localhost:", just add
// the port number at the end, otherwise, add ":4222".
if sURL[len(sURL)-1] != ':' {
sURL += ":"
}
sURL += defaultPortString
}
var tlsName string
if implicit {
curl := nc.current.url
// Check to see if we do not have a url.User but current connected
// url does. If so copy over.
if u.User == nil && curl.User != nil {
u.User = curl.User
}
// We are checking to see if we have a secure connection and are
// adding an implicit server that just has an IP. If so we will remember
// the current hostname we are connected to.
if saveTLSName && hostIsIP(u) {
tlsName = curl.Hostname()
}
}
s := &srv{url: u, isImplicit: implicit, tlsName: tlsName}
nc.srvPool = append(nc.srvPool, s)
nc.urls[u.Host] = struct{}{}
return nil
} | [
"func",
"(",
"nc",
"*",
"Conn",
")",
"addURLToPool",
"(",
"sURL",
"string",
",",
"implicit",
",",
"saveTLSName",
"bool",
")",
"error",
"{",
"if",
"!",
"strings",
".",
"Contains",
"(",
"sURL",
",",
"\"://\"",
")",
"{",
"sURL",
"=",
"fmt",
".",
"Sprintf",
"(",
"\"%s://%s\"",
",",
"nc",
".",
"connScheme",
"(",
")",
",",
"sURL",
")",
"\n",
"}",
"\n",
"var",
"(",
"u",
"*",
"url",
".",
"URL",
"\n",
"err",
"error",
"\n",
")",
"\n",
"for",
"i",
":=",
"0",
";",
"i",
"<",
"2",
";",
"i",
"++",
"{",
"u",
",",
"err",
"=",
"url",
".",
"Parse",
"(",
"sURL",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"if",
"u",
".",
"Port",
"(",
")",
"!=",
"\"\"",
"{",
"break",
"\n",
"}",
"\n",
"if",
"sURL",
"[",
"len",
"(",
"sURL",
")",
"-",
"1",
"]",
"!=",
"':'",
"{",
"sURL",
"+=",
"\":\"",
"\n",
"}",
"\n",
"sURL",
"+=",
"defaultPortString",
"\n",
"}",
"\n",
"var",
"tlsName",
"string",
"\n",
"if",
"implicit",
"{",
"curl",
":=",
"nc",
".",
"current",
".",
"url",
"\n",
"if",
"u",
".",
"User",
"==",
"nil",
"&&",
"curl",
".",
"User",
"!=",
"nil",
"{",
"u",
".",
"User",
"=",
"curl",
".",
"User",
"\n",
"}",
"\n",
"if",
"saveTLSName",
"&&",
"hostIsIP",
"(",
"u",
")",
"{",
"tlsName",
"=",
"curl",
".",
"Hostname",
"(",
")",
"\n",
"}",
"\n",
"}",
"\n",
"s",
":=",
"&",
"srv",
"{",
"url",
":",
"u",
",",
"isImplicit",
":",
"implicit",
",",
"tlsName",
":",
"tlsName",
"}",
"\n",
"nc",
".",
"srvPool",
"=",
"append",
"(",
"nc",
".",
"srvPool",
",",
"s",
")",
"\n",
"nc",
".",
"urls",
"[",
"u",
".",
"Host",
"]",
"=",
"struct",
"{",
"}",
"{",
"}",
"\n",
"return",
"nil",
"\n",
"}"
] | // addURLToPool adds an entry to the server pool | [
"addURLToPool",
"adds",
"an",
"entry",
"to",
"the",
"server",
"pool"
] | 36d30b0ba7aa260ae25b4f3d312b2a700106fd78 | https://github.com/nats-io/go-nats/blob/36d30b0ba7aa260ae25b4f3d312b2a700106fd78/nats.go#L1115-L1159 | train |
nats-io/go-nats | nats.go | shufflePool | func (nc *Conn) shufflePool() {
if len(nc.srvPool) <= 1 {
return
}
source := rand.NewSource(time.Now().UnixNano())
r := rand.New(source)
for i := range nc.srvPool {
j := r.Intn(i + 1)
nc.srvPool[i], nc.srvPool[j] = nc.srvPool[j], nc.srvPool[i]
}
} | go | func (nc *Conn) shufflePool() {
if len(nc.srvPool) <= 1 {
return
}
source := rand.NewSource(time.Now().UnixNano())
r := rand.New(source)
for i := range nc.srvPool {
j := r.Intn(i + 1)
nc.srvPool[i], nc.srvPool[j] = nc.srvPool[j], nc.srvPool[i]
}
} | [
"func",
"(",
"nc",
"*",
"Conn",
")",
"shufflePool",
"(",
")",
"{",
"if",
"len",
"(",
"nc",
".",
"srvPool",
")",
"<=",
"1",
"{",
"return",
"\n",
"}",
"\n",
"source",
":=",
"rand",
".",
"NewSource",
"(",
"time",
".",
"Now",
"(",
")",
".",
"UnixNano",
"(",
")",
")",
"\n",
"r",
":=",
"rand",
".",
"New",
"(",
"source",
")",
"\n",
"for",
"i",
":=",
"range",
"nc",
".",
"srvPool",
"{",
"j",
":=",
"r",
".",
"Intn",
"(",
"i",
"+",
"1",
")",
"\n",
"nc",
".",
"srvPool",
"[",
"i",
"]",
",",
"nc",
".",
"srvPool",
"[",
"j",
"]",
"=",
"nc",
".",
"srvPool",
"[",
"j",
"]",
",",
"nc",
".",
"srvPool",
"[",
"i",
"]",
"\n",
"}",
"\n",
"}"
] | // shufflePool swaps randomly elements in the server pool | [
"shufflePool",
"swaps",
"randomly",
"elements",
"in",
"the",
"server",
"pool"
] | 36d30b0ba7aa260ae25b4f3d312b2a700106fd78 | https://github.com/nats-io/go-nats/blob/36d30b0ba7aa260ae25b4f3d312b2a700106fd78/nats.go#L1162-L1172 | train |
nats-io/go-nats | nats.go | createConn | func (nc *Conn) createConn() (err error) {
if nc.Opts.Timeout < 0 {
return ErrBadTimeout
}
if _, cur := nc.currentServer(); cur == nil {
return ErrNoServers
} else {
cur.lastAttempt = time.Now()
}
// We will auto-expand host names if they resolve to multiple IPs
hosts := []string{}
u := nc.current.url
if net.ParseIP(u.Hostname()) == nil {
addrs, _ := net.LookupHost(u.Hostname())
for _, addr := range addrs {
hosts = append(hosts, net.JoinHostPort(addr, u.Port()))
}
}
// Fall back to what we were given.
if len(hosts) == 0 {
hosts = append(hosts, u.Host)
}
// CustomDialer takes precedence. If not set, use Opts.Dialer which
// is set to a default *net.Dialer (in Connect()) if not explicitly
// set by the user.
dialer := nc.Opts.CustomDialer
if dialer == nil {
// We will copy and shorten the timeout if we have multiple hosts to try.
copyDialer := *nc.Opts.Dialer
copyDialer.Timeout = copyDialer.Timeout / time.Duration(len(hosts))
dialer = ©Dialer
}
if len(hosts) > 1 && !nc.Opts.NoRandomize {
rand.Shuffle(len(hosts), func(i, j int) {
hosts[i], hosts[j] = hosts[j], hosts[i]
})
}
for _, host := range hosts {
nc.conn, err = dialer.Dial("tcp", host)
if err == nil {
break
}
}
if err != nil {
return err
}
// No clue why, but this stalls and kills performance on Mac (Mavericks).
// https://code.google.com/p/go/issues/detail?id=6930
//if ip, ok := nc.conn.(*net.TCPConn); ok {
// ip.SetReadBuffer(defaultBufSize)
//}
if nc.pending != nil && nc.bw != nil {
// Move to pending buffer.
nc.bw.Flush()
}
nc.bw = nc.newBuffer()
return nil
} | go | func (nc *Conn) createConn() (err error) {
if nc.Opts.Timeout < 0 {
return ErrBadTimeout
}
if _, cur := nc.currentServer(); cur == nil {
return ErrNoServers
} else {
cur.lastAttempt = time.Now()
}
// We will auto-expand host names if they resolve to multiple IPs
hosts := []string{}
u := nc.current.url
if net.ParseIP(u.Hostname()) == nil {
addrs, _ := net.LookupHost(u.Hostname())
for _, addr := range addrs {
hosts = append(hosts, net.JoinHostPort(addr, u.Port()))
}
}
// Fall back to what we were given.
if len(hosts) == 0 {
hosts = append(hosts, u.Host)
}
// CustomDialer takes precedence. If not set, use Opts.Dialer which
// is set to a default *net.Dialer (in Connect()) if not explicitly
// set by the user.
dialer := nc.Opts.CustomDialer
if dialer == nil {
// We will copy and shorten the timeout if we have multiple hosts to try.
copyDialer := *nc.Opts.Dialer
copyDialer.Timeout = copyDialer.Timeout / time.Duration(len(hosts))
dialer = ©Dialer
}
if len(hosts) > 1 && !nc.Opts.NoRandomize {
rand.Shuffle(len(hosts), func(i, j int) {
hosts[i], hosts[j] = hosts[j], hosts[i]
})
}
for _, host := range hosts {
nc.conn, err = dialer.Dial("tcp", host)
if err == nil {
break
}
}
if err != nil {
return err
}
// No clue why, but this stalls and kills performance on Mac (Mavericks).
// https://code.google.com/p/go/issues/detail?id=6930
//if ip, ok := nc.conn.(*net.TCPConn); ok {
// ip.SetReadBuffer(defaultBufSize)
//}
if nc.pending != nil && nc.bw != nil {
// Move to pending buffer.
nc.bw.Flush()
}
nc.bw = nc.newBuffer()
return nil
} | [
"func",
"(",
"nc",
"*",
"Conn",
")",
"createConn",
"(",
")",
"(",
"err",
"error",
")",
"{",
"if",
"nc",
".",
"Opts",
".",
"Timeout",
"<",
"0",
"{",
"return",
"ErrBadTimeout",
"\n",
"}",
"\n",
"if",
"_",
",",
"cur",
":=",
"nc",
".",
"currentServer",
"(",
")",
";",
"cur",
"==",
"nil",
"{",
"return",
"ErrNoServers",
"\n",
"}",
"else",
"{",
"cur",
".",
"lastAttempt",
"=",
"time",
".",
"Now",
"(",
")",
"\n",
"}",
"\n",
"hosts",
":=",
"[",
"]",
"string",
"{",
"}",
"\n",
"u",
":=",
"nc",
".",
"current",
".",
"url",
"\n",
"if",
"net",
".",
"ParseIP",
"(",
"u",
".",
"Hostname",
"(",
")",
")",
"==",
"nil",
"{",
"addrs",
",",
"_",
":=",
"net",
".",
"LookupHost",
"(",
"u",
".",
"Hostname",
"(",
")",
")",
"\n",
"for",
"_",
",",
"addr",
":=",
"range",
"addrs",
"{",
"hosts",
"=",
"append",
"(",
"hosts",
",",
"net",
".",
"JoinHostPort",
"(",
"addr",
",",
"u",
".",
"Port",
"(",
")",
")",
")",
"\n",
"}",
"\n",
"}",
"\n",
"if",
"len",
"(",
"hosts",
")",
"==",
"0",
"{",
"hosts",
"=",
"append",
"(",
"hosts",
",",
"u",
".",
"Host",
")",
"\n",
"}",
"\n",
"dialer",
":=",
"nc",
".",
"Opts",
".",
"CustomDialer",
"\n",
"if",
"dialer",
"==",
"nil",
"{",
"copyDialer",
":=",
"*",
"nc",
".",
"Opts",
".",
"Dialer",
"\n",
"copyDialer",
".",
"Timeout",
"=",
"copyDialer",
".",
"Timeout",
"/",
"time",
".",
"Duration",
"(",
"len",
"(",
"hosts",
")",
")",
"\n",
"dialer",
"=",
"&",
"copyDialer",
"\n",
"}",
"\n",
"if",
"len",
"(",
"hosts",
")",
">",
"1",
"&&",
"!",
"nc",
".",
"Opts",
".",
"NoRandomize",
"{",
"rand",
".",
"Shuffle",
"(",
"len",
"(",
"hosts",
")",
",",
"func",
"(",
"i",
",",
"j",
"int",
")",
"{",
"hosts",
"[",
"i",
"]",
",",
"hosts",
"[",
"j",
"]",
"=",
"hosts",
"[",
"j",
"]",
",",
"hosts",
"[",
"i",
"]",
"\n",
"}",
")",
"\n",
"}",
"\n",
"for",
"_",
",",
"host",
":=",
"range",
"hosts",
"{",
"nc",
".",
"conn",
",",
"err",
"=",
"dialer",
".",
"Dial",
"(",
"\"tcp\"",
",",
"host",
")",
"\n",
"if",
"err",
"==",
"nil",
"{",
"break",
"\n",
"}",
"\n",
"}",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"if",
"nc",
".",
"pending",
"!=",
"nil",
"&&",
"nc",
".",
"bw",
"!=",
"nil",
"{",
"nc",
".",
"bw",
".",
"Flush",
"(",
")",
"\n",
"}",
"\n",
"nc",
".",
"bw",
"=",
"nc",
".",
"newBuffer",
"(",
")",
"\n",
"return",
"nil",
"\n",
"}"
] | // createConn will connect to the server and wrap the appropriate
// bufio structures. It will do the right thing when an existing
// connection is in place. | [
"createConn",
"will",
"connect",
"to",
"the",
"server",
"and",
"wrap",
"the",
"appropriate",
"bufio",
"structures",
".",
"It",
"will",
"do",
"the",
"right",
"thing",
"when",
"an",
"existing",
"connection",
"is",
"in",
"place",
"."
] | 36d30b0ba7aa260ae25b4f3d312b2a700106fd78 | https://github.com/nats-io/go-nats/blob/36d30b0ba7aa260ae25b4f3d312b2a700106fd78/nats.go#L1185-L1248 | train |
nats-io/go-nats | nats.go | makeTLSConn | func (nc *Conn) makeTLSConn() error {
// Allow the user to configure their own tls.Config structure.
var tlsCopy *tls.Config
if nc.Opts.TLSConfig != nil {
tlsCopy = util.CloneTLSConfig(nc.Opts.TLSConfig)
} else {
tlsCopy = &tls.Config{}
}
// If its blank we will override it with the current host
if tlsCopy.ServerName == _EMPTY_ {
if nc.current.tlsName != _EMPTY_ {
tlsCopy.ServerName = nc.current.tlsName
} else {
h, _, _ := net.SplitHostPort(nc.current.url.Host)
tlsCopy.ServerName = h
}
}
nc.conn = tls.Client(nc.conn, tlsCopy)
conn := nc.conn.(*tls.Conn)
if err := conn.Handshake(); err != nil {
return err
}
nc.bw = nc.newBuffer()
return nil
} | go | func (nc *Conn) makeTLSConn() error {
// Allow the user to configure their own tls.Config structure.
var tlsCopy *tls.Config
if nc.Opts.TLSConfig != nil {
tlsCopy = util.CloneTLSConfig(nc.Opts.TLSConfig)
} else {
tlsCopy = &tls.Config{}
}
// If its blank we will override it with the current host
if tlsCopy.ServerName == _EMPTY_ {
if nc.current.tlsName != _EMPTY_ {
tlsCopy.ServerName = nc.current.tlsName
} else {
h, _, _ := net.SplitHostPort(nc.current.url.Host)
tlsCopy.ServerName = h
}
}
nc.conn = tls.Client(nc.conn, tlsCopy)
conn := nc.conn.(*tls.Conn)
if err := conn.Handshake(); err != nil {
return err
}
nc.bw = nc.newBuffer()
return nil
} | [
"func",
"(",
"nc",
"*",
"Conn",
")",
"makeTLSConn",
"(",
")",
"error",
"{",
"var",
"tlsCopy",
"*",
"tls",
".",
"Config",
"\n",
"if",
"nc",
".",
"Opts",
".",
"TLSConfig",
"!=",
"nil",
"{",
"tlsCopy",
"=",
"util",
".",
"CloneTLSConfig",
"(",
"nc",
".",
"Opts",
".",
"TLSConfig",
")",
"\n",
"}",
"else",
"{",
"tlsCopy",
"=",
"&",
"tls",
".",
"Config",
"{",
"}",
"\n",
"}",
"\n",
"if",
"tlsCopy",
".",
"ServerName",
"==",
"_EMPTY_",
"{",
"if",
"nc",
".",
"current",
".",
"tlsName",
"!=",
"_EMPTY_",
"{",
"tlsCopy",
".",
"ServerName",
"=",
"nc",
".",
"current",
".",
"tlsName",
"\n",
"}",
"else",
"{",
"h",
",",
"_",
",",
"_",
":=",
"net",
".",
"SplitHostPort",
"(",
"nc",
".",
"current",
".",
"url",
".",
"Host",
")",
"\n",
"tlsCopy",
".",
"ServerName",
"=",
"h",
"\n",
"}",
"\n",
"}",
"\n",
"nc",
".",
"conn",
"=",
"tls",
".",
"Client",
"(",
"nc",
".",
"conn",
",",
"tlsCopy",
")",
"\n",
"conn",
":=",
"nc",
".",
"conn",
".",
"(",
"*",
"tls",
".",
"Conn",
")",
"\n",
"if",
"err",
":=",
"conn",
".",
"Handshake",
"(",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"nc",
".",
"bw",
"=",
"nc",
".",
"newBuffer",
"(",
")",
"\n",
"return",
"nil",
"\n",
"}"
] | // makeTLSConn will wrap an existing Conn using TLS | [
"makeTLSConn",
"will",
"wrap",
"an",
"existing",
"Conn",
"using",
"TLS"
] | 36d30b0ba7aa260ae25b4f3d312b2a700106fd78 | https://github.com/nats-io/go-nats/blob/36d30b0ba7aa260ae25b4f3d312b2a700106fd78/nats.go#L1251-L1275 | train |
nats-io/go-nats | nats.go | ConnectedUrl | func (nc *Conn) ConnectedUrl() string {
if nc == nil {
return _EMPTY_
}
nc.mu.RLock()
defer nc.mu.RUnlock()
if nc.status != CONNECTED {
return _EMPTY_
}
return nc.current.url.String()
} | go | func (nc *Conn) ConnectedUrl() string {
if nc == nil {
return _EMPTY_
}
nc.mu.RLock()
defer nc.mu.RUnlock()
if nc.status != CONNECTED {
return _EMPTY_
}
return nc.current.url.String()
} | [
"func",
"(",
"nc",
"*",
"Conn",
")",
"ConnectedUrl",
"(",
")",
"string",
"{",
"if",
"nc",
"==",
"nil",
"{",
"return",
"_EMPTY_",
"\n",
"}",
"\n",
"nc",
".",
"mu",
".",
"RLock",
"(",
")",
"\n",
"defer",
"nc",
".",
"mu",
".",
"RUnlock",
"(",
")",
"\n",
"if",
"nc",
".",
"status",
"!=",
"CONNECTED",
"{",
"return",
"_EMPTY_",
"\n",
"}",
"\n",
"return",
"nc",
".",
"current",
".",
"url",
".",
"String",
"(",
")",
"\n",
"}"
] | // Report the connected server's Url | [
"Report",
"the",
"connected",
"server",
"s",
"Url"
] | 36d30b0ba7aa260ae25b4f3d312b2a700106fd78 | https://github.com/nats-io/go-nats/blob/36d30b0ba7aa260ae25b4f3d312b2a700106fd78/nats.go#L1291-L1303 | train |
nats-io/go-nats | nats.go | ConnectedAddr | func (nc *Conn) ConnectedAddr() string {
if nc == nil {
return _EMPTY_
}
nc.mu.RLock()
defer nc.mu.RUnlock()
if nc.status != CONNECTED {
return _EMPTY_
}
return nc.conn.RemoteAddr().String()
} | go | func (nc *Conn) ConnectedAddr() string {
if nc == nil {
return _EMPTY_
}
nc.mu.RLock()
defer nc.mu.RUnlock()
if nc.status != CONNECTED {
return _EMPTY_
}
return nc.conn.RemoteAddr().String()
} | [
"func",
"(",
"nc",
"*",
"Conn",
")",
"ConnectedAddr",
"(",
")",
"string",
"{",
"if",
"nc",
"==",
"nil",
"{",
"return",
"_EMPTY_",
"\n",
"}",
"\n",
"nc",
".",
"mu",
".",
"RLock",
"(",
")",
"\n",
"defer",
"nc",
".",
"mu",
".",
"RUnlock",
"(",
")",
"\n",
"if",
"nc",
".",
"status",
"!=",
"CONNECTED",
"{",
"return",
"_EMPTY_",
"\n",
"}",
"\n",
"return",
"nc",
".",
"conn",
".",
"RemoteAddr",
"(",
")",
".",
"String",
"(",
")",
"\n",
"}"
] | // ConnectedAddr returns the connected server's IP | [
"ConnectedAddr",
"returns",
"the",
"connected",
"server",
"s",
"IP"
] | 36d30b0ba7aa260ae25b4f3d312b2a700106fd78 | https://github.com/nats-io/go-nats/blob/36d30b0ba7aa260ae25b4f3d312b2a700106fd78/nats.go#L1306-L1318 | train |
nats-io/go-nats | nats.go | ConnectedServerId | func (nc *Conn) ConnectedServerId() string {
if nc == nil {
return _EMPTY_
}
nc.mu.RLock()
defer nc.mu.RUnlock()
if nc.status != CONNECTED {
return _EMPTY_
}
return nc.info.Id
} | go | func (nc *Conn) ConnectedServerId() string {
if nc == nil {
return _EMPTY_
}
nc.mu.RLock()
defer nc.mu.RUnlock()
if nc.status != CONNECTED {
return _EMPTY_
}
return nc.info.Id
} | [
"func",
"(",
"nc",
"*",
"Conn",
")",
"ConnectedServerId",
"(",
")",
"string",
"{",
"if",
"nc",
"==",
"nil",
"{",
"return",
"_EMPTY_",
"\n",
"}",
"\n",
"nc",
".",
"mu",
".",
"RLock",
"(",
")",
"\n",
"defer",
"nc",
".",
"mu",
".",
"RUnlock",
"(",
")",
"\n",
"if",
"nc",
".",
"status",
"!=",
"CONNECTED",
"{",
"return",
"_EMPTY_",
"\n",
"}",
"\n",
"return",
"nc",
".",
"info",
".",
"Id",
"\n",
"}"
] | // Report the connected server's Id | [
"Report",
"the",
"connected",
"server",
"s",
"Id"
] | 36d30b0ba7aa260ae25b4f3d312b2a700106fd78 | https://github.com/nats-io/go-nats/blob/36d30b0ba7aa260ae25b4f3d312b2a700106fd78/nats.go#L1321-L1333 | train |
nats-io/go-nats | nats.go | setup | func (nc *Conn) setup() {
nc.subs = make(map[int64]*Subscription)
nc.pongs = make([]chan struct{}, 0, 8)
nc.fch = make(chan struct{}, flushChanSize)
// Setup scratch outbound buffer for PUB
pub := nc.scratch[:len(_PUB_P_)]
copy(pub, _PUB_P_)
} | go | func (nc *Conn) setup() {
nc.subs = make(map[int64]*Subscription)
nc.pongs = make([]chan struct{}, 0, 8)
nc.fch = make(chan struct{}, flushChanSize)
// Setup scratch outbound buffer for PUB
pub := nc.scratch[:len(_PUB_P_)]
copy(pub, _PUB_P_)
} | [
"func",
"(",
"nc",
"*",
"Conn",
")",
"setup",
"(",
")",
"{",
"nc",
".",
"subs",
"=",
"make",
"(",
"map",
"[",
"int64",
"]",
"*",
"Subscription",
")",
"\n",
"nc",
".",
"pongs",
"=",
"make",
"(",
"[",
"]",
"chan",
"struct",
"{",
"}",
",",
"0",
",",
"8",
")",
"\n",
"nc",
".",
"fch",
"=",
"make",
"(",
"chan",
"struct",
"{",
"}",
",",
"flushChanSize",
")",
"\n",
"pub",
":=",
"nc",
".",
"scratch",
"[",
":",
"len",
"(",
"_PUB_P_",
")",
"]",
"\n",
"copy",
"(",
"pub",
",",
"_PUB_P_",
")",
"\n",
"}"
] | // Low level setup for structs, etc | [
"Low",
"level",
"setup",
"for",
"structs",
"etc"
] | 36d30b0ba7aa260ae25b4f3d312b2a700106fd78 | https://github.com/nats-io/go-nats/blob/36d30b0ba7aa260ae25b4f3d312b2a700106fd78/nats.go#L1336-L1345 | train |
nats-io/go-nats | nats.go | processConnectInit | func (nc *Conn) processConnectInit() error {
// Set our deadline for the whole connect process
nc.conn.SetDeadline(time.Now().Add(nc.Opts.Timeout))
defer nc.conn.SetDeadline(time.Time{})
// Set our status to connecting.
nc.status = CONNECTING
// Process the INFO protocol received from the server
err := nc.processExpectedInfo()
if err != nil {
return err
}
// Send the CONNECT protocol along with the initial PING protocol.
// Wait for the PONG response (or any error that we get from the server).
err = nc.sendConnect()
if err != nil {
return err
}
// Reset the number of PING sent out
nc.pout = 0
// Start or reset Timer
if nc.Opts.PingInterval > 0 {
if nc.ptmr == nil {
nc.ptmr = time.AfterFunc(nc.Opts.PingInterval, nc.processPingTimer)
} else {
nc.ptmr.Reset(nc.Opts.PingInterval)
}
}
// Start the readLoop and flusher go routines, we will wait on both on a reconnect event.
nc.wg.Add(2)
go nc.readLoop()
go nc.flusher()
return nil
} | go | func (nc *Conn) processConnectInit() error {
// Set our deadline for the whole connect process
nc.conn.SetDeadline(time.Now().Add(nc.Opts.Timeout))
defer nc.conn.SetDeadline(time.Time{})
// Set our status to connecting.
nc.status = CONNECTING
// Process the INFO protocol received from the server
err := nc.processExpectedInfo()
if err != nil {
return err
}
// Send the CONNECT protocol along with the initial PING protocol.
// Wait for the PONG response (or any error that we get from the server).
err = nc.sendConnect()
if err != nil {
return err
}
// Reset the number of PING sent out
nc.pout = 0
// Start or reset Timer
if nc.Opts.PingInterval > 0 {
if nc.ptmr == nil {
nc.ptmr = time.AfterFunc(nc.Opts.PingInterval, nc.processPingTimer)
} else {
nc.ptmr.Reset(nc.Opts.PingInterval)
}
}
// Start the readLoop and flusher go routines, we will wait on both on a reconnect event.
nc.wg.Add(2)
go nc.readLoop()
go nc.flusher()
return nil
} | [
"func",
"(",
"nc",
"*",
"Conn",
")",
"processConnectInit",
"(",
")",
"error",
"{",
"nc",
".",
"conn",
".",
"SetDeadline",
"(",
"time",
".",
"Now",
"(",
")",
".",
"Add",
"(",
"nc",
".",
"Opts",
".",
"Timeout",
")",
")",
"\n",
"defer",
"nc",
".",
"conn",
".",
"SetDeadline",
"(",
"time",
".",
"Time",
"{",
"}",
")",
"\n",
"nc",
".",
"status",
"=",
"CONNECTING",
"\n",
"err",
":=",
"nc",
".",
"processExpectedInfo",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"err",
"=",
"nc",
".",
"sendConnect",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"nc",
".",
"pout",
"=",
"0",
"\n",
"if",
"nc",
".",
"Opts",
".",
"PingInterval",
">",
"0",
"{",
"if",
"nc",
".",
"ptmr",
"==",
"nil",
"{",
"nc",
".",
"ptmr",
"=",
"time",
".",
"AfterFunc",
"(",
"nc",
".",
"Opts",
".",
"PingInterval",
",",
"nc",
".",
"processPingTimer",
")",
"\n",
"}",
"else",
"{",
"nc",
".",
"ptmr",
".",
"Reset",
"(",
"nc",
".",
"Opts",
".",
"PingInterval",
")",
"\n",
"}",
"\n",
"}",
"\n",
"nc",
".",
"wg",
".",
"Add",
"(",
"2",
")",
"\n",
"go",
"nc",
".",
"readLoop",
"(",
")",
"\n",
"go",
"nc",
".",
"flusher",
"(",
")",
"\n",
"return",
"nil",
"\n",
"}"
] | // Process a connected connection and initialize properly. | [
"Process",
"a",
"connected",
"connection",
"and",
"initialize",
"properly",
"."
] | 36d30b0ba7aa260ae25b4f3d312b2a700106fd78 | https://github.com/nats-io/go-nats/blob/36d30b0ba7aa260ae25b4f3d312b2a700106fd78/nats.go#L1348-L1388 | train |
nats-io/go-nats | nats.go | connect | func (nc *Conn) connect() error {
var returnedErr error
// Create actual socket connection
// For first connect we walk all servers in the pool and try
// to connect immediately.
nc.mu.Lock()
nc.initc = true
// The pool may change inside the loop iteration due to INFO protocol.
for i := 0; i < len(nc.srvPool); i++ {
nc.current = nc.srvPool[i]
if err := nc.createConn(); err == nil {
// This was moved out of processConnectInit() because
// that function is now invoked from doReconnect() too.
nc.setup()
err = nc.processConnectInit()
if err == nil {
nc.srvPool[i].didConnect = true
nc.srvPool[i].reconnects = 0
returnedErr = nil
break
} else {
returnedErr = err
nc.mu.Unlock()
nc.close(DISCONNECTED, false)
nc.mu.Lock()
nc.current = nil
}
} else {
// Cancel out default connection refused, will trigger the
// No servers error conditional
if strings.Contains(err.Error(), "connection refused") {
returnedErr = nil
}
}
}
nc.initc = false
if returnedErr == nil && nc.status != CONNECTED {
returnedErr = ErrNoServers
}
nc.mu.Unlock()
return returnedErr
} | go | func (nc *Conn) connect() error {
var returnedErr error
// Create actual socket connection
// For first connect we walk all servers in the pool and try
// to connect immediately.
nc.mu.Lock()
nc.initc = true
// The pool may change inside the loop iteration due to INFO protocol.
for i := 0; i < len(nc.srvPool); i++ {
nc.current = nc.srvPool[i]
if err := nc.createConn(); err == nil {
// This was moved out of processConnectInit() because
// that function is now invoked from doReconnect() too.
nc.setup()
err = nc.processConnectInit()
if err == nil {
nc.srvPool[i].didConnect = true
nc.srvPool[i].reconnects = 0
returnedErr = nil
break
} else {
returnedErr = err
nc.mu.Unlock()
nc.close(DISCONNECTED, false)
nc.mu.Lock()
nc.current = nil
}
} else {
// Cancel out default connection refused, will trigger the
// No servers error conditional
if strings.Contains(err.Error(), "connection refused") {
returnedErr = nil
}
}
}
nc.initc = false
if returnedErr == nil && nc.status != CONNECTED {
returnedErr = ErrNoServers
}
nc.mu.Unlock()
return returnedErr
} | [
"func",
"(",
"nc",
"*",
"Conn",
")",
"connect",
"(",
")",
"error",
"{",
"var",
"returnedErr",
"error",
"\n",
"nc",
".",
"mu",
".",
"Lock",
"(",
")",
"\n",
"nc",
".",
"initc",
"=",
"true",
"\n",
"for",
"i",
":=",
"0",
";",
"i",
"<",
"len",
"(",
"nc",
".",
"srvPool",
")",
";",
"i",
"++",
"{",
"nc",
".",
"current",
"=",
"nc",
".",
"srvPool",
"[",
"i",
"]",
"\n",
"if",
"err",
":=",
"nc",
".",
"createConn",
"(",
")",
";",
"err",
"==",
"nil",
"{",
"nc",
".",
"setup",
"(",
")",
"\n",
"err",
"=",
"nc",
".",
"processConnectInit",
"(",
")",
"\n",
"if",
"err",
"==",
"nil",
"{",
"nc",
".",
"srvPool",
"[",
"i",
"]",
".",
"didConnect",
"=",
"true",
"\n",
"nc",
".",
"srvPool",
"[",
"i",
"]",
".",
"reconnects",
"=",
"0",
"\n",
"returnedErr",
"=",
"nil",
"\n",
"break",
"\n",
"}",
"else",
"{",
"returnedErr",
"=",
"err",
"\n",
"nc",
".",
"mu",
".",
"Unlock",
"(",
")",
"\n",
"nc",
".",
"close",
"(",
"DISCONNECTED",
",",
"false",
")",
"\n",
"nc",
".",
"mu",
".",
"Lock",
"(",
")",
"\n",
"nc",
".",
"current",
"=",
"nil",
"\n",
"}",
"\n",
"}",
"else",
"{",
"if",
"strings",
".",
"Contains",
"(",
"err",
".",
"Error",
"(",
")",
",",
"\"connection refused\"",
")",
"{",
"returnedErr",
"=",
"nil",
"\n",
"}",
"\n",
"}",
"\n",
"}",
"\n",
"nc",
".",
"initc",
"=",
"false",
"\n",
"if",
"returnedErr",
"==",
"nil",
"&&",
"nc",
".",
"status",
"!=",
"CONNECTED",
"{",
"returnedErr",
"=",
"ErrNoServers",
"\n",
"}",
"\n",
"nc",
".",
"mu",
".",
"Unlock",
"(",
")",
"\n",
"return",
"returnedErr",
"\n",
"}"
] | // Main connect function. Will connect to the nats-server | [
"Main",
"connect",
"function",
".",
"Will",
"connect",
"to",
"the",
"nats",
"-",
"server"
] | 36d30b0ba7aa260ae25b4f3d312b2a700106fd78 | https://github.com/nats-io/go-nats/blob/36d30b0ba7aa260ae25b4f3d312b2a700106fd78/nats.go#L1391-L1436 | train |
nats-io/go-nats | nats.go | checkForSecure | func (nc *Conn) checkForSecure() error {
// Check to see if we need to engage TLS
o := nc.Opts
// Check for mismatch in setups
if o.Secure && !nc.info.TLSRequired {
return ErrSecureConnWanted
} else if nc.info.TLSRequired && !o.Secure {
// Switch to Secure since server needs TLS.
o.Secure = true
}
// Need to rewrap with bufio
if o.Secure {
if err := nc.makeTLSConn(); err != nil {
return err
}
}
return nil
} | go | func (nc *Conn) checkForSecure() error {
// Check to see if we need to engage TLS
o := nc.Opts
// Check for mismatch in setups
if o.Secure && !nc.info.TLSRequired {
return ErrSecureConnWanted
} else if nc.info.TLSRequired && !o.Secure {
// Switch to Secure since server needs TLS.
o.Secure = true
}
// Need to rewrap with bufio
if o.Secure {
if err := nc.makeTLSConn(); err != nil {
return err
}
}
return nil
} | [
"func",
"(",
"nc",
"*",
"Conn",
")",
"checkForSecure",
"(",
")",
"error",
"{",
"o",
":=",
"nc",
".",
"Opts",
"\n",
"if",
"o",
".",
"Secure",
"&&",
"!",
"nc",
".",
"info",
".",
"TLSRequired",
"{",
"return",
"ErrSecureConnWanted",
"\n",
"}",
"else",
"if",
"nc",
".",
"info",
".",
"TLSRequired",
"&&",
"!",
"o",
".",
"Secure",
"{",
"o",
".",
"Secure",
"=",
"true",
"\n",
"}",
"\n",
"if",
"o",
".",
"Secure",
"{",
"if",
"err",
":=",
"nc",
".",
"makeTLSConn",
"(",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}"
] | // This will check to see if the connection should be
// secure. This can be dictated from either end and should
// only be called after the INIT protocol has been received. | [
"This",
"will",
"check",
"to",
"see",
"if",
"the",
"connection",
"should",
"be",
"secure",
".",
"This",
"can",
"be",
"dictated",
"from",
"either",
"end",
"and",
"should",
"only",
"be",
"called",
"after",
"the",
"INIT",
"protocol",
"has",
"been",
"received",
"."
] | 36d30b0ba7aa260ae25b4f3d312b2a700106fd78 | https://github.com/nats-io/go-nats/blob/36d30b0ba7aa260ae25b4f3d312b2a700106fd78/nats.go#L1441-L1460 | train |
nats-io/go-nats | nats.go | processExpectedInfo | func (nc *Conn) processExpectedInfo() error {
c := &control{}
// Read the protocol
err := nc.readOp(c)
if err != nil {
return err
}
// The nats protocol should send INFO first always.
if c.op != _INFO_OP_ {
return ErrNoInfoReceived
}
// Parse the protocol
if err := nc.processInfo(c.args); err != nil {
return err
}
if nc.Opts.Nkey != "" && nc.info.Nonce == "" {
return ErrNkeysNotSupported
}
return nc.checkForSecure()
} | go | func (nc *Conn) processExpectedInfo() error {
c := &control{}
// Read the protocol
err := nc.readOp(c)
if err != nil {
return err
}
// The nats protocol should send INFO first always.
if c.op != _INFO_OP_ {
return ErrNoInfoReceived
}
// Parse the protocol
if err := nc.processInfo(c.args); err != nil {
return err
}
if nc.Opts.Nkey != "" && nc.info.Nonce == "" {
return ErrNkeysNotSupported
}
return nc.checkForSecure()
} | [
"func",
"(",
"nc",
"*",
"Conn",
")",
"processExpectedInfo",
"(",
")",
"error",
"{",
"c",
":=",
"&",
"control",
"{",
"}",
"\n",
"err",
":=",
"nc",
".",
"readOp",
"(",
"c",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"if",
"c",
".",
"op",
"!=",
"_INFO_OP_",
"{",
"return",
"ErrNoInfoReceived",
"\n",
"}",
"\n",
"if",
"err",
":=",
"nc",
".",
"processInfo",
"(",
"c",
".",
"args",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"if",
"nc",
".",
"Opts",
".",
"Nkey",
"!=",
"\"\"",
"&&",
"nc",
".",
"info",
".",
"Nonce",
"==",
"\"\"",
"{",
"return",
"ErrNkeysNotSupported",
"\n",
"}",
"\n",
"return",
"nc",
".",
"checkForSecure",
"(",
")",
"\n",
"}"
] | // processExpectedInfo will look for the expected first INFO message
// sent when a connection is established. The lock should be held entering. | [
"processExpectedInfo",
"will",
"look",
"for",
"the",
"expected",
"first",
"INFO",
"message",
"sent",
"when",
"a",
"connection",
"is",
"established",
".",
"The",
"lock",
"should",
"be",
"held",
"entering",
"."
] | 36d30b0ba7aa260ae25b4f3d312b2a700106fd78 | https://github.com/nats-io/go-nats/blob/36d30b0ba7aa260ae25b4f3d312b2a700106fd78/nats.go#L1464-L1489 | train |
nats-io/go-nats | nats.go | sendProto | func (nc *Conn) sendProto(proto string) {
nc.mu.Lock()
nc.bw.WriteString(proto)
nc.kickFlusher()
nc.mu.Unlock()
} | go | func (nc *Conn) sendProto(proto string) {
nc.mu.Lock()
nc.bw.WriteString(proto)
nc.kickFlusher()
nc.mu.Unlock()
} | [
"func",
"(",
"nc",
"*",
"Conn",
")",
"sendProto",
"(",
"proto",
"string",
")",
"{",
"nc",
".",
"mu",
".",
"Lock",
"(",
")",
"\n",
"nc",
".",
"bw",
".",
"WriteString",
"(",
"proto",
")",
"\n",
"nc",
".",
"kickFlusher",
"(",
")",
"\n",
"nc",
".",
"mu",
".",
"Unlock",
"(",
")",
"\n",
"}"
] | // Sends a protocol control message by queuing into the bufio writer
// and kicking the flush Go routine. These writes are protected. | [
"Sends",
"a",
"protocol",
"control",
"message",
"by",
"queuing",
"into",
"the",
"bufio",
"writer",
"and",
"kicking",
"the",
"flush",
"Go",
"routine",
".",
"These",
"writes",
"are",
"protected",
"."
] | 36d30b0ba7aa260ae25b4f3d312b2a700106fd78 | https://github.com/nats-io/go-nats/blob/36d30b0ba7aa260ae25b4f3d312b2a700106fd78/nats.go#L1493-L1498 | train |
nats-io/go-nats | nats.go | normalizeErr | func normalizeErr(line string) string {
s := strings.TrimSpace(strings.TrimPrefix(line, _ERR_OP_))
s = strings.TrimLeft(strings.TrimRight(s, "'"), "'")
return s
} | go | func normalizeErr(line string) string {
s := strings.TrimSpace(strings.TrimPrefix(line, _ERR_OP_))
s = strings.TrimLeft(strings.TrimRight(s, "'"), "'")
return s
} | [
"func",
"normalizeErr",
"(",
"line",
"string",
")",
"string",
"{",
"s",
":=",
"strings",
".",
"TrimSpace",
"(",
"strings",
".",
"TrimPrefix",
"(",
"line",
",",
"_ERR_OP_",
")",
")",
"\n",
"s",
"=",
"strings",
".",
"TrimLeft",
"(",
"strings",
".",
"TrimRight",
"(",
"s",
",",
"\"'\"",
")",
",",
"\"'\"",
")",
"\n",
"return",
"s",
"\n",
"}"
] | // normalizeErr removes the prefix -ERR, trim spaces and remove the quotes. | [
"normalizeErr",
"removes",
"the",
"prefix",
"-",
"ERR",
"trim",
"spaces",
"and",
"remove",
"the",
"quotes",
"."
] | 36d30b0ba7aa260ae25b4f3d312b2a700106fd78 | https://github.com/nats-io/go-nats/blob/36d30b0ba7aa260ae25b4f3d312b2a700106fd78/nats.go#L1572-L1576 | train |
nats-io/go-nats | nats.go | readProto | func (nc *Conn) readProto() (string, error) {
var (
_buf = [10]byte{}
buf = _buf[:0]
b = [1]byte{}
protoEnd = byte('\n')
)
for {
if _, err := nc.conn.Read(b[:1]); err != nil {
// Do not report EOF error
if err == io.EOF {
return string(buf), nil
}
return "", err
}
buf = append(buf, b[0])
if b[0] == protoEnd {
return string(buf), nil
}
}
} | go | func (nc *Conn) readProto() (string, error) {
var (
_buf = [10]byte{}
buf = _buf[:0]
b = [1]byte{}
protoEnd = byte('\n')
)
for {
if _, err := nc.conn.Read(b[:1]); err != nil {
// Do not report EOF error
if err == io.EOF {
return string(buf), nil
}
return "", err
}
buf = append(buf, b[0])
if b[0] == protoEnd {
return string(buf), nil
}
}
} | [
"func",
"(",
"nc",
"*",
"Conn",
")",
"readProto",
"(",
")",
"(",
"string",
",",
"error",
")",
"{",
"var",
"(",
"_buf",
"=",
"[",
"10",
"]",
"byte",
"{",
"}",
"\n",
"buf",
"=",
"_buf",
"[",
":",
"0",
"]",
"\n",
"b",
"=",
"[",
"1",
"]",
"byte",
"{",
"}",
"\n",
"protoEnd",
"=",
"byte",
"(",
"'\\n'",
")",
"\n",
")",
"\n",
"for",
"{",
"if",
"_",
",",
"err",
":=",
"nc",
".",
"conn",
".",
"Read",
"(",
"b",
"[",
":",
"1",
"]",
")",
";",
"err",
"!=",
"nil",
"{",
"if",
"err",
"==",
"io",
".",
"EOF",
"{",
"return",
"string",
"(",
"buf",
")",
",",
"nil",
"\n",
"}",
"\n",
"return",
"\"\"",
",",
"err",
"\n",
"}",
"\n",
"buf",
"=",
"append",
"(",
"buf",
",",
"b",
"[",
"0",
"]",
")",
"\n",
"if",
"b",
"[",
"0",
"]",
"==",
"protoEnd",
"{",
"return",
"string",
"(",
"buf",
")",
",",
"nil",
"\n",
"}",
"\n",
"}",
"\n",
"}"
] | // reads a protocol one byte at a time. | [
"reads",
"a",
"protocol",
"one",
"byte",
"at",
"a",
"time",
"."
] | 36d30b0ba7aa260ae25b4f3d312b2a700106fd78 | https://github.com/nats-io/go-nats/blob/36d30b0ba7aa260ae25b4f3d312b2a700106fd78/nats.go#L1650-L1670 | train |
nats-io/go-nats | nats.go | readOp | func (nc *Conn) readOp(c *control) error {
br := bufio.NewReaderSize(nc.conn, defaultBufSize)
line, err := br.ReadString('\n')
if err != nil {
return err
}
parseControl(line, c)
return nil
} | go | func (nc *Conn) readOp(c *control) error {
br := bufio.NewReaderSize(nc.conn, defaultBufSize)
line, err := br.ReadString('\n')
if err != nil {
return err
}
parseControl(line, c)
return nil
} | [
"func",
"(",
"nc",
"*",
"Conn",
")",
"readOp",
"(",
"c",
"*",
"control",
")",
"error",
"{",
"br",
":=",
"bufio",
".",
"NewReaderSize",
"(",
"nc",
".",
"conn",
",",
"defaultBufSize",
")",
"\n",
"line",
",",
"err",
":=",
"br",
".",
"ReadString",
"(",
"'\\n'",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"parseControl",
"(",
"line",
",",
"c",
")",
"\n",
"return",
"nil",
"\n",
"}"
] | // Read a control line and process the intended op. | [
"Read",
"a",
"control",
"line",
"and",
"process",
"the",
"intended",
"op",
"."
] | 36d30b0ba7aa260ae25b4f3d312b2a700106fd78 | https://github.com/nats-io/go-nats/blob/36d30b0ba7aa260ae25b4f3d312b2a700106fd78/nats.go#L1678-L1686 | train |
nats-io/go-nats | nats.go | parseControl | func parseControl(line string, c *control) {
toks := strings.SplitN(line, _SPC_, 2)
if len(toks) == 1 {
c.op = strings.TrimSpace(toks[0])
c.args = _EMPTY_
} else if len(toks) == 2 {
c.op, c.args = strings.TrimSpace(toks[0]), strings.TrimSpace(toks[1])
} else {
c.op = _EMPTY_
}
} | go | func parseControl(line string, c *control) {
toks := strings.SplitN(line, _SPC_, 2)
if len(toks) == 1 {
c.op = strings.TrimSpace(toks[0])
c.args = _EMPTY_
} else if len(toks) == 2 {
c.op, c.args = strings.TrimSpace(toks[0]), strings.TrimSpace(toks[1])
} else {
c.op = _EMPTY_
}
} | [
"func",
"parseControl",
"(",
"line",
"string",
",",
"c",
"*",
"control",
")",
"{",
"toks",
":=",
"strings",
".",
"SplitN",
"(",
"line",
",",
"_SPC_",
",",
"2",
")",
"\n",
"if",
"len",
"(",
"toks",
")",
"==",
"1",
"{",
"c",
".",
"op",
"=",
"strings",
".",
"TrimSpace",
"(",
"toks",
"[",
"0",
"]",
")",
"\n",
"c",
".",
"args",
"=",
"_EMPTY_",
"\n",
"}",
"else",
"if",
"len",
"(",
"toks",
")",
"==",
"2",
"{",
"c",
".",
"op",
",",
"c",
".",
"args",
"=",
"strings",
".",
"TrimSpace",
"(",
"toks",
"[",
"0",
"]",
")",
",",
"strings",
".",
"TrimSpace",
"(",
"toks",
"[",
"1",
"]",
")",
"\n",
"}",
"else",
"{",
"c",
".",
"op",
"=",
"_EMPTY_",
"\n",
"}",
"\n",
"}"
] | // Parse a control line from the server. | [
"Parse",
"a",
"control",
"line",
"from",
"the",
"server",
"."
] | 36d30b0ba7aa260ae25b4f3d312b2a700106fd78 | https://github.com/nats-io/go-nats/blob/36d30b0ba7aa260ae25b4f3d312b2a700106fd78/nats.go#L1689-L1699 | train |
nats-io/go-nats | nats.go | flushReconnectPendingItems | func (nc *Conn) flushReconnectPendingItems() {
if nc.pending == nil {
return
}
if nc.pending.Len() > 0 {
nc.bw.Write(nc.pending.Bytes())
}
} | go | func (nc *Conn) flushReconnectPendingItems() {
if nc.pending == nil {
return
}
if nc.pending.Len() > 0 {
nc.bw.Write(nc.pending.Bytes())
}
} | [
"func",
"(",
"nc",
"*",
"Conn",
")",
"flushReconnectPendingItems",
"(",
")",
"{",
"if",
"nc",
".",
"pending",
"==",
"nil",
"{",
"return",
"\n",
"}",
"\n",
"if",
"nc",
".",
"pending",
".",
"Len",
"(",
")",
">",
"0",
"{",
"nc",
".",
"bw",
".",
"Write",
"(",
"nc",
".",
"pending",
".",
"Bytes",
"(",
")",
")",
"\n",
"}",
"\n",
"}"
] | // flushReconnectPending will push the pending items that were
// gathered while we were in a RECONNECTING state to the socket. | [
"flushReconnectPending",
"will",
"push",
"the",
"pending",
"items",
"that",
"were",
"gathered",
"while",
"we",
"were",
"in",
"a",
"RECONNECTING",
"state",
"to",
"the",
"socket",
"."
] | 36d30b0ba7aa260ae25b4f3d312b2a700106fd78 | https://github.com/nats-io/go-nats/blob/36d30b0ba7aa260ae25b4f3d312b2a700106fd78/nats.go#L1703-L1710 | train |
nats-io/go-nats | nats.go | doReconnect | func (nc *Conn) doReconnect() {
// We want to make sure we have the other watchers shutdown properly
// here before we proceed past this point.
nc.waitForExits()
// FIXME(dlc) - We have an issue here if we have
// outstanding flush points (pongs) and they were not
// sent out, but are still in the pipe.
// Hold the lock manually and release where needed below,
// can't do defer here.
nc.mu.Lock()
// Clear any queued pongs, e.g. pending flush calls.
nc.clearPendingFlushCalls()
// Clear any errors.
nc.err = nil
// Perform appropriate callback if needed for a disconnect.
if nc.Opts.DisconnectedCB != nil {
nc.ach.push(func() { nc.Opts.DisconnectedCB(nc) })
}
// This is used to wait on go routines exit if we start them in the loop
// but an error occurs after that.
waitForGoRoutines := false
for len(nc.srvPool) > 0 {
cur, err := nc.selectNextServer()
if err != nil {
nc.err = err
break
}
sleepTime := int64(0)
// Sleep appropriate amount of time before the
// connection attempt if connecting to same server
// we just got disconnected from..
if time.Since(cur.lastAttempt) < nc.Opts.ReconnectWait {
sleepTime = int64(nc.Opts.ReconnectWait - time.Since(cur.lastAttempt))
}
// On Windows, createConn() will take more than a second when no
// server is running at that address. So it could be that the
// time elapsed between reconnect attempts is always > than
// the set option. Release the lock to give a chance to a parallel
// nc.Close() to break the loop.
nc.mu.Unlock()
if sleepTime <= 0 {
runtime.Gosched()
} else {
time.Sleep(time.Duration(sleepTime))
}
// If the readLoop, etc.. go routines were started, wait for them to complete.
if waitForGoRoutines {
nc.waitForExits()
waitForGoRoutines = false
}
nc.mu.Lock()
// Check if we have been closed first.
if nc.isClosed() {
break
}
// Mark that we tried a reconnect
cur.reconnects++
// Try to create a new connection
err = nc.createConn()
// Not yet connected, retry...
// Continue to hold the lock
if err != nil {
nc.err = nil
continue
}
// We are reconnected
nc.Reconnects++
// Process connect logic
if nc.err = nc.processConnectInit(); nc.err != nil {
nc.status = RECONNECTING
// Reset the buffered writer to the pending buffer
// (was set to a buffered writer on nc.conn in createConn)
nc.bw.Reset(nc.pending)
continue
}
// Clear out server stats for the server we connected to..
cur.didConnect = true
cur.reconnects = 0
// Send existing subscription state
nc.resendSubscriptions()
// Now send off and clear pending buffer
nc.flushReconnectPendingItems()
// Flush the buffer
nc.err = nc.bw.Flush()
if nc.err != nil {
nc.status = RECONNECTING
// Reset the buffered writer to the pending buffer (bytes.Buffer).
nc.bw.Reset(nc.pending)
// Stop the ping timer (if set)
nc.stopPingTimer()
// Since processConnectInit() returned without error, the
// go routines were started, so wait for them to return
// on the next iteration (after releasing the lock).
waitForGoRoutines = true
continue
}
// Done with the pending buffer
nc.pending = nil
// This is where we are truly connected.
nc.status = CONNECTED
// Queue up the reconnect callback.
if nc.Opts.ReconnectedCB != nil {
nc.ach.push(func() { nc.Opts.ReconnectedCB(nc) })
}
// Release lock here, we will return below.
nc.mu.Unlock()
// Make sure to flush everything
nc.Flush()
return
}
// Call into close.. We have no servers left..
if nc.err == nil {
nc.err = ErrNoServers
}
nc.mu.Unlock()
nc.Close()
} | go | func (nc *Conn) doReconnect() {
// We want to make sure we have the other watchers shutdown properly
// here before we proceed past this point.
nc.waitForExits()
// FIXME(dlc) - We have an issue here if we have
// outstanding flush points (pongs) and they were not
// sent out, but are still in the pipe.
// Hold the lock manually and release where needed below,
// can't do defer here.
nc.mu.Lock()
// Clear any queued pongs, e.g. pending flush calls.
nc.clearPendingFlushCalls()
// Clear any errors.
nc.err = nil
// Perform appropriate callback if needed for a disconnect.
if nc.Opts.DisconnectedCB != nil {
nc.ach.push(func() { nc.Opts.DisconnectedCB(nc) })
}
// This is used to wait on go routines exit if we start them in the loop
// but an error occurs after that.
waitForGoRoutines := false
for len(nc.srvPool) > 0 {
cur, err := nc.selectNextServer()
if err != nil {
nc.err = err
break
}
sleepTime := int64(0)
// Sleep appropriate amount of time before the
// connection attempt if connecting to same server
// we just got disconnected from..
if time.Since(cur.lastAttempt) < nc.Opts.ReconnectWait {
sleepTime = int64(nc.Opts.ReconnectWait - time.Since(cur.lastAttempt))
}
// On Windows, createConn() will take more than a second when no
// server is running at that address. So it could be that the
// time elapsed between reconnect attempts is always > than
// the set option. Release the lock to give a chance to a parallel
// nc.Close() to break the loop.
nc.mu.Unlock()
if sleepTime <= 0 {
runtime.Gosched()
} else {
time.Sleep(time.Duration(sleepTime))
}
// If the readLoop, etc.. go routines were started, wait for them to complete.
if waitForGoRoutines {
nc.waitForExits()
waitForGoRoutines = false
}
nc.mu.Lock()
// Check if we have been closed first.
if nc.isClosed() {
break
}
// Mark that we tried a reconnect
cur.reconnects++
// Try to create a new connection
err = nc.createConn()
// Not yet connected, retry...
// Continue to hold the lock
if err != nil {
nc.err = nil
continue
}
// We are reconnected
nc.Reconnects++
// Process connect logic
if nc.err = nc.processConnectInit(); nc.err != nil {
nc.status = RECONNECTING
// Reset the buffered writer to the pending buffer
// (was set to a buffered writer on nc.conn in createConn)
nc.bw.Reset(nc.pending)
continue
}
// Clear out server stats for the server we connected to..
cur.didConnect = true
cur.reconnects = 0
// Send existing subscription state
nc.resendSubscriptions()
// Now send off and clear pending buffer
nc.flushReconnectPendingItems()
// Flush the buffer
nc.err = nc.bw.Flush()
if nc.err != nil {
nc.status = RECONNECTING
// Reset the buffered writer to the pending buffer (bytes.Buffer).
nc.bw.Reset(nc.pending)
// Stop the ping timer (if set)
nc.stopPingTimer()
// Since processConnectInit() returned without error, the
// go routines were started, so wait for them to return
// on the next iteration (after releasing the lock).
waitForGoRoutines = true
continue
}
// Done with the pending buffer
nc.pending = nil
// This is where we are truly connected.
nc.status = CONNECTED
// Queue up the reconnect callback.
if nc.Opts.ReconnectedCB != nil {
nc.ach.push(func() { nc.Opts.ReconnectedCB(nc) })
}
// Release lock here, we will return below.
nc.mu.Unlock()
// Make sure to flush everything
nc.Flush()
return
}
// Call into close.. We have no servers left..
if nc.err == nil {
nc.err = ErrNoServers
}
nc.mu.Unlock()
nc.Close()
} | [
"func",
"(",
"nc",
"*",
"Conn",
")",
"doReconnect",
"(",
")",
"{",
"nc",
".",
"waitForExits",
"(",
")",
"\n",
"nc",
".",
"mu",
".",
"Lock",
"(",
")",
"\n",
"nc",
".",
"clearPendingFlushCalls",
"(",
")",
"\n",
"nc",
".",
"err",
"=",
"nil",
"\n",
"if",
"nc",
".",
"Opts",
".",
"DisconnectedCB",
"!=",
"nil",
"{",
"nc",
".",
"ach",
".",
"push",
"(",
"func",
"(",
")",
"{",
"nc",
".",
"Opts",
".",
"DisconnectedCB",
"(",
"nc",
")",
"}",
")",
"\n",
"}",
"\n",
"waitForGoRoutines",
":=",
"false",
"\n",
"for",
"len",
"(",
"nc",
".",
"srvPool",
")",
">",
"0",
"{",
"cur",
",",
"err",
":=",
"nc",
".",
"selectNextServer",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"nc",
".",
"err",
"=",
"err",
"\n",
"break",
"\n",
"}",
"\n",
"sleepTime",
":=",
"int64",
"(",
"0",
")",
"\n",
"if",
"time",
".",
"Since",
"(",
"cur",
".",
"lastAttempt",
")",
"<",
"nc",
".",
"Opts",
".",
"ReconnectWait",
"{",
"sleepTime",
"=",
"int64",
"(",
"nc",
".",
"Opts",
".",
"ReconnectWait",
"-",
"time",
".",
"Since",
"(",
"cur",
".",
"lastAttempt",
")",
")",
"\n",
"}",
"\n",
"nc",
".",
"mu",
".",
"Unlock",
"(",
")",
"\n",
"if",
"sleepTime",
"<=",
"0",
"{",
"runtime",
".",
"Gosched",
"(",
")",
"\n",
"}",
"else",
"{",
"time",
".",
"Sleep",
"(",
"time",
".",
"Duration",
"(",
"sleepTime",
")",
")",
"\n",
"}",
"\n",
"if",
"waitForGoRoutines",
"{",
"nc",
".",
"waitForExits",
"(",
")",
"\n",
"waitForGoRoutines",
"=",
"false",
"\n",
"}",
"\n",
"nc",
".",
"mu",
".",
"Lock",
"(",
")",
"\n",
"if",
"nc",
".",
"isClosed",
"(",
")",
"{",
"break",
"\n",
"}",
"\n",
"cur",
".",
"reconnects",
"++",
"\n",
"err",
"=",
"nc",
".",
"createConn",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"nc",
".",
"err",
"=",
"nil",
"\n",
"continue",
"\n",
"}",
"\n",
"nc",
".",
"Reconnects",
"++",
"\n",
"if",
"nc",
".",
"err",
"=",
"nc",
".",
"processConnectInit",
"(",
")",
";",
"nc",
".",
"err",
"!=",
"nil",
"{",
"nc",
".",
"status",
"=",
"RECONNECTING",
"\n",
"nc",
".",
"bw",
".",
"Reset",
"(",
"nc",
".",
"pending",
")",
"\n",
"continue",
"\n",
"}",
"\n",
"cur",
".",
"didConnect",
"=",
"true",
"\n",
"cur",
".",
"reconnects",
"=",
"0",
"\n",
"nc",
".",
"resendSubscriptions",
"(",
")",
"\n",
"nc",
".",
"flushReconnectPendingItems",
"(",
")",
"\n",
"nc",
".",
"err",
"=",
"nc",
".",
"bw",
".",
"Flush",
"(",
")",
"\n",
"if",
"nc",
".",
"err",
"!=",
"nil",
"{",
"nc",
".",
"status",
"=",
"RECONNECTING",
"\n",
"nc",
".",
"bw",
".",
"Reset",
"(",
"nc",
".",
"pending",
")",
"\n",
"nc",
".",
"stopPingTimer",
"(",
")",
"\n",
"waitForGoRoutines",
"=",
"true",
"\n",
"continue",
"\n",
"}",
"\n",
"nc",
".",
"pending",
"=",
"nil",
"\n",
"nc",
".",
"status",
"=",
"CONNECTED",
"\n",
"if",
"nc",
".",
"Opts",
".",
"ReconnectedCB",
"!=",
"nil",
"{",
"nc",
".",
"ach",
".",
"push",
"(",
"func",
"(",
")",
"{",
"nc",
".",
"Opts",
".",
"ReconnectedCB",
"(",
"nc",
")",
"}",
")",
"\n",
"}",
"\n",
"nc",
".",
"mu",
".",
"Unlock",
"(",
")",
"\n",
"nc",
".",
"Flush",
"(",
")",
"\n",
"return",
"\n",
"}",
"\n",
"if",
"nc",
".",
"err",
"==",
"nil",
"{",
"nc",
".",
"err",
"=",
"ErrNoServers",
"\n",
"}",
"\n",
"nc",
".",
"mu",
".",
"Unlock",
"(",
")",
"\n",
"nc",
".",
"Close",
"(",
")",
"\n",
"}"
] | // Try to reconnect using the option parameters.
// This function assumes we are allowed to reconnect. | [
"Try",
"to",
"reconnect",
"using",
"the",
"option",
"parameters",
".",
"This",
"function",
"assumes",
"we",
"are",
"allowed",
"to",
"reconnect",
"."
] | 36d30b0ba7aa260ae25b4f3d312b2a700106fd78 | https://github.com/nats-io/go-nats/blob/36d30b0ba7aa260ae25b4f3d312b2a700106fd78/nats.go#L1722-L1863 | train |
nats-io/go-nats | nats.go | processOpErr | func (nc *Conn) processOpErr(err error) {
nc.mu.Lock()
if nc.isConnecting() || nc.isClosed() || nc.isReconnecting() {
nc.mu.Unlock()
return
}
if nc.Opts.AllowReconnect && nc.status == CONNECTED {
// Set our new status
nc.status = RECONNECTING
// Stop ping timer if set
nc.stopPingTimer()
if nc.conn != nil {
nc.bw.Flush()
nc.conn.Close()
nc.conn = nil
}
// Create pending buffer before reconnecting.
nc.pending = new(bytes.Buffer)
nc.bw.Reset(nc.pending)
go nc.doReconnect()
nc.mu.Unlock()
return
}
nc.status = DISCONNECTED
nc.err = err
nc.mu.Unlock()
nc.Close()
} | go | func (nc *Conn) processOpErr(err error) {
nc.mu.Lock()
if nc.isConnecting() || nc.isClosed() || nc.isReconnecting() {
nc.mu.Unlock()
return
}
if nc.Opts.AllowReconnect && nc.status == CONNECTED {
// Set our new status
nc.status = RECONNECTING
// Stop ping timer if set
nc.stopPingTimer()
if nc.conn != nil {
nc.bw.Flush()
nc.conn.Close()
nc.conn = nil
}
// Create pending buffer before reconnecting.
nc.pending = new(bytes.Buffer)
nc.bw.Reset(nc.pending)
go nc.doReconnect()
nc.mu.Unlock()
return
}
nc.status = DISCONNECTED
nc.err = err
nc.mu.Unlock()
nc.Close()
} | [
"func",
"(",
"nc",
"*",
"Conn",
")",
"processOpErr",
"(",
"err",
"error",
")",
"{",
"nc",
".",
"mu",
".",
"Lock",
"(",
")",
"\n",
"if",
"nc",
".",
"isConnecting",
"(",
")",
"||",
"nc",
".",
"isClosed",
"(",
")",
"||",
"nc",
".",
"isReconnecting",
"(",
")",
"{",
"nc",
".",
"mu",
".",
"Unlock",
"(",
")",
"\n",
"return",
"\n",
"}",
"\n",
"if",
"nc",
".",
"Opts",
".",
"AllowReconnect",
"&&",
"nc",
".",
"status",
"==",
"CONNECTED",
"{",
"nc",
".",
"status",
"=",
"RECONNECTING",
"\n",
"nc",
".",
"stopPingTimer",
"(",
")",
"\n",
"if",
"nc",
".",
"conn",
"!=",
"nil",
"{",
"nc",
".",
"bw",
".",
"Flush",
"(",
")",
"\n",
"nc",
".",
"conn",
".",
"Close",
"(",
")",
"\n",
"nc",
".",
"conn",
"=",
"nil",
"\n",
"}",
"\n",
"nc",
".",
"pending",
"=",
"new",
"(",
"bytes",
".",
"Buffer",
")",
"\n",
"nc",
".",
"bw",
".",
"Reset",
"(",
"nc",
".",
"pending",
")",
"\n",
"go",
"nc",
".",
"doReconnect",
"(",
")",
"\n",
"nc",
".",
"mu",
".",
"Unlock",
"(",
")",
"\n",
"return",
"\n",
"}",
"\n",
"nc",
".",
"status",
"=",
"DISCONNECTED",
"\n",
"nc",
".",
"err",
"=",
"err",
"\n",
"nc",
".",
"mu",
".",
"Unlock",
"(",
")",
"\n",
"nc",
".",
"Close",
"(",
")",
"\n",
"}"
] | // processOpErr handles errors from reading or parsing the protocol.
// The lock should not be held entering this function. | [
"processOpErr",
"handles",
"errors",
"from",
"reading",
"or",
"parsing",
"the",
"protocol",
".",
"The",
"lock",
"should",
"not",
"be",
"held",
"entering",
"this",
"function",
"."
] | 36d30b0ba7aa260ae25b4f3d312b2a700106fd78 | https://github.com/nats-io/go-nats/blob/36d30b0ba7aa260ae25b4f3d312b2a700106fd78/nats.go#L1867-L1898 | train |
nats-io/go-nats | nats.go | asyncCBDispatcher | func (ac *asyncCallbacksHandler) asyncCBDispatcher() {
for {
ac.mu.Lock()
// Protect for spurious wakeups. We should get out of the
// wait only if there is an element to pop from the list.
for ac.head == nil {
ac.cond.Wait()
}
cur := ac.head
ac.head = cur.next
if cur == ac.tail {
ac.tail = nil
}
ac.mu.Unlock()
// This signals that the dispatcher has been closed and all
// previous callbacks have been dispatched.
if cur.f == nil {
return
}
// Invoke callback outside of handler's lock
cur.f()
}
} | go | func (ac *asyncCallbacksHandler) asyncCBDispatcher() {
for {
ac.mu.Lock()
// Protect for spurious wakeups. We should get out of the
// wait only if there is an element to pop from the list.
for ac.head == nil {
ac.cond.Wait()
}
cur := ac.head
ac.head = cur.next
if cur == ac.tail {
ac.tail = nil
}
ac.mu.Unlock()
// This signals that the dispatcher has been closed and all
// previous callbacks have been dispatched.
if cur.f == nil {
return
}
// Invoke callback outside of handler's lock
cur.f()
}
} | [
"func",
"(",
"ac",
"*",
"asyncCallbacksHandler",
")",
"asyncCBDispatcher",
"(",
")",
"{",
"for",
"{",
"ac",
".",
"mu",
".",
"Lock",
"(",
")",
"\n",
"for",
"ac",
".",
"head",
"==",
"nil",
"{",
"ac",
".",
"cond",
".",
"Wait",
"(",
")",
"\n",
"}",
"\n",
"cur",
":=",
"ac",
".",
"head",
"\n",
"ac",
".",
"head",
"=",
"cur",
".",
"next",
"\n",
"if",
"cur",
"==",
"ac",
".",
"tail",
"{",
"ac",
".",
"tail",
"=",
"nil",
"\n",
"}",
"\n",
"ac",
".",
"mu",
".",
"Unlock",
"(",
")",
"\n",
"if",
"cur",
".",
"f",
"==",
"nil",
"{",
"return",
"\n",
"}",
"\n",
"cur",
".",
"f",
"(",
")",
"\n",
"}",
"\n",
"}"
] | // dispatch is responsible for calling any async callbacks | [
"dispatch",
"is",
"responsible",
"for",
"calling",
"any",
"async",
"callbacks"
] | 36d30b0ba7aa260ae25b4f3d312b2a700106fd78 | https://github.com/nats-io/go-nats/blob/36d30b0ba7aa260ae25b4f3d312b2a700106fd78/nats.go#L1901-L1924 | train |
nats-io/go-nats | nats.go | pushOrClose | func (ac *asyncCallbacksHandler) pushOrClose(f func(), close bool) {
ac.mu.Lock()
defer ac.mu.Unlock()
// Make sure that library is not calling push with nil function,
// since this is used to notify the dispatcher that it should stop.
if !close && f == nil {
panic("pushing a nil callback")
}
cb := &asyncCB{f: f}
if ac.tail != nil {
ac.tail.next = cb
} else {
ac.head = cb
}
ac.tail = cb
if close {
ac.cond.Broadcast()
} else {
ac.cond.Signal()
}
} | go | func (ac *asyncCallbacksHandler) pushOrClose(f func(), close bool) {
ac.mu.Lock()
defer ac.mu.Unlock()
// Make sure that library is not calling push with nil function,
// since this is used to notify the dispatcher that it should stop.
if !close && f == nil {
panic("pushing a nil callback")
}
cb := &asyncCB{f: f}
if ac.tail != nil {
ac.tail.next = cb
} else {
ac.head = cb
}
ac.tail = cb
if close {
ac.cond.Broadcast()
} else {
ac.cond.Signal()
}
} | [
"func",
"(",
"ac",
"*",
"asyncCallbacksHandler",
")",
"pushOrClose",
"(",
"f",
"func",
"(",
")",
",",
"close",
"bool",
")",
"{",
"ac",
".",
"mu",
".",
"Lock",
"(",
")",
"\n",
"defer",
"ac",
".",
"mu",
".",
"Unlock",
"(",
")",
"\n",
"if",
"!",
"close",
"&&",
"f",
"==",
"nil",
"{",
"panic",
"(",
"\"pushing a nil callback\"",
")",
"\n",
"}",
"\n",
"cb",
":=",
"&",
"asyncCB",
"{",
"f",
":",
"f",
"}",
"\n",
"if",
"ac",
".",
"tail",
"!=",
"nil",
"{",
"ac",
".",
"tail",
".",
"next",
"=",
"cb",
"\n",
"}",
"else",
"{",
"ac",
".",
"head",
"=",
"cb",
"\n",
"}",
"\n",
"ac",
".",
"tail",
"=",
"cb",
"\n",
"if",
"close",
"{",
"ac",
".",
"cond",
".",
"Broadcast",
"(",
")",
"\n",
"}",
"else",
"{",
"ac",
".",
"cond",
".",
"Signal",
"(",
")",
"\n",
"}",
"\n",
"}"
] | // Add the given function to the tail of the list and
// signals the dispatcher. | [
"Add",
"the",
"given",
"function",
"to",
"the",
"tail",
"of",
"the",
"list",
"and",
"signals",
"the",
"dispatcher",
"."
] | 36d30b0ba7aa260ae25b4f3d312b2a700106fd78 | https://github.com/nats-io/go-nats/blob/36d30b0ba7aa260ae25b4f3d312b2a700106fd78/nats.go#L1939-L1959 | train |
nats-io/go-nats | nats.go | waitForMsgs | func (nc *Conn) waitForMsgs(s *Subscription) {
var closed bool
var delivered, max uint64
// Used to account for adjustments to sub.pBytes when we wrap back around.
msgLen := -1
for {
s.mu.Lock()
// Do accounting for last msg delivered here so we only lock once
// and drain state trips after callback has returned.
if msgLen >= 0 {
s.pMsgs--
s.pBytes -= msgLen
msgLen = -1
}
if s.pHead == nil && !s.closed {
s.pCond.Wait()
}
// Pop the msg off the list
m := s.pHead
if m != nil {
s.pHead = m.next
if s.pHead == nil {
s.pTail = nil
}
if m.barrier != nil {
s.mu.Unlock()
if atomic.AddInt64(&m.barrier.refs, -1) == 0 {
m.barrier.f()
}
continue
}
msgLen = len(m.Data)
}
mcb := s.mcb
max = s.max
closed = s.closed
if !s.closed {
s.delivered++
delivered = s.delivered
}
s.mu.Unlock()
if closed {
break
}
// Deliver the message.
if m != nil && (max == 0 || delivered <= max) {
mcb(m)
}
// If we have hit the max for delivered msgs, remove sub.
if max > 0 && delivered >= max {
nc.mu.Lock()
nc.removeSub(s)
nc.mu.Unlock()
break
}
}
// Check for barrier messages
s.mu.Lock()
for m := s.pHead; m != nil; m = s.pHead {
if m.barrier != nil {
s.mu.Unlock()
if atomic.AddInt64(&m.barrier.refs, -1) == 0 {
m.barrier.f()
}
s.mu.Lock()
}
s.pHead = m.next
}
s.mu.Unlock()
} | go | func (nc *Conn) waitForMsgs(s *Subscription) {
var closed bool
var delivered, max uint64
// Used to account for adjustments to sub.pBytes when we wrap back around.
msgLen := -1
for {
s.mu.Lock()
// Do accounting for last msg delivered here so we only lock once
// and drain state trips after callback has returned.
if msgLen >= 0 {
s.pMsgs--
s.pBytes -= msgLen
msgLen = -1
}
if s.pHead == nil && !s.closed {
s.pCond.Wait()
}
// Pop the msg off the list
m := s.pHead
if m != nil {
s.pHead = m.next
if s.pHead == nil {
s.pTail = nil
}
if m.barrier != nil {
s.mu.Unlock()
if atomic.AddInt64(&m.barrier.refs, -1) == 0 {
m.barrier.f()
}
continue
}
msgLen = len(m.Data)
}
mcb := s.mcb
max = s.max
closed = s.closed
if !s.closed {
s.delivered++
delivered = s.delivered
}
s.mu.Unlock()
if closed {
break
}
// Deliver the message.
if m != nil && (max == 0 || delivered <= max) {
mcb(m)
}
// If we have hit the max for delivered msgs, remove sub.
if max > 0 && delivered >= max {
nc.mu.Lock()
nc.removeSub(s)
nc.mu.Unlock()
break
}
}
// Check for barrier messages
s.mu.Lock()
for m := s.pHead; m != nil; m = s.pHead {
if m.barrier != nil {
s.mu.Unlock()
if atomic.AddInt64(&m.barrier.refs, -1) == 0 {
m.barrier.f()
}
s.mu.Lock()
}
s.pHead = m.next
}
s.mu.Unlock()
} | [
"func",
"(",
"nc",
"*",
"Conn",
")",
"waitForMsgs",
"(",
"s",
"*",
"Subscription",
")",
"{",
"var",
"closed",
"bool",
"\n",
"var",
"delivered",
",",
"max",
"uint64",
"\n",
"msgLen",
":=",
"-",
"1",
"\n",
"for",
"{",
"s",
".",
"mu",
".",
"Lock",
"(",
")",
"\n",
"if",
"msgLen",
">=",
"0",
"{",
"s",
".",
"pMsgs",
"--",
"\n",
"s",
".",
"pBytes",
"-=",
"msgLen",
"\n",
"msgLen",
"=",
"-",
"1",
"\n",
"}",
"\n",
"if",
"s",
".",
"pHead",
"==",
"nil",
"&&",
"!",
"s",
".",
"closed",
"{",
"s",
".",
"pCond",
".",
"Wait",
"(",
")",
"\n",
"}",
"\n",
"m",
":=",
"s",
".",
"pHead",
"\n",
"if",
"m",
"!=",
"nil",
"{",
"s",
".",
"pHead",
"=",
"m",
".",
"next",
"\n",
"if",
"s",
".",
"pHead",
"==",
"nil",
"{",
"s",
".",
"pTail",
"=",
"nil",
"\n",
"}",
"\n",
"if",
"m",
".",
"barrier",
"!=",
"nil",
"{",
"s",
".",
"mu",
".",
"Unlock",
"(",
")",
"\n",
"if",
"atomic",
".",
"AddInt64",
"(",
"&",
"m",
".",
"barrier",
".",
"refs",
",",
"-",
"1",
")",
"==",
"0",
"{",
"m",
".",
"barrier",
".",
"f",
"(",
")",
"\n",
"}",
"\n",
"continue",
"\n",
"}",
"\n",
"msgLen",
"=",
"len",
"(",
"m",
".",
"Data",
")",
"\n",
"}",
"\n",
"mcb",
":=",
"s",
".",
"mcb",
"\n",
"max",
"=",
"s",
".",
"max",
"\n",
"closed",
"=",
"s",
".",
"closed",
"\n",
"if",
"!",
"s",
".",
"closed",
"{",
"s",
".",
"delivered",
"++",
"\n",
"delivered",
"=",
"s",
".",
"delivered",
"\n",
"}",
"\n",
"s",
".",
"mu",
".",
"Unlock",
"(",
")",
"\n",
"if",
"closed",
"{",
"break",
"\n",
"}",
"\n",
"if",
"m",
"!=",
"nil",
"&&",
"(",
"max",
"==",
"0",
"||",
"delivered",
"<=",
"max",
")",
"{",
"mcb",
"(",
"m",
")",
"\n",
"}",
"\n",
"if",
"max",
">",
"0",
"&&",
"delivered",
">=",
"max",
"{",
"nc",
".",
"mu",
".",
"Lock",
"(",
")",
"\n",
"nc",
".",
"removeSub",
"(",
"s",
")",
"\n",
"nc",
".",
"mu",
".",
"Unlock",
"(",
")",
"\n",
"break",
"\n",
"}",
"\n",
"}",
"\n",
"s",
".",
"mu",
".",
"Lock",
"(",
")",
"\n",
"for",
"m",
":=",
"s",
".",
"pHead",
";",
"m",
"!=",
"nil",
";",
"m",
"=",
"s",
".",
"pHead",
"{",
"if",
"m",
".",
"barrier",
"!=",
"nil",
"{",
"s",
".",
"mu",
".",
"Unlock",
"(",
")",
"\n",
"if",
"atomic",
".",
"AddInt64",
"(",
"&",
"m",
".",
"barrier",
".",
"refs",
",",
"-",
"1",
")",
"==",
"0",
"{",
"m",
".",
"barrier",
".",
"f",
"(",
")",
"\n",
"}",
"\n",
"s",
".",
"mu",
".",
"Lock",
"(",
")",
"\n",
"}",
"\n",
"s",
".",
"pHead",
"=",
"m",
".",
"next",
"\n",
"}",
"\n",
"s",
".",
"mu",
".",
"Unlock",
"(",
")",
"\n",
"}"
] | // waitForMsgs waits on the conditional shared with readLoop and processMsg.
// It is used to deliver messages to asynchronous subscribers. | [
"waitForMsgs",
"waits",
"on",
"the",
"conditional",
"shared",
"with",
"readLoop",
"and",
"processMsg",
".",
"It",
"is",
"used",
"to",
"deliver",
"messages",
"to",
"asynchronous",
"subscribers",
"."
] | 36d30b0ba7aa260ae25b4f3d312b2a700106fd78 | https://github.com/nats-io/go-nats/blob/36d30b0ba7aa260ae25b4f3d312b2a700106fd78/nats.go#L2010-L2084 | train |
nats-io/go-nats | nats.go | processPermissionsViolation | func (nc *Conn) processPermissionsViolation(err string) {
nc.mu.Lock()
// create error here so we can pass it as a closure to the async cb dispatcher.
e := errors.New("nats: " + err)
nc.err = e
if nc.Opts.AsyncErrorCB != nil {
nc.ach.push(func() { nc.Opts.AsyncErrorCB(nc, nil, e) })
}
nc.mu.Unlock()
} | go | func (nc *Conn) processPermissionsViolation(err string) {
nc.mu.Lock()
// create error here so we can pass it as a closure to the async cb dispatcher.
e := errors.New("nats: " + err)
nc.err = e
if nc.Opts.AsyncErrorCB != nil {
nc.ach.push(func() { nc.Opts.AsyncErrorCB(nc, nil, e) })
}
nc.mu.Unlock()
} | [
"func",
"(",
"nc",
"*",
"Conn",
")",
"processPermissionsViolation",
"(",
"err",
"string",
")",
"{",
"nc",
".",
"mu",
".",
"Lock",
"(",
")",
"\n",
"e",
":=",
"errors",
".",
"New",
"(",
"\"nats: \"",
"+",
"err",
")",
"\n",
"nc",
".",
"err",
"=",
"e",
"\n",
"if",
"nc",
".",
"Opts",
".",
"AsyncErrorCB",
"!=",
"nil",
"{",
"nc",
".",
"ach",
".",
"push",
"(",
"func",
"(",
")",
"{",
"nc",
".",
"Opts",
".",
"AsyncErrorCB",
"(",
"nc",
",",
"nil",
",",
"e",
")",
"}",
")",
"\n",
"}",
"\n",
"nc",
".",
"mu",
".",
"Unlock",
"(",
")",
"\n",
"}"
] | // processPermissionsViolation is called when the server signals a subject
// permissions violation on either publish or subscribe. | [
"processPermissionsViolation",
"is",
"called",
"when",
"the",
"server",
"signals",
"a",
"subject",
"permissions",
"violation",
"on",
"either",
"publish",
"or",
"subscribe",
"."
] | 36d30b0ba7aa260ae25b4f3d312b2a700106fd78 | https://github.com/nats-io/go-nats/blob/36d30b0ba7aa260ae25b4f3d312b2a700106fd78/nats.go#L2193-L2202 | train |
nats-io/go-nats | nats.go | processAuthorizationViolation | func (nc *Conn) processAuthorizationViolation(err string) {
nc.mu.Lock()
nc.err = ErrAuthorization
if nc.Opts.AsyncErrorCB != nil {
nc.ach.push(func() { nc.Opts.AsyncErrorCB(nc, nil, ErrAuthorization) })
}
nc.mu.Unlock()
} | go | func (nc *Conn) processAuthorizationViolation(err string) {
nc.mu.Lock()
nc.err = ErrAuthorization
if nc.Opts.AsyncErrorCB != nil {
nc.ach.push(func() { nc.Opts.AsyncErrorCB(nc, nil, ErrAuthorization) })
}
nc.mu.Unlock()
} | [
"func",
"(",
"nc",
"*",
"Conn",
")",
"processAuthorizationViolation",
"(",
"err",
"string",
")",
"{",
"nc",
".",
"mu",
".",
"Lock",
"(",
")",
"\n",
"nc",
".",
"err",
"=",
"ErrAuthorization",
"\n",
"if",
"nc",
".",
"Opts",
".",
"AsyncErrorCB",
"!=",
"nil",
"{",
"nc",
".",
"ach",
".",
"push",
"(",
"func",
"(",
")",
"{",
"nc",
".",
"Opts",
".",
"AsyncErrorCB",
"(",
"nc",
",",
"nil",
",",
"ErrAuthorization",
")",
"}",
")",
"\n",
"}",
"\n",
"nc",
".",
"mu",
".",
"Unlock",
"(",
")",
"\n",
"}"
] | // processAuthorizationViolation is called when the server signals a user
// authorization violation. | [
"processAuthorizationViolation",
"is",
"called",
"when",
"the",
"server",
"signals",
"a",
"user",
"authorization",
"violation",
"."
] | 36d30b0ba7aa260ae25b4f3d312b2a700106fd78 | https://github.com/nats-io/go-nats/blob/36d30b0ba7aa260ae25b4f3d312b2a700106fd78/nats.go#L2206-L2213 | train |
nats-io/go-nats | nats.go | flusher | func (nc *Conn) flusher() {
// Release the wait group
defer nc.wg.Done()
// snapshot the bw and conn since they can change from underneath of us.
nc.mu.Lock()
bw := nc.bw
conn := nc.conn
fch := nc.fch
nc.mu.Unlock()
if conn == nil || bw == nil {
return
}
for {
if _, ok := <-fch; !ok {
return
}
nc.mu.Lock()
// Check to see if we should bail out.
if !nc.isConnected() || nc.isConnecting() || bw != nc.bw || conn != nc.conn {
nc.mu.Unlock()
return
}
if bw.Buffered() > 0 {
if err := bw.Flush(); err != nil {
if nc.err == nil {
nc.err = err
}
}
}
nc.mu.Unlock()
}
} | go | func (nc *Conn) flusher() {
// Release the wait group
defer nc.wg.Done()
// snapshot the bw and conn since they can change from underneath of us.
nc.mu.Lock()
bw := nc.bw
conn := nc.conn
fch := nc.fch
nc.mu.Unlock()
if conn == nil || bw == nil {
return
}
for {
if _, ok := <-fch; !ok {
return
}
nc.mu.Lock()
// Check to see if we should bail out.
if !nc.isConnected() || nc.isConnecting() || bw != nc.bw || conn != nc.conn {
nc.mu.Unlock()
return
}
if bw.Buffered() > 0 {
if err := bw.Flush(); err != nil {
if nc.err == nil {
nc.err = err
}
}
}
nc.mu.Unlock()
}
} | [
"func",
"(",
"nc",
"*",
"Conn",
")",
"flusher",
"(",
")",
"{",
"defer",
"nc",
".",
"wg",
".",
"Done",
"(",
")",
"\n",
"nc",
".",
"mu",
".",
"Lock",
"(",
")",
"\n",
"bw",
":=",
"nc",
".",
"bw",
"\n",
"conn",
":=",
"nc",
".",
"conn",
"\n",
"fch",
":=",
"nc",
".",
"fch",
"\n",
"nc",
".",
"mu",
".",
"Unlock",
"(",
")",
"\n",
"if",
"conn",
"==",
"nil",
"||",
"bw",
"==",
"nil",
"{",
"return",
"\n",
"}",
"\n",
"for",
"{",
"if",
"_",
",",
"ok",
":=",
"<-",
"fch",
";",
"!",
"ok",
"{",
"return",
"\n",
"}",
"\n",
"nc",
".",
"mu",
".",
"Lock",
"(",
")",
"\n",
"if",
"!",
"nc",
".",
"isConnected",
"(",
")",
"||",
"nc",
".",
"isConnecting",
"(",
")",
"||",
"bw",
"!=",
"nc",
".",
"bw",
"||",
"conn",
"!=",
"nc",
".",
"conn",
"{",
"nc",
".",
"mu",
".",
"Unlock",
"(",
")",
"\n",
"return",
"\n",
"}",
"\n",
"if",
"bw",
".",
"Buffered",
"(",
")",
">",
"0",
"{",
"if",
"err",
":=",
"bw",
".",
"Flush",
"(",
")",
";",
"err",
"!=",
"nil",
"{",
"if",
"nc",
".",
"err",
"==",
"nil",
"{",
"nc",
".",
"err",
"=",
"err",
"\n",
"}",
"\n",
"}",
"\n",
"}",
"\n",
"nc",
".",
"mu",
".",
"Unlock",
"(",
")",
"\n",
"}",
"\n",
"}"
] | // flusher is a separate Go routine that will process flush requests for the write
// bufio. This allows coalescing of writes to the underlying socket. | [
"flusher",
"is",
"a",
"separate",
"Go",
"routine",
"that",
"will",
"process",
"flush",
"requests",
"for",
"the",
"write",
"bufio",
".",
"This",
"allows",
"coalescing",
"of",
"writes",
"to",
"the",
"underlying",
"socket",
"."
] | 36d30b0ba7aa260ae25b4f3d312b2a700106fd78 | https://github.com/nats-io/go-nats/blob/36d30b0ba7aa260ae25b4f3d312b2a700106fd78/nats.go#L2217-L2252 | train |
nats-io/go-nats | nats.go | processPong | func (nc *Conn) processPong() {
var ch chan struct{}
nc.mu.Lock()
if len(nc.pongs) > 0 {
ch = nc.pongs[0]
nc.pongs = nc.pongs[1:]
}
nc.pout = 0
nc.mu.Unlock()
if ch != nil {
ch <- struct{}{}
}
} | go | func (nc *Conn) processPong() {
var ch chan struct{}
nc.mu.Lock()
if len(nc.pongs) > 0 {
ch = nc.pongs[0]
nc.pongs = nc.pongs[1:]
}
nc.pout = 0
nc.mu.Unlock()
if ch != nil {
ch <- struct{}{}
}
} | [
"func",
"(",
"nc",
"*",
"Conn",
")",
"processPong",
"(",
")",
"{",
"var",
"ch",
"chan",
"struct",
"{",
"}",
"\n",
"nc",
".",
"mu",
".",
"Lock",
"(",
")",
"\n",
"if",
"len",
"(",
"nc",
".",
"pongs",
")",
">",
"0",
"{",
"ch",
"=",
"nc",
".",
"pongs",
"[",
"0",
"]",
"\n",
"nc",
".",
"pongs",
"=",
"nc",
".",
"pongs",
"[",
"1",
":",
"]",
"\n",
"}",
"\n",
"nc",
".",
"pout",
"=",
"0",
"\n",
"nc",
".",
"mu",
".",
"Unlock",
"(",
")",
"\n",
"if",
"ch",
"!=",
"nil",
"{",
"ch",
"<-",
"struct",
"{",
"}",
"{",
"}",
"\n",
"}",
"\n",
"}"
] | // processPong is used to process responses to the client's ping
// messages. We use pings for the flush mechanism as well. | [
"processPong",
"is",
"used",
"to",
"process",
"responses",
"to",
"the",
"client",
"s",
"ping",
"messages",
".",
"We",
"use",
"pings",
"for",
"the",
"flush",
"mechanism",
"as",
"well",
"."
] | 36d30b0ba7aa260ae25b4f3d312b2a700106fd78 | https://github.com/nats-io/go-nats/blob/36d30b0ba7aa260ae25b4f3d312b2a700106fd78/nats.go#L2262-L2275 | train |
nats-io/go-nats | nats.go | processInfo | func (nc *Conn) processInfo(info string) error {
if info == _EMPTY_ {
return nil
}
ncInfo := serverInfo{}
if err := json.Unmarshal([]byte(info), &ncInfo); err != nil {
return err
}
// Copy content into connection's info structure.
nc.info = ncInfo
// The array could be empty/not present on initial connect,
// if advertise is disabled on that server, or servers that
// did not include themselves in the async INFO protocol.
// If empty, do not remove the implicit servers from the pool.
if len(ncInfo.ConnectURLs) == 0 {
return nil
}
// Note about pool randomization: when the pool was first created,
// it was randomized (if allowed). We keep the order the same (removing
// implicit servers that are no longer sent to us). New URLs are sent
// to us in no specific order so don't need extra randomization.
hasNew := false
// This is what we got from the server we are connected to.
urls := nc.info.ConnectURLs
// Transform that to a map for easy lookups
tmp := make(map[string]struct{}, len(urls))
for _, curl := range urls {
tmp[curl] = struct{}{}
}
// Walk the pool and removed the implicit servers that are no longer in the
// given array/map
sp := nc.srvPool
for i := 0; i < len(sp); i++ {
srv := sp[i]
curl := srv.url.Host
// Check if this URL is in the INFO protocol
_, inInfo := tmp[curl]
// Remove from the temp map so that at the end we are left with only
// new (or restarted) servers that need to be added to the pool.
delete(tmp, curl)
// Keep servers that were set through Options, but also the one that
// we are currently connected to (even if it is a discovered server).
if !srv.isImplicit || srv.url == nc.current.url {
continue
}
if !inInfo {
// Remove from server pool. Keep current order.
copy(sp[i:], sp[i+1:])
nc.srvPool = sp[:len(sp)-1]
sp = nc.srvPool
i--
}
}
// Figure out if we should save off the current non-IP hostname if we encounter a bare IP.
saveTLS := nc.current != nil && !hostIsIP(nc.current.url)
// If there are any left in the tmp map, these are new (or restarted) servers
// and need to be added to the pool.
for curl := range tmp {
// Before adding, check if this is a new (as in never seen) URL.
// This is used to figure out if we invoke the DiscoveredServersCB
if _, present := nc.urls[curl]; !present {
hasNew = true
}
nc.addURLToPool(fmt.Sprintf("%s://%s", nc.connScheme(), curl), true, saveTLS)
}
if hasNew && !nc.initc && nc.Opts.DiscoveredServersCB != nil {
nc.ach.push(func() { nc.Opts.DiscoveredServersCB(nc) })
}
return nil
} | go | func (nc *Conn) processInfo(info string) error {
if info == _EMPTY_ {
return nil
}
ncInfo := serverInfo{}
if err := json.Unmarshal([]byte(info), &ncInfo); err != nil {
return err
}
// Copy content into connection's info structure.
nc.info = ncInfo
// The array could be empty/not present on initial connect,
// if advertise is disabled on that server, or servers that
// did not include themselves in the async INFO protocol.
// If empty, do not remove the implicit servers from the pool.
if len(ncInfo.ConnectURLs) == 0 {
return nil
}
// Note about pool randomization: when the pool was first created,
// it was randomized (if allowed). We keep the order the same (removing
// implicit servers that are no longer sent to us). New URLs are sent
// to us in no specific order so don't need extra randomization.
hasNew := false
// This is what we got from the server we are connected to.
urls := nc.info.ConnectURLs
// Transform that to a map for easy lookups
tmp := make(map[string]struct{}, len(urls))
for _, curl := range urls {
tmp[curl] = struct{}{}
}
// Walk the pool and removed the implicit servers that are no longer in the
// given array/map
sp := nc.srvPool
for i := 0; i < len(sp); i++ {
srv := sp[i]
curl := srv.url.Host
// Check if this URL is in the INFO protocol
_, inInfo := tmp[curl]
// Remove from the temp map so that at the end we are left with only
// new (or restarted) servers that need to be added to the pool.
delete(tmp, curl)
// Keep servers that were set through Options, but also the one that
// we are currently connected to (even if it is a discovered server).
if !srv.isImplicit || srv.url == nc.current.url {
continue
}
if !inInfo {
// Remove from server pool. Keep current order.
copy(sp[i:], sp[i+1:])
nc.srvPool = sp[:len(sp)-1]
sp = nc.srvPool
i--
}
}
// Figure out if we should save off the current non-IP hostname if we encounter a bare IP.
saveTLS := nc.current != nil && !hostIsIP(nc.current.url)
// If there are any left in the tmp map, these are new (or restarted) servers
// and need to be added to the pool.
for curl := range tmp {
// Before adding, check if this is a new (as in never seen) URL.
// This is used to figure out if we invoke the DiscoveredServersCB
if _, present := nc.urls[curl]; !present {
hasNew = true
}
nc.addURLToPool(fmt.Sprintf("%s://%s", nc.connScheme(), curl), true, saveTLS)
}
if hasNew && !nc.initc && nc.Opts.DiscoveredServersCB != nil {
nc.ach.push(func() { nc.Opts.DiscoveredServersCB(nc) })
}
return nil
} | [
"func",
"(",
"nc",
"*",
"Conn",
")",
"processInfo",
"(",
"info",
"string",
")",
"error",
"{",
"if",
"info",
"==",
"_EMPTY_",
"{",
"return",
"nil",
"\n",
"}",
"\n",
"ncInfo",
":=",
"serverInfo",
"{",
"}",
"\n",
"if",
"err",
":=",
"json",
".",
"Unmarshal",
"(",
"[",
"]",
"byte",
"(",
"info",
")",
",",
"&",
"ncInfo",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"nc",
".",
"info",
"=",
"ncInfo",
"\n",
"if",
"len",
"(",
"ncInfo",
".",
"ConnectURLs",
")",
"==",
"0",
"{",
"return",
"nil",
"\n",
"}",
"\n",
"hasNew",
":=",
"false",
"\n",
"urls",
":=",
"nc",
".",
"info",
".",
"ConnectURLs",
"\n",
"tmp",
":=",
"make",
"(",
"map",
"[",
"string",
"]",
"struct",
"{",
"}",
",",
"len",
"(",
"urls",
")",
")",
"\n",
"for",
"_",
",",
"curl",
":=",
"range",
"urls",
"{",
"tmp",
"[",
"curl",
"]",
"=",
"struct",
"{",
"}",
"{",
"}",
"\n",
"}",
"\n",
"sp",
":=",
"nc",
".",
"srvPool",
"\n",
"for",
"i",
":=",
"0",
";",
"i",
"<",
"len",
"(",
"sp",
")",
";",
"i",
"++",
"{",
"srv",
":=",
"sp",
"[",
"i",
"]",
"\n",
"curl",
":=",
"srv",
".",
"url",
".",
"Host",
"\n",
"_",
",",
"inInfo",
":=",
"tmp",
"[",
"curl",
"]",
"\n",
"delete",
"(",
"tmp",
",",
"curl",
")",
"\n",
"if",
"!",
"srv",
".",
"isImplicit",
"||",
"srv",
".",
"url",
"==",
"nc",
".",
"current",
".",
"url",
"{",
"continue",
"\n",
"}",
"\n",
"if",
"!",
"inInfo",
"{",
"copy",
"(",
"sp",
"[",
"i",
":",
"]",
",",
"sp",
"[",
"i",
"+",
"1",
":",
"]",
")",
"\n",
"nc",
".",
"srvPool",
"=",
"sp",
"[",
":",
"len",
"(",
"sp",
")",
"-",
"1",
"]",
"\n",
"sp",
"=",
"nc",
".",
"srvPool",
"\n",
"i",
"--",
"\n",
"}",
"\n",
"}",
"\n",
"saveTLS",
":=",
"nc",
".",
"current",
"!=",
"nil",
"&&",
"!",
"hostIsIP",
"(",
"nc",
".",
"current",
".",
"url",
")",
"\n",
"for",
"curl",
":=",
"range",
"tmp",
"{",
"if",
"_",
",",
"present",
":=",
"nc",
".",
"urls",
"[",
"curl",
"]",
";",
"!",
"present",
"{",
"hasNew",
"=",
"true",
"\n",
"}",
"\n",
"nc",
".",
"addURLToPool",
"(",
"fmt",
".",
"Sprintf",
"(",
"\"%s://%s\"",
",",
"nc",
".",
"connScheme",
"(",
")",
",",
"curl",
")",
",",
"true",
",",
"saveTLS",
")",
"\n",
"}",
"\n",
"if",
"hasNew",
"&&",
"!",
"nc",
".",
"initc",
"&&",
"nc",
".",
"Opts",
".",
"DiscoveredServersCB",
"!=",
"nil",
"{",
"nc",
".",
"ach",
".",
"push",
"(",
"func",
"(",
")",
"{",
"nc",
".",
"Opts",
".",
"DiscoveredServersCB",
"(",
"nc",
")",
"}",
")",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}"
] | // processInfo is used to parse the info messages sent
// from the server.
// This function may update the server pool. | [
"processInfo",
"is",
"used",
"to",
"parse",
"the",
"info",
"messages",
"sent",
"from",
"the",
"server",
".",
"This",
"function",
"may",
"update",
"the",
"server",
"pool",
"."
] | 36d30b0ba7aa260ae25b4f3d312b2a700106fd78 | https://github.com/nats-io/go-nats/blob/36d30b0ba7aa260ae25b4f3d312b2a700106fd78/nats.go#L2285-L2357 | train |
nats-io/go-nats | nats.go | processAsyncInfo | func (nc *Conn) processAsyncInfo(info []byte) {
nc.mu.Lock()
// Ignore errors, we will simply not update the server pool...
nc.processInfo(string(info))
nc.mu.Unlock()
} | go | func (nc *Conn) processAsyncInfo(info []byte) {
nc.mu.Lock()
// Ignore errors, we will simply not update the server pool...
nc.processInfo(string(info))
nc.mu.Unlock()
} | [
"func",
"(",
"nc",
"*",
"Conn",
")",
"processAsyncInfo",
"(",
"info",
"[",
"]",
"byte",
")",
"{",
"nc",
".",
"mu",
".",
"Lock",
"(",
")",
"\n",
"nc",
".",
"processInfo",
"(",
"string",
"(",
"info",
")",
")",
"\n",
"nc",
".",
"mu",
".",
"Unlock",
"(",
")",
"\n",
"}"
] | // processAsyncInfo does the same than processInfo, but is called
// from the parser. Calls processInfo under connection's lock
// protection. | [
"processAsyncInfo",
"does",
"the",
"same",
"than",
"processInfo",
"but",
"is",
"called",
"from",
"the",
"parser",
".",
"Calls",
"processInfo",
"under",
"connection",
"s",
"lock",
"protection",
"."
] | 36d30b0ba7aa260ae25b4f3d312b2a700106fd78 | https://github.com/nats-io/go-nats/blob/36d30b0ba7aa260ae25b4f3d312b2a700106fd78/nats.go#L2362-L2367 | train |
nats-io/go-nats | nats.go | LastError | func (nc *Conn) LastError() error {
if nc == nil {
return ErrInvalidConnection
}
nc.mu.RLock()
err := nc.err
nc.mu.RUnlock()
return err
} | go | func (nc *Conn) LastError() error {
if nc == nil {
return ErrInvalidConnection
}
nc.mu.RLock()
err := nc.err
nc.mu.RUnlock()
return err
} | [
"func",
"(",
"nc",
"*",
"Conn",
")",
"LastError",
"(",
")",
"error",
"{",
"if",
"nc",
"==",
"nil",
"{",
"return",
"ErrInvalidConnection",
"\n",
"}",
"\n",
"nc",
".",
"mu",
".",
"RLock",
"(",
")",
"\n",
"err",
":=",
"nc",
".",
"err",
"\n",
"nc",
".",
"mu",
".",
"RUnlock",
"(",
")",
"\n",
"return",
"err",
"\n",
"}"
] | // LastError reports the last error encountered via the connection.
// It can be used reliably within ClosedCB in order to find out reason
// why connection was closed for example. | [
"LastError",
"reports",
"the",
"last",
"error",
"encountered",
"via",
"the",
"connection",
".",
"It",
"can",
"be",
"used",
"reliably",
"within",
"ClosedCB",
"in",
"order",
"to",
"find",
"out",
"reason",
"why",
"connection",
"was",
"closed",
"for",
"example",
"."
] | 36d30b0ba7aa260ae25b4f3d312b2a700106fd78 | https://github.com/nats-io/go-nats/blob/36d30b0ba7aa260ae25b4f3d312b2a700106fd78/nats.go#L2372-L2380 | train |
nats-io/go-nats | nats.go | processErr | func (nc *Conn) processErr(ie string) {
// Trim, remove quotes
ne := normalizeErr(ie)
// convert to lower case.
e := strings.ToLower(ne)
// FIXME(dlc) - process Slow Consumer signals special.
if e == STALE_CONNECTION {
nc.processOpErr(ErrStaleConnection)
} else if strings.HasPrefix(e, PERMISSIONS_ERR) {
nc.processPermissionsViolation(ne)
} else if strings.HasPrefix(e, AUTHORIZATION_ERR) {
nc.processAuthorizationViolation(ne)
} else {
nc.mu.Lock()
nc.err = errors.New("nats: " + ne)
nc.mu.Unlock()
nc.Close()
}
} | go | func (nc *Conn) processErr(ie string) {
// Trim, remove quotes
ne := normalizeErr(ie)
// convert to lower case.
e := strings.ToLower(ne)
// FIXME(dlc) - process Slow Consumer signals special.
if e == STALE_CONNECTION {
nc.processOpErr(ErrStaleConnection)
} else if strings.HasPrefix(e, PERMISSIONS_ERR) {
nc.processPermissionsViolation(ne)
} else if strings.HasPrefix(e, AUTHORIZATION_ERR) {
nc.processAuthorizationViolation(ne)
} else {
nc.mu.Lock()
nc.err = errors.New("nats: " + ne)
nc.mu.Unlock()
nc.Close()
}
} | [
"func",
"(",
"nc",
"*",
"Conn",
")",
"processErr",
"(",
"ie",
"string",
")",
"{",
"ne",
":=",
"normalizeErr",
"(",
"ie",
")",
"\n",
"e",
":=",
"strings",
".",
"ToLower",
"(",
"ne",
")",
"\n",
"if",
"e",
"==",
"STALE_CONNECTION",
"{",
"nc",
".",
"processOpErr",
"(",
"ErrStaleConnection",
")",
"\n",
"}",
"else",
"if",
"strings",
".",
"HasPrefix",
"(",
"e",
",",
"PERMISSIONS_ERR",
")",
"{",
"nc",
".",
"processPermissionsViolation",
"(",
"ne",
")",
"\n",
"}",
"else",
"if",
"strings",
".",
"HasPrefix",
"(",
"e",
",",
"AUTHORIZATION_ERR",
")",
"{",
"nc",
".",
"processAuthorizationViolation",
"(",
"ne",
")",
"\n",
"}",
"else",
"{",
"nc",
".",
"mu",
".",
"Lock",
"(",
")",
"\n",
"nc",
".",
"err",
"=",
"errors",
".",
"New",
"(",
"\"nats: \"",
"+",
"ne",
")",
"\n",
"nc",
".",
"mu",
".",
"Unlock",
"(",
")",
"\n",
"nc",
".",
"Close",
"(",
")",
"\n",
"}",
"\n",
"}"
] | // processErr processes any error messages from the server and
// sets the connection's lastError. | [
"processErr",
"processes",
"any",
"error",
"messages",
"from",
"the",
"server",
"and",
"sets",
"the",
"connection",
"s",
"lastError",
"."
] | 36d30b0ba7aa260ae25b4f3d312b2a700106fd78 | https://github.com/nats-io/go-nats/blob/36d30b0ba7aa260ae25b4f3d312b2a700106fd78/nats.go#L2384-L2403 | train |
nats-io/go-nats | nats.go | Publish | func (nc *Conn) Publish(subj string, data []byte) error {
return nc.publish(subj, _EMPTY_, data)
} | go | func (nc *Conn) Publish(subj string, data []byte) error {
return nc.publish(subj, _EMPTY_, data)
} | [
"func",
"(",
"nc",
"*",
"Conn",
")",
"Publish",
"(",
"subj",
"string",
",",
"data",
"[",
"]",
"byte",
")",
"error",
"{",
"return",
"nc",
".",
"publish",
"(",
"subj",
",",
"_EMPTY_",
",",
"data",
")",
"\n",
"}"
] | // Publish publishes the data argument to the given subject. The data
// argument is left untouched and needs to be correctly interpreted on
// the receiver. | [
"Publish",
"publishes",
"the",
"data",
"argument",
"to",
"the",
"given",
"subject",
".",
"The",
"data",
"argument",
"is",
"left",
"untouched",
"and",
"needs",
"to",
"be",
"correctly",
"interpreted",
"on",
"the",
"receiver",
"."
] | 36d30b0ba7aa260ae25b4f3d312b2a700106fd78 | https://github.com/nats-io/go-nats/blob/36d30b0ba7aa260ae25b4f3d312b2a700106fd78/nats.go#L2419-L2421 | train |
nats-io/go-nats | nats.go | PublishMsg | func (nc *Conn) PublishMsg(m *Msg) error {
if m == nil {
return ErrInvalidMsg
}
return nc.publish(m.Subject, m.Reply, m.Data)
} | go | func (nc *Conn) PublishMsg(m *Msg) error {
if m == nil {
return ErrInvalidMsg
}
return nc.publish(m.Subject, m.Reply, m.Data)
} | [
"func",
"(",
"nc",
"*",
"Conn",
")",
"PublishMsg",
"(",
"m",
"*",
"Msg",
")",
"error",
"{",
"if",
"m",
"==",
"nil",
"{",
"return",
"ErrInvalidMsg",
"\n",
"}",
"\n",
"return",
"nc",
".",
"publish",
"(",
"m",
".",
"Subject",
",",
"m",
".",
"Reply",
",",
"m",
".",
"Data",
")",
"\n",
"}"
] | // PublishMsg publishes the Msg structure, which includes the
// Subject, an optional Reply and an optional Data field. | [
"PublishMsg",
"publishes",
"the",
"Msg",
"structure",
"which",
"includes",
"the",
"Subject",
"an",
"optional",
"Reply",
"and",
"an",
"optional",
"Data",
"field",
"."
] | 36d30b0ba7aa260ae25b4f3d312b2a700106fd78 | https://github.com/nats-io/go-nats/blob/36d30b0ba7aa260ae25b4f3d312b2a700106fd78/nats.go#L2425-L2430 | train |
nats-io/go-nats | nats.go | publish | func (nc *Conn) publish(subj, reply string, data []byte) error {
if nc == nil {
return ErrInvalidConnection
}
if subj == "" {
return ErrBadSubject
}
nc.mu.Lock()
if nc.isClosed() {
nc.mu.Unlock()
return ErrConnectionClosed
}
if nc.isDrainingPubs() {
nc.mu.Unlock()
return ErrConnectionDraining
}
// Proactively reject payloads over the threshold set by server.
msgSize := int64(len(data))
if msgSize > nc.info.MaxPayload {
nc.mu.Unlock()
return ErrMaxPayload
}
// Check if we are reconnecting, and if so check if
// we have exceeded our reconnect outbound buffer limits.
if nc.isReconnecting() {
// Flush to underlying buffer.
nc.bw.Flush()
// Check if we are over
if nc.pending.Len() >= nc.Opts.ReconnectBufSize {
nc.mu.Unlock()
return ErrReconnectBufExceeded
}
}
msgh := nc.scratch[:len(_PUB_P_)]
msgh = append(msgh, subj...)
msgh = append(msgh, ' ')
if reply != "" {
msgh = append(msgh, reply...)
msgh = append(msgh, ' ')
}
// We could be smarter here, but simple loop is ok,
// just avoid strconv in fast path
// FIXME(dlc) - Find a better way here.
// msgh = strconv.AppendInt(msgh, int64(len(data)), 10)
var b [12]byte
var i = len(b)
if len(data) > 0 {
for l := len(data); l > 0; l /= 10 {
i -= 1
b[i] = digits[l%10]
}
} else {
i -= 1
b[i] = digits[0]
}
msgh = append(msgh, b[i:]...)
msgh = append(msgh, _CRLF_...)
_, err := nc.bw.Write(msgh)
if err == nil {
_, err = nc.bw.Write(data)
}
if err == nil {
_, err = nc.bw.WriteString(_CRLF_)
}
if err != nil {
nc.mu.Unlock()
return err
}
nc.OutMsgs++
nc.OutBytes += uint64(len(data))
if len(nc.fch) == 0 {
nc.kickFlusher()
}
nc.mu.Unlock()
return nil
} | go | func (nc *Conn) publish(subj, reply string, data []byte) error {
if nc == nil {
return ErrInvalidConnection
}
if subj == "" {
return ErrBadSubject
}
nc.mu.Lock()
if nc.isClosed() {
nc.mu.Unlock()
return ErrConnectionClosed
}
if nc.isDrainingPubs() {
nc.mu.Unlock()
return ErrConnectionDraining
}
// Proactively reject payloads over the threshold set by server.
msgSize := int64(len(data))
if msgSize > nc.info.MaxPayload {
nc.mu.Unlock()
return ErrMaxPayload
}
// Check if we are reconnecting, and if so check if
// we have exceeded our reconnect outbound buffer limits.
if nc.isReconnecting() {
// Flush to underlying buffer.
nc.bw.Flush()
// Check if we are over
if nc.pending.Len() >= nc.Opts.ReconnectBufSize {
nc.mu.Unlock()
return ErrReconnectBufExceeded
}
}
msgh := nc.scratch[:len(_PUB_P_)]
msgh = append(msgh, subj...)
msgh = append(msgh, ' ')
if reply != "" {
msgh = append(msgh, reply...)
msgh = append(msgh, ' ')
}
// We could be smarter here, but simple loop is ok,
// just avoid strconv in fast path
// FIXME(dlc) - Find a better way here.
// msgh = strconv.AppendInt(msgh, int64(len(data)), 10)
var b [12]byte
var i = len(b)
if len(data) > 0 {
for l := len(data); l > 0; l /= 10 {
i -= 1
b[i] = digits[l%10]
}
} else {
i -= 1
b[i] = digits[0]
}
msgh = append(msgh, b[i:]...)
msgh = append(msgh, _CRLF_...)
_, err := nc.bw.Write(msgh)
if err == nil {
_, err = nc.bw.Write(data)
}
if err == nil {
_, err = nc.bw.WriteString(_CRLF_)
}
if err != nil {
nc.mu.Unlock()
return err
}
nc.OutMsgs++
nc.OutBytes += uint64(len(data))
if len(nc.fch) == 0 {
nc.kickFlusher()
}
nc.mu.Unlock()
return nil
} | [
"func",
"(",
"nc",
"*",
"Conn",
")",
"publish",
"(",
"subj",
",",
"reply",
"string",
",",
"data",
"[",
"]",
"byte",
")",
"error",
"{",
"if",
"nc",
"==",
"nil",
"{",
"return",
"ErrInvalidConnection",
"\n",
"}",
"\n",
"if",
"subj",
"==",
"\"\"",
"{",
"return",
"ErrBadSubject",
"\n",
"}",
"\n",
"nc",
".",
"mu",
".",
"Lock",
"(",
")",
"\n",
"if",
"nc",
".",
"isClosed",
"(",
")",
"{",
"nc",
".",
"mu",
".",
"Unlock",
"(",
")",
"\n",
"return",
"ErrConnectionClosed",
"\n",
"}",
"\n",
"if",
"nc",
".",
"isDrainingPubs",
"(",
")",
"{",
"nc",
".",
"mu",
".",
"Unlock",
"(",
")",
"\n",
"return",
"ErrConnectionDraining",
"\n",
"}",
"\n",
"msgSize",
":=",
"int64",
"(",
"len",
"(",
"data",
")",
")",
"\n",
"if",
"msgSize",
">",
"nc",
".",
"info",
".",
"MaxPayload",
"{",
"nc",
".",
"mu",
".",
"Unlock",
"(",
")",
"\n",
"return",
"ErrMaxPayload",
"\n",
"}",
"\n",
"if",
"nc",
".",
"isReconnecting",
"(",
")",
"{",
"nc",
".",
"bw",
".",
"Flush",
"(",
")",
"\n",
"if",
"nc",
".",
"pending",
".",
"Len",
"(",
")",
">=",
"nc",
".",
"Opts",
".",
"ReconnectBufSize",
"{",
"nc",
".",
"mu",
".",
"Unlock",
"(",
")",
"\n",
"return",
"ErrReconnectBufExceeded",
"\n",
"}",
"\n",
"}",
"\n",
"msgh",
":=",
"nc",
".",
"scratch",
"[",
":",
"len",
"(",
"_PUB_P_",
")",
"]",
"\n",
"msgh",
"=",
"append",
"(",
"msgh",
",",
"subj",
"...",
")",
"\n",
"msgh",
"=",
"append",
"(",
"msgh",
",",
"' '",
")",
"\n",
"if",
"reply",
"!=",
"\"\"",
"{",
"msgh",
"=",
"append",
"(",
"msgh",
",",
"reply",
"...",
")",
"\n",
"msgh",
"=",
"append",
"(",
"msgh",
",",
"' '",
")",
"\n",
"}",
"\n",
"var",
"b",
"[",
"12",
"]",
"byte",
"\n",
"var",
"i",
"=",
"len",
"(",
"b",
")",
"\n",
"if",
"len",
"(",
"data",
")",
">",
"0",
"{",
"for",
"l",
":=",
"len",
"(",
"data",
")",
";",
"l",
">",
"0",
";",
"l",
"/=",
"10",
"{",
"i",
"-=",
"1",
"\n",
"b",
"[",
"i",
"]",
"=",
"digits",
"[",
"l",
"%",
"10",
"]",
"\n",
"}",
"\n",
"}",
"else",
"{",
"i",
"-=",
"1",
"\n",
"b",
"[",
"i",
"]",
"=",
"digits",
"[",
"0",
"]",
"\n",
"}",
"\n",
"msgh",
"=",
"append",
"(",
"msgh",
",",
"b",
"[",
"i",
":",
"]",
"...",
")",
"\n",
"msgh",
"=",
"append",
"(",
"msgh",
",",
"_CRLF_",
"...",
")",
"\n",
"_",
",",
"err",
":=",
"nc",
".",
"bw",
".",
"Write",
"(",
"msgh",
")",
"\n",
"if",
"err",
"==",
"nil",
"{",
"_",
",",
"err",
"=",
"nc",
".",
"bw",
".",
"Write",
"(",
"data",
")",
"\n",
"}",
"\n",
"if",
"err",
"==",
"nil",
"{",
"_",
",",
"err",
"=",
"nc",
".",
"bw",
".",
"WriteString",
"(",
"_CRLF_",
")",
"\n",
"}",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"nc",
".",
"mu",
".",
"Unlock",
"(",
")",
"\n",
"return",
"err",
"\n",
"}",
"\n",
"nc",
".",
"OutMsgs",
"++",
"\n",
"nc",
".",
"OutBytes",
"+=",
"uint64",
"(",
"len",
"(",
"data",
")",
")",
"\n",
"if",
"len",
"(",
"nc",
".",
"fch",
")",
"==",
"0",
"{",
"nc",
".",
"kickFlusher",
"(",
")",
"\n",
"}",
"\n",
"nc",
".",
"mu",
".",
"Unlock",
"(",
")",
"\n",
"return",
"nil",
"\n",
"}"
] | // publish is the internal function to publish messages to a nats-server.
// Sends a protocol data message by queuing into the bufio writer
// and kicking the flush go routine. These writes should be protected. | [
"publish",
"is",
"the",
"internal",
"function",
"to",
"publish",
"messages",
"to",
"a",
"nats",
"-",
"server",
".",
"Sends",
"a",
"protocol",
"data",
"message",
"by",
"queuing",
"into",
"the",
"bufio",
"writer",
"and",
"kicking",
"the",
"flush",
"go",
"routine",
".",
"These",
"writes",
"should",
"be",
"protected",
"."
] | 36d30b0ba7aa260ae25b4f3d312b2a700106fd78 | https://github.com/nats-io/go-nats/blob/36d30b0ba7aa260ae25b4f3d312b2a700106fd78/nats.go#L2445-L2531 | train |
nats-io/go-nats | nats.go | respHandler | func (nc *Conn) respHandler(m *Msg) {
rt := respToken(m.Subject)
nc.mu.Lock()
// Just return if closed.
if nc.isClosed() {
nc.mu.Unlock()
return
}
// Grab mch
mch := nc.respMap[rt]
// Delete the key regardless, one response only.
// FIXME(dlc) - should we track responses past 1
// just statistics wise?
delete(nc.respMap, rt)
nc.mu.Unlock()
// Don't block, let Request timeout instead, mch is
// buffered and we should delete the key before a
// second response is processed.
select {
case mch <- m:
default:
return
}
} | go | func (nc *Conn) respHandler(m *Msg) {
rt := respToken(m.Subject)
nc.mu.Lock()
// Just return if closed.
if nc.isClosed() {
nc.mu.Unlock()
return
}
// Grab mch
mch := nc.respMap[rt]
// Delete the key regardless, one response only.
// FIXME(dlc) - should we track responses past 1
// just statistics wise?
delete(nc.respMap, rt)
nc.mu.Unlock()
// Don't block, let Request timeout instead, mch is
// buffered and we should delete the key before a
// second response is processed.
select {
case mch <- m:
default:
return
}
} | [
"func",
"(",
"nc",
"*",
"Conn",
")",
"respHandler",
"(",
"m",
"*",
"Msg",
")",
"{",
"rt",
":=",
"respToken",
"(",
"m",
".",
"Subject",
")",
"\n",
"nc",
".",
"mu",
".",
"Lock",
"(",
")",
"\n",
"if",
"nc",
".",
"isClosed",
"(",
")",
"{",
"nc",
".",
"mu",
".",
"Unlock",
"(",
")",
"\n",
"return",
"\n",
"}",
"\n",
"mch",
":=",
"nc",
".",
"respMap",
"[",
"rt",
"]",
"\n",
"delete",
"(",
"nc",
".",
"respMap",
",",
"rt",
")",
"\n",
"nc",
".",
"mu",
".",
"Unlock",
"(",
")",
"\n",
"select",
"{",
"case",
"mch",
"<-",
"m",
":",
"default",
":",
"return",
"\n",
"}",
"\n",
"}"
] | // respHandler is the global response handler. It will look up
// the appropriate channel based on the last token and place
// the message on the channel if possible. | [
"respHandler",
"is",
"the",
"global",
"response",
"handler",
".",
"It",
"will",
"look",
"up",
"the",
"appropriate",
"channel",
"based",
"on",
"the",
"last",
"token",
"and",
"place",
"the",
"message",
"on",
"the",
"channel",
"if",
"possible",
"."
] | 36d30b0ba7aa260ae25b4f3d312b2a700106fd78 | https://github.com/nats-io/go-nats/blob/36d30b0ba7aa260ae25b4f3d312b2a700106fd78/nats.go#L2536-L2562 | train |
nats-io/go-nats | nats.go | createRespMux | func (nc *Conn) createRespMux(respSub string) error {
s, err := nc.Subscribe(respSub, nc.respHandler)
if err != nil {
return err
}
nc.mu.Lock()
nc.respMux = s
nc.mu.Unlock()
return nil
} | go | func (nc *Conn) createRespMux(respSub string) error {
s, err := nc.Subscribe(respSub, nc.respHandler)
if err != nil {
return err
}
nc.mu.Lock()
nc.respMux = s
nc.mu.Unlock()
return nil
} | [
"func",
"(",
"nc",
"*",
"Conn",
")",
"createRespMux",
"(",
"respSub",
"string",
")",
"error",
"{",
"s",
",",
"err",
":=",
"nc",
".",
"Subscribe",
"(",
"respSub",
",",
"nc",
".",
"respHandler",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"nc",
".",
"mu",
".",
"Lock",
"(",
")",
"\n",
"nc",
".",
"respMux",
"=",
"s",
"\n",
"nc",
".",
"mu",
".",
"Unlock",
"(",
")",
"\n",
"return",
"nil",
"\n",
"}"
] | // Create the response subscription we will use for all
// new style responses. This will be on an _INBOX with an
// additional terminal token. The subscription will be on
// a wildcard. Caller is responsible for ensuring this is
// only called once. | [
"Create",
"the",
"response",
"subscription",
"we",
"will",
"use",
"for",
"all",
"new",
"style",
"responses",
".",
"This",
"will",
"be",
"on",
"an",
"_INBOX",
"with",
"an",
"additional",
"terminal",
"token",
".",
"The",
"subscription",
"will",
"be",
"on",
"a",
"wildcard",
".",
"Caller",
"is",
"responsible",
"for",
"ensuring",
"this",
"is",
"only",
"called",
"once",
"."
] | 36d30b0ba7aa260ae25b4f3d312b2a700106fd78 | https://github.com/nats-io/go-nats/blob/36d30b0ba7aa260ae25b4f3d312b2a700106fd78/nats.go#L2569-L2578 | train |
nats-io/go-nats | nats.go | Request | func (nc *Conn) Request(subj string, data []byte, timeout time.Duration) (*Msg, error) {
if nc == nil {
return nil, ErrInvalidConnection
}
nc.mu.Lock()
// If user wants the old style.
if nc.Opts.UseOldRequestStyle {
nc.mu.Unlock()
return nc.oldRequest(subj, data, timeout)
}
// Do setup for the new style.
if nc.respMap == nil {
nc.initNewResp()
}
// Create literal Inbox and map to a chan msg.
mch := make(chan *Msg, RequestChanLen)
respInbox := nc.newRespInbox()
token := respToken(respInbox)
nc.respMap[token] = mch
createSub := nc.respMux == nil
ginbox := nc.respSub
nc.mu.Unlock()
if createSub {
// Make sure scoped subscription is setup only once.
var err error
nc.respSetup.Do(func() { err = nc.createRespMux(ginbox) })
if err != nil {
return nil, err
}
}
if err := nc.PublishRequest(subj, respInbox, data); err != nil {
return nil, err
}
t := globalTimerPool.Get(timeout)
defer globalTimerPool.Put(t)
var ok bool
var msg *Msg
select {
case msg, ok = <-mch:
if !ok {
return nil, ErrConnectionClosed
}
case <-t.C:
nc.mu.Lock()
delete(nc.respMap, token)
nc.mu.Unlock()
return nil, ErrTimeout
}
return msg, nil
} | go | func (nc *Conn) Request(subj string, data []byte, timeout time.Duration) (*Msg, error) {
if nc == nil {
return nil, ErrInvalidConnection
}
nc.mu.Lock()
// If user wants the old style.
if nc.Opts.UseOldRequestStyle {
nc.mu.Unlock()
return nc.oldRequest(subj, data, timeout)
}
// Do setup for the new style.
if nc.respMap == nil {
nc.initNewResp()
}
// Create literal Inbox and map to a chan msg.
mch := make(chan *Msg, RequestChanLen)
respInbox := nc.newRespInbox()
token := respToken(respInbox)
nc.respMap[token] = mch
createSub := nc.respMux == nil
ginbox := nc.respSub
nc.mu.Unlock()
if createSub {
// Make sure scoped subscription is setup only once.
var err error
nc.respSetup.Do(func() { err = nc.createRespMux(ginbox) })
if err != nil {
return nil, err
}
}
if err := nc.PublishRequest(subj, respInbox, data); err != nil {
return nil, err
}
t := globalTimerPool.Get(timeout)
defer globalTimerPool.Put(t)
var ok bool
var msg *Msg
select {
case msg, ok = <-mch:
if !ok {
return nil, ErrConnectionClosed
}
case <-t.C:
nc.mu.Lock()
delete(nc.respMap, token)
nc.mu.Unlock()
return nil, ErrTimeout
}
return msg, nil
} | [
"func",
"(",
"nc",
"*",
"Conn",
")",
"Request",
"(",
"subj",
"string",
",",
"data",
"[",
"]",
"byte",
",",
"timeout",
"time",
".",
"Duration",
")",
"(",
"*",
"Msg",
",",
"error",
")",
"{",
"if",
"nc",
"==",
"nil",
"{",
"return",
"nil",
",",
"ErrInvalidConnection",
"\n",
"}",
"\n",
"nc",
".",
"mu",
".",
"Lock",
"(",
")",
"\n",
"if",
"nc",
".",
"Opts",
".",
"UseOldRequestStyle",
"{",
"nc",
".",
"mu",
".",
"Unlock",
"(",
")",
"\n",
"return",
"nc",
".",
"oldRequest",
"(",
"subj",
",",
"data",
",",
"timeout",
")",
"\n",
"}",
"\n",
"if",
"nc",
".",
"respMap",
"==",
"nil",
"{",
"nc",
".",
"initNewResp",
"(",
")",
"\n",
"}",
"\n",
"mch",
":=",
"make",
"(",
"chan",
"*",
"Msg",
",",
"RequestChanLen",
")",
"\n",
"respInbox",
":=",
"nc",
".",
"newRespInbox",
"(",
")",
"\n",
"token",
":=",
"respToken",
"(",
"respInbox",
")",
"\n",
"nc",
".",
"respMap",
"[",
"token",
"]",
"=",
"mch",
"\n",
"createSub",
":=",
"nc",
".",
"respMux",
"==",
"nil",
"\n",
"ginbox",
":=",
"nc",
".",
"respSub",
"\n",
"nc",
".",
"mu",
".",
"Unlock",
"(",
")",
"\n",
"if",
"createSub",
"{",
"var",
"err",
"error",
"\n",
"nc",
".",
"respSetup",
".",
"Do",
"(",
"func",
"(",
")",
"{",
"err",
"=",
"nc",
".",
"createRespMux",
"(",
"ginbox",
")",
"}",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"}",
"\n",
"if",
"err",
":=",
"nc",
".",
"PublishRequest",
"(",
"subj",
",",
"respInbox",
",",
"data",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"t",
":=",
"globalTimerPool",
".",
"Get",
"(",
"timeout",
")",
"\n",
"defer",
"globalTimerPool",
".",
"Put",
"(",
"t",
")",
"\n",
"var",
"ok",
"bool",
"\n",
"var",
"msg",
"*",
"Msg",
"\n",
"select",
"{",
"case",
"msg",
",",
"ok",
"=",
"<-",
"mch",
":",
"if",
"!",
"ok",
"{",
"return",
"nil",
",",
"ErrConnectionClosed",
"\n",
"}",
"\n",
"case",
"<-",
"t",
".",
"C",
":",
"nc",
".",
"mu",
".",
"Lock",
"(",
")",
"\n",
"delete",
"(",
"nc",
".",
"respMap",
",",
"token",
")",
"\n",
"nc",
".",
"mu",
".",
"Unlock",
"(",
")",
"\n",
"return",
"nil",
",",
"ErrTimeout",
"\n",
"}",
"\n",
"return",
"msg",
",",
"nil",
"\n",
"}"
] | // Request will send a request payload and deliver the response message,
// or an error, including a timeout if no message was received properly. | [
"Request",
"will",
"send",
"a",
"request",
"payload",
"and",
"deliver",
"the",
"response",
"message",
"or",
"an",
"error",
"including",
"a",
"timeout",
"if",
"no",
"message",
"was",
"received",
"properly",
"."
] | 36d30b0ba7aa260ae25b4f3d312b2a700106fd78 | https://github.com/nats-io/go-nats/blob/36d30b0ba7aa260ae25b4f3d312b2a700106fd78/nats.go#L2582-L2639 | train |
nats-io/go-nats | nats.go | NewInbox | func NewInbox() string {
var b [inboxPrefixLen + nuidSize]byte
pres := b[:inboxPrefixLen]
copy(pres, InboxPrefix)
ns := b[inboxPrefixLen:]
copy(ns, nuid.Next())
return string(b[:])
} | go | func NewInbox() string {
var b [inboxPrefixLen + nuidSize]byte
pres := b[:inboxPrefixLen]
copy(pres, InboxPrefix)
ns := b[inboxPrefixLen:]
copy(ns, nuid.Next())
return string(b[:])
} | [
"func",
"NewInbox",
"(",
")",
"string",
"{",
"var",
"b",
"[",
"inboxPrefixLen",
"+",
"nuidSize",
"]",
"byte",
"\n",
"pres",
":=",
"b",
"[",
":",
"inboxPrefixLen",
"]",
"\n",
"copy",
"(",
"pres",
",",
"InboxPrefix",
")",
"\n",
"ns",
":=",
"b",
"[",
"inboxPrefixLen",
":",
"]",
"\n",
"copy",
"(",
"ns",
",",
"nuid",
".",
"Next",
"(",
")",
")",
"\n",
"return",
"string",
"(",
"b",
"[",
":",
"]",
")",
"\n",
"}"
] | // NewInbox will return an inbox string which can be used for directed replies from
// subscribers. These are guaranteed to be unique, but can be shared and subscribed
// to by others. | [
"NewInbox",
"will",
"return",
"an",
"inbox",
"string",
"which",
"can",
"be",
"used",
"for",
"directed",
"replies",
"from",
"subscribers",
".",
"These",
"are",
"guaranteed",
"to",
"be",
"unique",
"but",
"can",
"be",
"shared",
"and",
"subscribed",
"to",
"by",
"others",
"."
] | 36d30b0ba7aa260ae25b4f3d312b2a700106fd78 | https://github.com/nats-io/go-nats/blob/36d30b0ba7aa260ae25b4f3d312b2a700106fd78/nats.go#L2675-L2682 | train |
nats-io/go-nats | nats.go | initNewResp | func (nc *Conn) initNewResp() {
// _INBOX wildcard
nc.respSub = fmt.Sprintf("%s.*", NewInbox())
nc.respMap = make(map[string]chan *Msg)
nc.respRand = rand.New(rand.NewSource(time.Now().UnixNano()))
} | go | func (nc *Conn) initNewResp() {
// _INBOX wildcard
nc.respSub = fmt.Sprintf("%s.*", NewInbox())
nc.respMap = make(map[string]chan *Msg)
nc.respRand = rand.New(rand.NewSource(time.Now().UnixNano()))
} | [
"func",
"(",
"nc",
"*",
"Conn",
")",
"initNewResp",
"(",
")",
"{",
"nc",
".",
"respSub",
"=",
"fmt",
".",
"Sprintf",
"(",
"\"%s.*\"",
",",
"NewInbox",
"(",
")",
")",
"\n",
"nc",
".",
"respMap",
"=",
"make",
"(",
"map",
"[",
"string",
"]",
"chan",
"*",
"Msg",
")",
"\n",
"nc",
".",
"respRand",
"=",
"rand",
".",
"New",
"(",
"rand",
".",
"NewSource",
"(",
"time",
".",
"Now",
"(",
")",
".",
"UnixNano",
"(",
")",
")",
")",
"\n",
"}"
] | // Function to init new response structures. | [
"Function",
"to",
"init",
"new",
"response",
"structures",
"."
] | 36d30b0ba7aa260ae25b4f3d312b2a700106fd78 | https://github.com/nats-io/go-nats/blob/36d30b0ba7aa260ae25b4f3d312b2a700106fd78/nats.go#L2685-L2690 | train |
nats-io/go-nats | nats.go | newRespInbox | func (nc *Conn) newRespInbox() string {
if nc.respMap == nil {
nc.initNewResp()
}
var b [respInboxPrefixLen + replySuffixLen]byte
pres := b[:respInboxPrefixLen]
copy(pres, nc.respSub)
rn := nc.respRand.Int63()
for i, l := respInboxPrefixLen, rn; i < len(b); i++ {
b[i] = rdigits[l%base]
l /= base
}
return string(b[:])
} | go | func (nc *Conn) newRespInbox() string {
if nc.respMap == nil {
nc.initNewResp()
}
var b [respInboxPrefixLen + replySuffixLen]byte
pres := b[:respInboxPrefixLen]
copy(pres, nc.respSub)
rn := nc.respRand.Int63()
for i, l := respInboxPrefixLen, rn; i < len(b); i++ {
b[i] = rdigits[l%base]
l /= base
}
return string(b[:])
} | [
"func",
"(",
"nc",
"*",
"Conn",
")",
"newRespInbox",
"(",
")",
"string",
"{",
"if",
"nc",
".",
"respMap",
"==",
"nil",
"{",
"nc",
".",
"initNewResp",
"(",
")",
"\n",
"}",
"\n",
"var",
"b",
"[",
"respInboxPrefixLen",
"+",
"replySuffixLen",
"]",
"byte",
"\n",
"pres",
":=",
"b",
"[",
":",
"respInboxPrefixLen",
"]",
"\n",
"copy",
"(",
"pres",
",",
"nc",
".",
"respSub",
")",
"\n",
"rn",
":=",
"nc",
".",
"respRand",
".",
"Int63",
"(",
")",
"\n",
"for",
"i",
",",
"l",
":=",
"respInboxPrefixLen",
",",
"rn",
";",
"i",
"<",
"len",
"(",
"b",
")",
";",
"i",
"++",
"{",
"b",
"[",
"i",
"]",
"=",
"rdigits",
"[",
"l",
"%",
"base",
"]",
"\n",
"l",
"/=",
"base",
"\n",
"}",
"\n",
"return",
"string",
"(",
"b",
"[",
":",
"]",
")",
"\n",
"}"
] | // newRespInbox creates a new literal response subject
// that will trigger the mux subscription handler.
// Lock should be held. | [
"newRespInbox",
"creates",
"a",
"new",
"literal",
"response",
"subject",
"that",
"will",
"trigger",
"the",
"mux",
"subscription",
"handler",
".",
"Lock",
"should",
"be",
"held",
"."
] | 36d30b0ba7aa260ae25b4f3d312b2a700106fd78 | https://github.com/nats-io/go-nats/blob/36d30b0ba7aa260ae25b4f3d312b2a700106fd78/nats.go#L2695-L2708 | train |
nats-io/go-nats | nats.go | NewRespInbox | func (nc *Conn) NewRespInbox() string {
nc.mu.Lock()
s := nc.newRespInbox()
nc.mu.Unlock()
return s
} | go | func (nc *Conn) NewRespInbox() string {
nc.mu.Lock()
s := nc.newRespInbox()
nc.mu.Unlock()
return s
} | [
"func",
"(",
"nc",
"*",
"Conn",
")",
"NewRespInbox",
"(",
")",
"string",
"{",
"nc",
".",
"mu",
".",
"Lock",
"(",
")",
"\n",
"s",
":=",
"nc",
".",
"newRespInbox",
"(",
")",
"\n",
"nc",
".",
"mu",
".",
"Unlock",
"(",
")",
"\n",
"return",
"s",
"\n",
"}"
] | // NewRespInbox is the new format used for _INBOX. | [
"NewRespInbox",
"is",
"the",
"new",
"format",
"used",
"for",
"_INBOX",
"."
] | 36d30b0ba7aa260ae25b4f3d312b2a700106fd78 | https://github.com/nats-io/go-nats/blob/36d30b0ba7aa260ae25b4f3d312b2a700106fd78/nats.go#L2711-L2716 | train |
nats-io/go-nats | nats.go | QueueSubscribe | func (nc *Conn) QueueSubscribe(subj, queue string, cb MsgHandler) (*Subscription, error) {
return nc.subscribe(subj, queue, cb, nil, false)
} | go | func (nc *Conn) QueueSubscribe(subj, queue string, cb MsgHandler) (*Subscription, error) {
return nc.subscribe(subj, queue, cb, nil, false)
} | [
"func",
"(",
"nc",
"*",
"Conn",
")",
"QueueSubscribe",
"(",
"subj",
",",
"queue",
"string",
",",
"cb",
"MsgHandler",
")",
"(",
"*",
"Subscription",
",",
"error",
")",
"{",
"return",
"nc",
".",
"subscribe",
"(",
"subj",
",",
"queue",
",",
"cb",
",",
"nil",
",",
"false",
")",
"\n",
"}"
] | // QueueSubscribe creates an asynchronous queue subscriber on the given subject.
// All subscribers with the same queue name will form the queue group and
// only one member of the group will be selected to receive any given
// message asynchronously. | [
"QueueSubscribe",
"creates",
"an",
"asynchronous",
"queue",
"subscriber",
"on",
"the",
"given",
"subject",
".",
"All",
"subscribers",
"with",
"the",
"same",
"queue",
"name",
"will",
"form",
"the",
"queue",
"group",
"and",
"only",
"one",
"member",
"of",
"the",
"group",
"will",
"be",
"selected",
"to",
"receive",
"any",
"given",
"message",
"asynchronously",
"."
] | 36d30b0ba7aa260ae25b4f3d312b2a700106fd78 | https://github.com/nats-io/go-nats/blob/36d30b0ba7aa260ae25b4f3d312b2a700106fd78/nats.go#L2763-L2765 | train |
nats-io/go-nats | nats.go | subscribe | func (nc *Conn) subscribe(subj, queue string, cb MsgHandler, ch chan *Msg, isSync bool) (*Subscription, error) {
if nc == nil {
return nil, ErrInvalidConnection
}
nc.mu.Lock()
// ok here, but defer is generally expensive
defer nc.mu.Unlock()
// Check for some error conditions.
if nc.isClosed() {
return nil, ErrConnectionClosed
}
if nc.isDraining() {
return nil, ErrConnectionDraining
}
if cb == nil && ch == nil {
return nil, ErrBadSubscription
}
sub := &Subscription{Subject: subj, Queue: queue, mcb: cb, conn: nc}
// Set pending limits.
sub.pMsgsLimit = DefaultSubPendingMsgsLimit
sub.pBytesLimit = DefaultSubPendingBytesLimit
// If we have an async callback, start up a sub specific
// Go routine to deliver the messages.
if cb != nil {
sub.typ = AsyncSubscription
sub.pCond = sync.NewCond(&sub.mu)
go nc.waitForMsgs(sub)
} else if !isSync {
sub.typ = ChanSubscription
sub.mch = ch
} else { // Sync Subscription
sub.typ = SyncSubscription
sub.mch = ch
}
nc.subsMu.Lock()
nc.ssid++
sub.sid = nc.ssid
nc.subs[sub.sid] = sub
nc.subsMu.Unlock()
// We will send these for all subs when we reconnect
// so that we can suppress here if reconnecting.
if !nc.isReconnecting() {
fmt.Fprintf(nc.bw, subProto, subj, queue, sub.sid)
// Kick flusher if needed.
if len(nc.fch) == 0 {
nc.kickFlusher()
}
}
return sub, nil
} | go | func (nc *Conn) subscribe(subj, queue string, cb MsgHandler, ch chan *Msg, isSync bool) (*Subscription, error) {
if nc == nil {
return nil, ErrInvalidConnection
}
nc.mu.Lock()
// ok here, but defer is generally expensive
defer nc.mu.Unlock()
// Check for some error conditions.
if nc.isClosed() {
return nil, ErrConnectionClosed
}
if nc.isDraining() {
return nil, ErrConnectionDraining
}
if cb == nil && ch == nil {
return nil, ErrBadSubscription
}
sub := &Subscription{Subject: subj, Queue: queue, mcb: cb, conn: nc}
// Set pending limits.
sub.pMsgsLimit = DefaultSubPendingMsgsLimit
sub.pBytesLimit = DefaultSubPendingBytesLimit
// If we have an async callback, start up a sub specific
// Go routine to deliver the messages.
if cb != nil {
sub.typ = AsyncSubscription
sub.pCond = sync.NewCond(&sub.mu)
go nc.waitForMsgs(sub)
} else if !isSync {
sub.typ = ChanSubscription
sub.mch = ch
} else { // Sync Subscription
sub.typ = SyncSubscription
sub.mch = ch
}
nc.subsMu.Lock()
nc.ssid++
sub.sid = nc.ssid
nc.subs[sub.sid] = sub
nc.subsMu.Unlock()
// We will send these for all subs when we reconnect
// so that we can suppress here if reconnecting.
if !nc.isReconnecting() {
fmt.Fprintf(nc.bw, subProto, subj, queue, sub.sid)
// Kick flusher if needed.
if len(nc.fch) == 0 {
nc.kickFlusher()
}
}
return sub, nil
} | [
"func",
"(",
"nc",
"*",
"Conn",
")",
"subscribe",
"(",
"subj",
",",
"queue",
"string",
",",
"cb",
"MsgHandler",
",",
"ch",
"chan",
"*",
"Msg",
",",
"isSync",
"bool",
")",
"(",
"*",
"Subscription",
",",
"error",
")",
"{",
"if",
"nc",
"==",
"nil",
"{",
"return",
"nil",
",",
"ErrInvalidConnection",
"\n",
"}",
"\n",
"nc",
".",
"mu",
".",
"Lock",
"(",
")",
"\n",
"defer",
"nc",
".",
"mu",
".",
"Unlock",
"(",
")",
"\n",
"if",
"nc",
".",
"isClosed",
"(",
")",
"{",
"return",
"nil",
",",
"ErrConnectionClosed",
"\n",
"}",
"\n",
"if",
"nc",
".",
"isDraining",
"(",
")",
"{",
"return",
"nil",
",",
"ErrConnectionDraining",
"\n",
"}",
"\n",
"if",
"cb",
"==",
"nil",
"&&",
"ch",
"==",
"nil",
"{",
"return",
"nil",
",",
"ErrBadSubscription",
"\n",
"}",
"\n",
"sub",
":=",
"&",
"Subscription",
"{",
"Subject",
":",
"subj",
",",
"Queue",
":",
"queue",
",",
"mcb",
":",
"cb",
",",
"conn",
":",
"nc",
"}",
"\n",
"sub",
".",
"pMsgsLimit",
"=",
"DefaultSubPendingMsgsLimit",
"\n",
"sub",
".",
"pBytesLimit",
"=",
"DefaultSubPendingBytesLimit",
"\n",
"if",
"cb",
"!=",
"nil",
"{",
"sub",
".",
"typ",
"=",
"AsyncSubscription",
"\n",
"sub",
".",
"pCond",
"=",
"sync",
".",
"NewCond",
"(",
"&",
"sub",
".",
"mu",
")",
"\n",
"go",
"nc",
".",
"waitForMsgs",
"(",
"sub",
")",
"\n",
"}",
"else",
"if",
"!",
"isSync",
"{",
"sub",
".",
"typ",
"=",
"ChanSubscription",
"\n",
"sub",
".",
"mch",
"=",
"ch",
"\n",
"}",
"else",
"{",
"sub",
".",
"typ",
"=",
"SyncSubscription",
"\n",
"sub",
".",
"mch",
"=",
"ch",
"\n",
"}",
"\n",
"nc",
".",
"subsMu",
".",
"Lock",
"(",
")",
"\n",
"nc",
".",
"ssid",
"++",
"\n",
"sub",
".",
"sid",
"=",
"nc",
".",
"ssid",
"\n",
"nc",
".",
"subs",
"[",
"sub",
".",
"sid",
"]",
"=",
"sub",
"\n",
"nc",
".",
"subsMu",
".",
"Unlock",
"(",
")",
"\n",
"if",
"!",
"nc",
".",
"isReconnecting",
"(",
")",
"{",
"fmt",
".",
"Fprintf",
"(",
"nc",
".",
"bw",
",",
"subProto",
",",
"subj",
",",
"queue",
",",
"sub",
".",
"sid",
")",
"\n",
"if",
"len",
"(",
"nc",
".",
"fch",
")",
"==",
"0",
"{",
"nc",
".",
"kickFlusher",
"(",
")",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"sub",
",",
"nil",
"\n",
"}"
] | // subscribe is the internal subscribe function that indicates interest in a subject. | [
"subscribe",
"is",
"the",
"internal",
"subscribe",
"function",
"that",
"indicates",
"interest",
"in",
"a",
"subject",
"."
] | 36d30b0ba7aa260ae25b4f3d312b2a700106fd78 | https://github.com/nats-io/go-nats/blob/36d30b0ba7aa260ae25b4f3d312b2a700106fd78/nats.go#L2788-L2844 | train |
nats-io/go-nats | nats.go | NumSubscriptions | func (nc *Conn) NumSubscriptions() int {
nc.mu.RLock()
defer nc.mu.RUnlock()
return len(nc.subs)
} | go | func (nc *Conn) NumSubscriptions() int {
nc.mu.RLock()
defer nc.mu.RUnlock()
return len(nc.subs)
} | [
"func",
"(",
"nc",
"*",
"Conn",
")",
"NumSubscriptions",
"(",
")",
"int",
"{",
"nc",
".",
"mu",
".",
"RLock",
"(",
")",
"\n",
"defer",
"nc",
".",
"mu",
".",
"RUnlock",
"(",
")",
"\n",
"return",
"len",
"(",
"nc",
".",
"subs",
")",
"\n",
"}"
] | // NumSubscriptions returns active number of subscriptions. | [
"NumSubscriptions",
"returns",
"active",
"number",
"of",
"subscriptions",
"."
] | 36d30b0ba7aa260ae25b4f3d312b2a700106fd78 | https://github.com/nats-io/go-nats/blob/36d30b0ba7aa260ae25b4f3d312b2a700106fd78/nats.go#L2847-L2851 | train |
nats-io/go-nats | nats.go | removeSub | func (nc *Conn) removeSub(s *Subscription) {
nc.subsMu.Lock()
delete(nc.subs, s.sid)
nc.subsMu.Unlock()
s.mu.Lock()
defer s.mu.Unlock()
// Release callers on NextMsg for SyncSubscription only
if s.mch != nil && s.typ == SyncSubscription {
close(s.mch)
}
s.mch = nil
// Mark as invalid
s.conn = nil
s.closed = true
if s.pCond != nil {
s.pCond.Broadcast()
}
} | go | func (nc *Conn) removeSub(s *Subscription) {
nc.subsMu.Lock()
delete(nc.subs, s.sid)
nc.subsMu.Unlock()
s.mu.Lock()
defer s.mu.Unlock()
// Release callers on NextMsg for SyncSubscription only
if s.mch != nil && s.typ == SyncSubscription {
close(s.mch)
}
s.mch = nil
// Mark as invalid
s.conn = nil
s.closed = true
if s.pCond != nil {
s.pCond.Broadcast()
}
} | [
"func",
"(",
"nc",
"*",
"Conn",
")",
"removeSub",
"(",
"s",
"*",
"Subscription",
")",
"{",
"nc",
".",
"subsMu",
".",
"Lock",
"(",
")",
"\n",
"delete",
"(",
"nc",
".",
"subs",
",",
"s",
".",
"sid",
")",
"\n",
"nc",
".",
"subsMu",
".",
"Unlock",
"(",
")",
"\n",
"s",
".",
"mu",
".",
"Lock",
"(",
")",
"\n",
"defer",
"s",
".",
"mu",
".",
"Unlock",
"(",
")",
"\n",
"if",
"s",
".",
"mch",
"!=",
"nil",
"&&",
"s",
".",
"typ",
"==",
"SyncSubscription",
"{",
"close",
"(",
"s",
".",
"mch",
")",
"\n",
"}",
"\n",
"s",
".",
"mch",
"=",
"nil",
"\n",
"s",
".",
"conn",
"=",
"nil",
"\n",
"s",
".",
"closed",
"=",
"true",
"\n",
"if",
"s",
".",
"pCond",
"!=",
"nil",
"{",
"s",
".",
"pCond",
".",
"Broadcast",
"(",
")",
"\n",
"}",
"\n",
"}"
] | // Lock for nc should be held here upon entry | [
"Lock",
"for",
"nc",
"should",
"be",
"held",
"here",
"upon",
"entry"
] | 36d30b0ba7aa260ae25b4f3d312b2a700106fd78 | https://github.com/nats-io/go-nats/blob/36d30b0ba7aa260ae25b4f3d312b2a700106fd78/nats.go#L2854-L2872 | train |
nats-io/go-nats | nats.go | Type | func (s *Subscription) Type() SubscriptionType {
if s == nil {
return NilSubscription
}
s.mu.Lock()
defer s.mu.Unlock()
return s.typ
} | go | func (s *Subscription) Type() SubscriptionType {
if s == nil {
return NilSubscription
}
s.mu.Lock()
defer s.mu.Unlock()
return s.typ
} | [
"func",
"(",
"s",
"*",
"Subscription",
")",
"Type",
"(",
")",
"SubscriptionType",
"{",
"if",
"s",
"==",
"nil",
"{",
"return",
"NilSubscription",
"\n",
"}",
"\n",
"s",
".",
"mu",
".",
"Lock",
"(",
")",
"\n",
"defer",
"s",
".",
"mu",
".",
"Unlock",
"(",
")",
"\n",
"return",
"s",
".",
"typ",
"\n",
"}"
] | // Type returns the type of Subscription. | [
"Type",
"returns",
"the",
"type",
"of",
"Subscription",
"."
] | 36d30b0ba7aa260ae25b4f3d312b2a700106fd78 | https://github.com/nats-io/go-nats/blob/36d30b0ba7aa260ae25b4f3d312b2a700106fd78/nats.go#L2886-L2893 | train |
nats-io/go-nats | nats.go | Drain | func (s *Subscription) Drain() error {
if s == nil {
return ErrBadSubscription
}
s.mu.Lock()
conn := s.conn
s.mu.Unlock()
if conn == nil {
return ErrBadSubscription
}
return conn.unsubscribe(s, 0, true)
} | go | func (s *Subscription) Drain() error {
if s == nil {
return ErrBadSubscription
}
s.mu.Lock()
conn := s.conn
s.mu.Unlock()
if conn == nil {
return ErrBadSubscription
}
return conn.unsubscribe(s, 0, true)
} | [
"func",
"(",
"s",
"*",
"Subscription",
")",
"Drain",
"(",
")",
"error",
"{",
"if",
"s",
"==",
"nil",
"{",
"return",
"ErrBadSubscription",
"\n",
"}",
"\n",
"s",
".",
"mu",
".",
"Lock",
"(",
")",
"\n",
"conn",
":=",
"s",
".",
"conn",
"\n",
"s",
".",
"mu",
".",
"Unlock",
"(",
")",
"\n",
"if",
"conn",
"==",
"nil",
"{",
"return",
"ErrBadSubscription",
"\n",
"}",
"\n",
"return",
"conn",
".",
"unsubscribe",
"(",
"s",
",",
"0",
",",
"true",
")",
"\n",
"}"
] | // Drain will remove interest but continue callbacks until all messages
// have been processed. | [
"Drain",
"will",
"remove",
"interest",
"but",
"continue",
"callbacks",
"until",
"all",
"messages",
"have",
"been",
"processed",
"."
] | 36d30b0ba7aa260ae25b4f3d312b2a700106fd78 | https://github.com/nats-io/go-nats/blob/36d30b0ba7aa260ae25b4f3d312b2a700106fd78/nats.go#L2909-L2920 | train |
nats-io/go-nats | nats.go | Unsubscribe | func (s *Subscription) Unsubscribe() error {
if s == nil {
return ErrBadSubscription
}
s.mu.Lock()
conn := s.conn
s.mu.Unlock()
if conn == nil {
return ErrBadSubscription
}
if conn.IsDraining() {
return ErrConnectionDraining
}
return conn.unsubscribe(s, 0, false)
} | go | func (s *Subscription) Unsubscribe() error {
if s == nil {
return ErrBadSubscription
}
s.mu.Lock()
conn := s.conn
s.mu.Unlock()
if conn == nil {
return ErrBadSubscription
}
if conn.IsDraining() {
return ErrConnectionDraining
}
return conn.unsubscribe(s, 0, false)
} | [
"func",
"(",
"s",
"*",
"Subscription",
")",
"Unsubscribe",
"(",
")",
"error",
"{",
"if",
"s",
"==",
"nil",
"{",
"return",
"ErrBadSubscription",
"\n",
"}",
"\n",
"s",
".",
"mu",
".",
"Lock",
"(",
")",
"\n",
"conn",
":=",
"s",
".",
"conn",
"\n",
"s",
".",
"mu",
".",
"Unlock",
"(",
")",
"\n",
"if",
"conn",
"==",
"nil",
"{",
"return",
"ErrBadSubscription",
"\n",
"}",
"\n",
"if",
"conn",
".",
"IsDraining",
"(",
")",
"{",
"return",
"ErrConnectionDraining",
"\n",
"}",
"\n",
"return",
"conn",
".",
"unsubscribe",
"(",
"s",
",",
"0",
",",
"false",
")",
"\n",
"}"
] | // Unsubscribe will remove interest in the given subject. | [
"Unsubscribe",
"will",
"remove",
"interest",
"in",
"the",
"given",
"subject",
"."
] | 36d30b0ba7aa260ae25b4f3d312b2a700106fd78 | https://github.com/nats-io/go-nats/blob/36d30b0ba7aa260ae25b4f3d312b2a700106fd78/nats.go#L2923-L2937 | train |
nats-io/go-nats | nats.go | checkDrained | func (nc *Conn) checkDrained(sub *Subscription) {
if nc == nil || sub == nil {
return
}
// This allows us to know that whatever we have in the client pending
// is correct and the server will not send additional information.
nc.Flush()
// Once we are here we just wait for Pending to reach 0 or
// any other state to exit this go routine.
for {
// check connection is still valid.
if nc.IsClosed() {
return
}
// Check subscription state
sub.mu.Lock()
conn := sub.conn
closed := sub.closed
pMsgs := sub.pMsgs
sub.mu.Unlock()
if conn == nil || closed || pMsgs == 0 {
nc.mu.Lock()
nc.removeSub(sub)
nc.mu.Unlock()
return
}
time.Sleep(100 * time.Millisecond)
}
} | go | func (nc *Conn) checkDrained(sub *Subscription) {
if nc == nil || sub == nil {
return
}
// This allows us to know that whatever we have in the client pending
// is correct and the server will not send additional information.
nc.Flush()
// Once we are here we just wait for Pending to reach 0 or
// any other state to exit this go routine.
for {
// check connection is still valid.
if nc.IsClosed() {
return
}
// Check subscription state
sub.mu.Lock()
conn := sub.conn
closed := sub.closed
pMsgs := sub.pMsgs
sub.mu.Unlock()
if conn == nil || closed || pMsgs == 0 {
nc.mu.Lock()
nc.removeSub(sub)
nc.mu.Unlock()
return
}
time.Sleep(100 * time.Millisecond)
}
} | [
"func",
"(",
"nc",
"*",
"Conn",
")",
"checkDrained",
"(",
"sub",
"*",
"Subscription",
")",
"{",
"if",
"nc",
"==",
"nil",
"||",
"sub",
"==",
"nil",
"{",
"return",
"\n",
"}",
"\n",
"nc",
".",
"Flush",
"(",
")",
"\n",
"for",
"{",
"if",
"nc",
".",
"IsClosed",
"(",
")",
"{",
"return",
"\n",
"}",
"\n",
"sub",
".",
"mu",
".",
"Lock",
"(",
")",
"\n",
"conn",
":=",
"sub",
".",
"conn",
"\n",
"closed",
":=",
"sub",
".",
"closed",
"\n",
"pMsgs",
":=",
"sub",
".",
"pMsgs",
"\n",
"sub",
".",
"mu",
".",
"Unlock",
"(",
")",
"\n",
"if",
"conn",
"==",
"nil",
"||",
"closed",
"||",
"pMsgs",
"==",
"0",
"{",
"nc",
".",
"mu",
".",
"Lock",
"(",
")",
"\n",
"nc",
".",
"removeSub",
"(",
"sub",
")",
"\n",
"nc",
".",
"mu",
".",
"Unlock",
"(",
")",
"\n",
"return",
"\n",
"}",
"\n",
"time",
".",
"Sleep",
"(",
"100",
"*",
"time",
".",
"Millisecond",
")",
"\n",
"}",
"\n",
"}"
] | // checkDrained will watch for a subscription to be fully drained
// and then remove it. | [
"checkDrained",
"will",
"watch",
"for",
"a",
"subscription",
"to",
"be",
"fully",
"drained",
"and",
"then",
"remove",
"it",
"."
] | 36d30b0ba7aa260ae25b4f3d312b2a700106fd78 | https://github.com/nats-io/go-nats/blob/36d30b0ba7aa260ae25b4f3d312b2a700106fd78/nats.go#L2941-L2974 | train |
nats-io/go-nats | nats.go | AutoUnsubscribe | func (s *Subscription) AutoUnsubscribe(max int) error {
if s == nil {
return ErrBadSubscription
}
s.mu.Lock()
conn := s.conn
s.mu.Unlock()
if conn == nil {
return ErrBadSubscription
}
return conn.unsubscribe(s, max, false)
} | go | func (s *Subscription) AutoUnsubscribe(max int) error {
if s == nil {
return ErrBadSubscription
}
s.mu.Lock()
conn := s.conn
s.mu.Unlock()
if conn == nil {
return ErrBadSubscription
}
return conn.unsubscribe(s, max, false)
} | [
"func",
"(",
"s",
"*",
"Subscription",
")",
"AutoUnsubscribe",
"(",
"max",
"int",
")",
"error",
"{",
"if",
"s",
"==",
"nil",
"{",
"return",
"ErrBadSubscription",
"\n",
"}",
"\n",
"s",
".",
"mu",
".",
"Lock",
"(",
")",
"\n",
"conn",
":=",
"s",
".",
"conn",
"\n",
"s",
".",
"mu",
".",
"Unlock",
"(",
")",
"\n",
"if",
"conn",
"==",
"nil",
"{",
"return",
"ErrBadSubscription",
"\n",
"}",
"\n",
"return",
"conn",
".",
"unsubscribe",
"(",
"s",
",",
"max",
",",
"false",
")",
"\n",
"}"
] | // AutoUnsubscribe will issue an automatic Unsubscribe that is
// processed by the server when max messages have been received.
// This can be useful when sending a request to an unknown number
// of subscribers. | [
"AutoUnsubscribe",
"will",
"issue",
"an",
"automatic",
"Unsubscribe",
"that",
"is",
"processed",
"by",
"the",
"server",
"when",
"max",
"messages",
"have",
"been",
"received",
".",
"This",
"can",
"be",
"useful",
"when",
"sending",
"a",
"request",
"to",
"an",
"unknown",
"number",
"of",
"subscribers",
"."
] | 36d30b0ba7aa260ae25b4f3d312b2a700106fd78 | https://github.com/nats-io/go-nats/blob/36d30b0ba7aa260ae25b4f3d312b2a700106fd78/nats.go#L2980-L2991 | train |
nats-io/go-nats | nats.go | NextMsg | func (s *Subscription) NextMsg(timeout time.Duration) (*Msg, error) {
if s == nil {
return nil, ErrBadSubscription
}
s.mu.Lock()
err := s.validateNextMsgState()
if err != nil {
s.mu.Unlock()
return nil, err
}
// snapshot
mch := s.mch
s.mu.Unlock()
var ok bool
var msg *Msg
// If something is available right away, let's optimize that case.
select {
case msg, ok = <-mch:
if !ok {
return nil, ErrConnectionClosed
}
if err := s.processNextMsgDelivered(msg); err != nil {
return nil, err
} else {
return msg, nil
}
default:
}
// If we are here a message was not immediately available, so lets loop
// with a timeout.
t := globalTimerPool.Get(timeout)
defer globalTimerPool.Put(t)
select {
case msg, ok = <-mch:
if !ok {
return nil, ErrConnectionClosed
}
if err := s.processNextMsgDelivered(msg); err != nil {
return nil, err
}
case <-t.C:
return nil, ErrTimeout
}
return msg, nil
} | go | func (s *Subscription) NextMsg(timeout time.Duration) (*Msg, error) {
if s == nil {
return nil, ErrBadSubscription
}
s.mu.Lock()
err := s.validateNextMsgState()
if err != nil {
s.mu.Unlock()
return nil, err
}
// snapshot
mch := s.mch
s.mu.Unlock()
var ok bool
var msg *Msg
// If something is available right away, let's optimize that case.
select {
case msg, ok = <-mch:
if !ok {
return nil, ErrConnectionClosed
}
if err := s.processNextMsgDelivered(msg); err != nil {
return nil, err
} else {
return msg, nil
}
default:
}
// If we are here a message was not immediately available, so lets loop
// with a timeout.
t := globalTimerPool.Get(timeout)
defer globalTimerPool.Put(t)
select {
case msg, ok = <-mch:
if !ok {
return nil, ErrConnectionClosed
}
if err := s.processNextMsgDelivered(msg); err != nil {
return nil, err
}
case <-t.C:
return nil, ErrTimeout
}
return msg, nil
} | [
"func",
"(",
"s",
"*",
"Subscription",
")",
"NextMsg",
"(",
"timeout",
"time",
".",
"Duration",
")",
"(",
"*",
"Msg",
",",
"error",
")",
"{",
"if",
"s",
"==",
"nil",
"{",
"return",
"nil",
",",
"ErrBadSubscription",
"\n",
"}",
"\n",
"s",
".",
"mu",
".",
"Lock",
"(",
")",
"\n",
"err",
":=",
"s",
".",
"validateNextMsgState",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"s",
".",
"mu",
".",
"Unlock",
"(",
")",
"\n",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"mch",
":=",
"s",
".",
"mch",
"\n",
"s",
".",
"mu",
".",
"Unlock",
"(",
")",
"\n",
"var",
"ok",
"bool",
"\n",
"var",
"msg",
"*",
"Msg",
"\n",
"select",
"{",
"case",
"msg",
",",
"ok",
"=",
"<-",
"mch",
":",
"if",
"!",
"ok",
"{",
"return",
"nil",
",",
"ErrConnectionClosed",
"\n",
"}",
"\n",
"if",
"err",
":=",
"s",
".",
"processNextMsgDelivered",
"(",
"msg",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"else",
"{",
"return",
"msg",
",",
"nil",
"\n",
"}",
"\n",
"default",
":",
"}",
"\n",
"t",
":=",
"globalTimerPool",
".",
"Get",
"(",
"timeout",
")",
"\n",
"defer",
"globalTimerPool",
".",
"Put",
"(",
"t",
")",
"\n",
"select",
"{",
"case",
"msg",
",",
"ok",
"=",
"<-",
"mch",
":",
"if",
"!",
"ok",
"{",
"return",
"nil",
",",
"ErrConnectionClosed",
"\n",
"}",
"\n",
"if",
"err",
":=",
"s",
".",
"processNextMsgDelivered",
"(",
"msg",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"case",
"<-",
"t",
".",
"C",
":",
"return",
"nil",
",",
"ErrTimeout",
"\n",
"}",
"\n",
"return",
"msg",
",",
"nil",
"\n",
"}"
] | // NextMsg will return the next message available to a synchronous subscriber
// or block until one is available. A timeout can be used to return when no
// message has been delivered. | [
"NextMsg",
"will",
"return",
"the",
"next",
"message",
"available",
"to",
"a",
"synchronous",
"subscriber",
"or",
"block",
"until",
"one",
"is",
"available",
".",
"A",
"timeout",
"can",
"be",
"used",
"to",
"return",
"when",
"no",
"message",
"has",
"been",
"delivered",
"."
] | 36d30b0ba7aa260ae25b4f3d312b2a700106fd78 | https://github.com/nats-io/go-nats/blob/36d30b0ba7aa260ae25b4f3d312b2a700106fd78/nats.go#L3036-L3088 | train |
nats-io/go-nats | nats.go | validateNextMsgState | func (s *Subscription) validateNextMsgState() error {
if s.connClosed {
return ErrConnectionClosed
}
if s.mch == nil {
if s.max > 0 && s.delivered >= s.max {
return ErrMaxMessages
} else if s.closed {
return ErrBadSubscription
}
}
if s.mcb != nil {
return ErrSyncSubRequired
}
if s.sc {
s.sc = false
return ErrSlowConsumer
}
return nil
} | go | func (s *Subscription) validateNextMsgState() error {
if s.connClosed {
return ErrConnectionClosed
}
if s.mch == nil {
if s.max > 0 && s.delivered >= s.max {
return ErrMaxMessages
} else if s.closed {
return ErrBadSubscription
}
}
if s.mcb != nil {
return ErrSyncSubRequired
}
if s.sc {
s.sc = false
return ErrSlowConsumer
}
return nil
} | [
"func",
"(",
"s",
"*",
"Subscription",
")",
"validateNextMsgState",
"(",
")",
"error",
"{",
"if",
"s",
".",
"connClosed",
"{",
"return",
"ErrConnectionClosed",
"\n",
"}",
"\n",
"if",
"s",
".",
"mch",
"==",
"nil",
"{",
"if",
"s",
".",
"max",
">",
"0",
"&&",
"s",
".",
"delivered",
">=",
"s",
".",
"max",
"{",
"return",
"ErrMaxMessages",
"\n",
"}",
"else",
"if",
"s",
".",
"closed",
"{",
"return",
"ErrBadSubscription",
"\n",
"}",
"\n",
"}",
"\n",
"if",
"s",
".",
"mcb",
"!=",
"nil",
"{",
"return",
"ErrSyncSubRequired",
"\n",
"}",
"\n",
"if",
"s",
".",
"sc",
"{",
"s",
".",
"sc",
"=",
"false",
"\n",
"return",
"ErrSlowConsumer",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}"
] | // validateNextMsgState checks whether the subscription is in a valid
// state to call NextMsg and be delivered another message synchronously.
// This should be called while holding the lock. | [
"validateNextMsgState",
"checks",
"whether",
"the",
"subscription",
"is",
"in",
"a",
"valid",
"state",
"to",
"call",
"NextMsg",
"and",
"be",
"delivered",
"another",
"message",
"synchronously",
".",
"This",
"should",
"be",
"called",
"while",
"holding",
"the",
"lock",
"."
] | 36d30b0ba7aa260ae25b4f3d312b2a700106fd78 | https://github.com/nats-io/go-nats/blob/36d30b0ba7aa260ae25b4f3d312b2a700106fd78/nats.go#L3093-L3113 | train |
nats-io/go-nats | nats.go | processNextMsgDelivered | func (s *Subscription) processNextMsgDelivered(msg *Msg) error {
s.mu.Lock()
nc := s.conn
max := s.max
// Update some stats.
s.delivered++
delivered := s.delivered
if s.typ == SyncSubscription {
s.pMsgs--
s.pBytes -= len(msg.Data)
}
s.mu.Unlock()
if max > 0 {
if delivered > max {
return ErrMaxMessages
}
// Remove subscription if we have reached max.
if delivered == max {
nc.mu.Lock()
nc.removeSub(s)
nc.mu.Unlock()
}
}
return nil
} | go | func (s *Subscription) processNextMsgDelivered(msg *Msg) error {
s.mu.Lock()
nc := s.conn
max := s.max
// Update some stats.
s.delivered++
delivered := s.delivered
if s.typ == SyncSubscription {
s.pMsgs--
s.pBytes -= len(msg.Data)
}
s.mu.Unlock()
if max > 0 {
if delivered > max {
return ErrMaxMessages
}
// Remove subscription if we have reached max.
if delivered == max {
nc.mu.Lock()
nc.removeSub(s)
nc.mu.Unlock()
}
}
return nil
} | [
"func",
"(",
"s",
"*",
"Subscription",
")",
"processNextMsgDelivered",
"(",
"msg",
"*",
"Msg",
")",
"error",
"{",
"s",
".",
"mu",
".",
"Lock",
"(",
")",
"\n",
"nc",
":=",
"s",
".",
"conn",
"\n",
"max",
":=",
"s",
".",
"max",
"\n",
"s",
".",
"delivered",
"++",
"\n",
"delivered",
":=",
"s",
".",
"delivered",
"\n",
"if",
"s",
".",
"typ",
"==",
"SyncSubscription",
"{",
"s",
".",
"pMsgs",
"--",
"\n",
"s",
".",
"pBytes",
"-=",
"len",
"(",
"msg",
".",
"Data",
")",
"\n",
"}",
"\n",
"s",
".",
"mu",
".",
"Unlock",
"(",
")",
"\n",
"if",
"max",
">",
"0",
"{",
"if",
"delivered",
">",
"max",
"{",
"return",
"ErrMaxMessages",
"\n",
"}",
"\n",
"if",
"delivered",
"==",
"max",
"{",
"nc",
".",
"mu",
".",
"Lock",
"(",
")",
"\n",
"nc",
".",
"removeSub",
"(",
"s",
")",
"\n",
"nc",
".",
"mu",
".",
"Unlock",
"(",
")",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}"
] | // processNextMsgDelivered takes a message and applies the needed
// accounting to the stats from the subscription, returning an
// error in case we have the maximum number of messages have been
// delivered already. It should not be called while holding the lock. | [
"processNextMsgDelivered",
"takes",
"a",
"message",
"and",
"applies",
"the",
"needed",
"accounting",
"to",
"the",
"stats",
"from",
"the",
"subscription",
"returning",
"an",
"error",
"in",
"case",
"we",
"have",
"the",
"maximum",
"number",
"of",
"messages",
"have",
"been",
"delivered",
"already",
".",
"It",
"should",
"not",
"be",
"called",
"while",
"holding",
"the",
"lock",
"."
] | 36d30b0ba7aa260ae25b4f3d312b2a700106fd78 | https://github.com/nats-io/go-nats/blob/36d30b0ba7aa260ae25b4f3d312b2a700106fd78/nats.go#L3119-L3146 | train |
nats-io/go-nats | nats.go | Pending | func (s *Subscription) Pending() (int, int, error) {
if s == nil {
return -1, -1, ErrBadSubscription
}
s.mu.Lock()
defer s.mu.Unlock()
if s.conn == nil {
return -1, -1, ErrBadSubscription
}
if s.typ == ChanSubscription {
return -1, -1, ErrTypeSubscription
}
return s.pMsgs, s.pBytes, nil
} | go | func (s *Subscription) Pending() (int, int, error) {
if s == nil {
return -1, -1, ErrBadSubscription
}
s.mu.Lock()
defer s.mu.Unlock()
if s.conn == nil {
return -1, -1, ErrBadSubscription
}
if s.typ == ChanSubscription {
return -1, -1, ErrTypeSubscription
}
return s.pMsgs, s.pBytes, nil
} | [
"func",
"(",
"s",
"*",
"Subscription",
")",
"Pending",
"(",
")",
"(",
"int",
",",
"int",
",",
"error",
")",
"{",
"if",
"s",
"==",
"nil",
"{",
"return",
"-",
"1",
",",
"-",
"1",
",",
"ErrBadSubscription",
"\n",
"}",
"\n",
"s",
".",
"mu",
".",
"Lock",
"(",
")",
"\n",
"defer",
"s",
".",
"mu",
".",
"Unlock",
"(",
")",
"\n",
"if",
"s",
".",
"conn",
"==",
"nil",
"{",
"return",
"-",
"1",
",",
"-",
"1",
",",
"ErrBadSubscription",
"\n",
"}",
"\n",
"if",
"s",
".",
"typ",
"==",
"ChanSubscription",
"{",
"return",
"-",
"1",
",",
"-",
"1",
",",
"ErrTypeSubscription",
"\n",
"}",
"\n",
"return",
"s",
".",
"pMsgs",
",",
"s",
".",
"pBytes",
",",
"nil",
"\n",
"}"
] | // Pending returns the number of queued messages and queued bytes in the client for this subscription. | [
"Pending",
"returns",
"the",
"number",
"of",
"queued",
"messages",
"and",
"queued",
"bytes",
"in",
"the",
"client",
"for",
"this",
"subscription",
"."
] | 36d30b0ba7aa260ae25b4f3d312b2a700106fd78 | https://github.com/nats-io/go-nats/blob/36d30b0ba7aa260ae25b4f3d312b2a700106fd78/nats.go#L3156-L3169 | train |
nats-io/go-nats | nats.go | PendingLimits | func (s *Subscription) PendingLimits() (int, int, error) {
if s == nil {
return -1, -1, ErrBadSubscription
}
s.mu.Lock()
defer s.mu.Unlock()
if s.conn == nil {
return -1, -1, ErrBadSubscription
}
if s.typ == ChanSubscription {
return -1, -1, ErrTypeSubscription
}
return s.pMsgsLimit, s.pBytesLimit, nil
} | go | func (s *Subscription) PendingLimits() (int, int, error) {
if s == nil {
return -1, -1, ErrBadSubscription
}
s.mu.Lock()
defer s.mu.Unlock()
if s.conn == nil {
return -1, -1, ErrBadSubscription
}
if s.typ == ChanSubscription {
return -1, -1, ErrTypeSubscription
}
return s.pMsgsLimit, s.pBytesLimit, nil
} | [
"func",
"(",
"s",
"*",
"Subscription",
")",
"PendingLimits",
"(",
")",
"(",
"int",
",",
"int",
",",
"error",
")",
"{",
"if",
"s",
"==",
"nil",
"{",
"return",
"-",
"1",
",",
"-",
"1",
",",
"ErrBadSubscription",
"\n",
"}",
"\n",
"s",
".",
"mu",
".",
"Lock",
"(",
")",
"\n",
"defer",
"s",
".",
"mu",
".",
"Unlock",
"(",
")",
"\n",
"if",
"s",
".",
"conn",
"==",
"nil",
"{",
"return",
"-",
"1",
",",
"-",
"1",
",",
"ErrBadSubscription",
"\n",
"}",
"\n",
"if",
"s",
".",
"typ",
"==",
"ChanSubscription",
"{",
"return",
"-",
"1",
",",
"-",
"1",
",",
"ErrTypeSubscription",
"\n",
"}",
"\n",
"return",
"s",
".",
"pMsgsLimit",
",",
"s",
".",
"pBytesLimit",
",",
"nil",
"\n",
"}"
] | // PendingLimits returns the current limits for this subscription.
// If no error is returned, a negative value indicates that the
// given metric is not limited. | [
"PendingLimits",
"returns",
"the",
"current",
"limits",
"for",
"this",
"subscription",
".",
"If",
"no",
"error",
"is",
"returned",
"a",
"negative",
"value",
"indicates",
"that",
"the",
"given",
"metric",
"is",
"not",
"limited",
"."
] | 36d30b0ba7aa260ae25b4f3d312b2a700106fd78 | https://github.com/nats-io/go-nats/blob/36d30b0ba7aa260ae25b4f3d312b2a700106fd78/nats.go#L3213-L3226 | train |
nats-io/go-nats | nats.go | sendPing | func (nc *Conn) sendPing(ch chan struct{}) {
nc.pongs = append(nc.pongs, ch)
nc.bw.WriteString(pingProto)
// Flush in place.
nc.bw.Flush()
} | go | func (nc *Conn) sendPing(ch chan struct{}) {
nc.pongs = append(nc.pongs, ch)
nc.bw.WriteString(pingProto)
// Flush in place.
nc.bw.Flush()
} | [
"func",
"(",
"nc",
"*",
"Conn",
")",
"sendPing",
"(",
"ch",
"chan",
"struct",
"{",
"}",
")",
"{",
"nc",
".",
"pongs",
"=",
"append",
"(",
"nc",
".",
"pongs",
",",
"ch",
")",
"\n",
"nc",
".",
"bw",
".",
"WriteString",
"(",
"pingProto",
")",
"\n",
"nc",
".",
"bw",
".",
"Flush",
"(",
")",
"\n",
"}"
] | // The lock must be held entering this function. | [
"The",
"lock",
"must",
"be",
"held",
"entering",
"this",
"function",
"."
] | 36d30b0ba7aa260ae25b4f3d312b2a700106fd78 | https://github.com/nats-io/go-nats/blob/36d30b0ba7aa260ae25b4f3d312b2a700106fd78/nats.go#L3298-L3303 | train |
nats-io/go-nats | nats.go | processPingTimer | func (nc *Conn) processPingTimer() {
nc.mu.Lock()
if nc.status != CONNECTED {
nc.mu.Unlock()
return
}
// Check for violation
nc.pout++
if nc.pout > nc.Opts.MaxPingsOut {
nc.mu.Unlock()
nc.processOpErr(ErrStaleConnection)
return
}
nc.sendPing(nil)
nc.ptmr.Reset(nc.Opts.PingInterval)
nc.mu.Unlock()
} | go | func (nc *Conn) processPingTimer() {
nc.mu.Lock()
if nc.status != CONNECTED {
nc.mu.Unlock()
return
}
// Check for violation
nc.pout++
if nc.pout > nc.Opts.MaxPingsOut {
nc.mu.Unlock()
nc.processOpErr(ErrStaleConnection)
return
}
nc.sendPing(nil)
nc.ptmr.Reset(nc.Opts.PingInterval)
nc.mu.Unlock()
} | [
"func",
"(",
"nc",
"*",
"Conn",
")",
"processPingTimer",
"(",
")",
"{",
"nc",
".",
"mu",
".",
"Lock",
"(",
")",
"\n",
"if",
"nc",
".",
"status",
"!=",
"CONNECTED",
"{",
"nc",
".",
"mu",
".",
"Unlock",
"(",
")",
"\n",
"return",
"\n",
"}",
"\n",
"nc",
".",
"pout",
"++",
"\n",
"if",
"nc",
".",
"pout",
">",
"nc",
".",
"Opts",
".",
"MaxPingsOut",
"{",
"nc",
".",
"mu",
".",
"Unlock",
"(",
")",
"\n",
"nc",
".",
"processOpErr",
"(",
"ErrStaleConnection",
")",
"\n",
"return",
"\n",
"}",
"\n",
"nc",
".",
"sendPing",
"(",
"nil",
")",
"\n",
"nc",
".",
"ptmr",
".",
"Reset",
"(",
"nc",
".",
"Opts",
".",
"PingInterval",
")",
"\n",
"nc",
".",
"mu",
".",
"Unlock",
"(",
")",
"\n",
"}"
] | // This will fire periodically and send a client origin
// ping to the server. Will also check that we have received
// responses from the server. | [
"This",
"will",
"fire",
"periodically",
"and",
"send",
"a",
"client",
"origin",
"ping",
"to",
"the",
"server",
".",
"Will",
"also",
"check",
"that",
"we",
"have",
"received",
"responses",
"from",
"the",
"server",
"."
] | 36d30b0ba7aa260ae25b4f3d312b2a700106fd78 | https://github.com/nats-io/go-nats/blob/36d30b0ba7aa260ae25b4f3d312b2a700106fd78/nats.go#L3308-L3327 | train |
nats-io/go-nats | nats.go | resendSubscriptions | func (nc *Conn) resendSubscriptions() {
// Since we are going to send protocols to the server, we don't want to
// be holding the subsMu lock (which is used in processMsg). So copy
// the subscriptions in a temporary array.
nc.subsMu.RLock()
subs := make([]*Subscription, 0, len(nc.subs))
for _, s := range nc.subs {
subs = append(subs, s)
}
nc.subsMu.RUnlock()
for _, s := range subs {
adjustedMax := uint64(0)
s.mu.Lock()
if s.max > 0 {
if s.delivered < s.max {
adjustedMax = s.max - s.delivered
}
// adjustedMax could be 0 here if the number of delivered msgs
// reached the max, if so unsubscribe.
if adjustedMax == 0 {
s.mu.Unlock()
fmt.Fprintf(nc.bw, unsubProto, s.sid, _EMPTY_)
continue
}
}
s.mu.Unlock()
fmt.Fprintf(nc.bw, subProto, s.Subject, s.Queue, s.sid)
if adjustedMax > 0 {
maxStr := strconv.Itoa(int(adjustedMax))
fmt.Fprintf(nc.bw, unsubProto, s.sid, maxStr)
}
}
} | go | func (nc *Conn) resendSubscriptions() {
// Since we are going to send protocols to the server, we don't want to
// be holding the subsMu lock (which is used in processMsg). So copy
// the subscriptions in a temporary array.
nc.subsMu.RLock()
subs := make([]*Subscription, 0, len(nc.subs))
for _, s := range nc.subs {
subs = append(subs, s)
}
nc.subsMu.RUnlock()
for _, s := range subs {
adjustedMax := uint64(0)
s.mu.Lock()
if s.max > 0 {
if s.delivered < s.max {
adjustedMax = s.max - s.delivered
}
// adjustedMax could be 0 here if the number of delivered msgs
// reached the max, if so unsubscribe.
if adjustedMax == 0 {
s.mu.Unlock()
fmt.Fprintf(nc.bw, unsubProto, s.sid, _EMPTY_)
continue
}
}
s.mu.Unlock()
fmt.Fprintf(nc.bw, subProto, s.Subject, s.Queue, s.sid)
if adjustedMax > 0 {
maxStr := strconv.Itoa(int(adjustedMax))
fmt.Fprintf(nc.bw, unsubProto, s.sid, maxStr)
}
}
} | [
"func",
"(",
"nc",
"*",
"Conn",
")",
"resendSubscriptions",
"(",
")",
"{",
"nc",
".",
"subsMu",
".",
"RLock",
"(",
")",
"\n",
"subs",
":=",
"make",
"(",
"[",
"]",
"*",
"Subscription",
",",
"0",
",",
"len",
"(",
"nc",
".",
"subs",
")",
")",
"\n",
"for",
"_",
",",
"s",
":=",
"range",
"nc",
".",
"subs",
"{",
"subs",
"=",
"append",
"(",
"subs",
",",
"s",
")",
"\n",
"}",
"\n",
"nc",
".",
"subsMu",
".",
"RUnlock",
"(",
")",
"\n",
"for",
"_",
",",
"s",
":=",
"range",
"subs",
"{",
"adjustedMax",
":=",
"uint64",
"(",
"0",
")",
"\n",
"s",
".",
"mu",
".",
"Lock",
"(",
")",
"\n",
"if",
"s",
".",
"max",
">",
"0",
"{",
"if",
"s",
".",
"delivered",
"<",
"s",
".",
"max",
"{",
"adjustedMax",
"=",
"s",
".",
"max",
"-",
"s",
".",
"delivered",
"\n",
"}",
"\n",
"if",
"adjustedMax",
"==",
"0",
"{",
"s",
".",
"mu",
".",
"Unlock",
"(",
")",
"\n",
"fmt",
".",
"Fprintf",
"(",
"nc",
".",
"bw",
",",
"unsubProto",
",",
"s",
".",
"sid",
",",
"_EMPTY_",
")",
"\n",
"continue",
"\n",
"}",
"\n",
"}",
"\n",
"s",
".",
"mu",
".",
"Unlock",
"(",
")",
"\n",
"fmt",
".",
"Fprintf",
"(",
"nc",
".",
"bw",
",",
"subProto",
",",
"s",
".",
"Subject",
",",
"s",
".",
"Queue",
",",
"s",
".",
"sid",
")",
"\n",
"if",
"adjustedMax",
">",
"0",
"{",
"maxStr",
":=",
"strconv",
".",
"Itoa",
"(",
"int",
"(",
"adjustedMax",
")",
")",
"\n",
"fmt",
".",
"Fprintf",
"(",
"nc",
".",
"bw",
",",
"unsubProto",
",",
"s",
".",
"sid",
",",
"maxStr",
")",
"\n",
"}",
"\n",
"}",
"\n",
"}"
] | // resendSubscriptions will send our subscription state back to the
// server. Used in reconnects | [
"resendSubscriptions",
"will",
"send",
"our",
"subscription",
"state",
"back",
"to",
"the",
"server",
".",
"Used",
"in",
"reconnects"
] | 36d30b0ba7aa260ae25b4f3d312b2a700106fd78 | https://github.com/nats-io/go-nats/blob/36d30b0ba7aa260ae25b4f3d312b2a700106fd78/nats.go#L3389-L3422 | train |
nats-io/go-nats | nats.go | clearPendingFlushCalls | func (nc *Conn) clearPendingFlushCalls() {
// Clear any queued pongs, e.g. pending flush calls.
for _, ch := range nc.pongs {
if ch != nil {
close(ch)
}
}
nc.pongs = nil
} | go | func (nc *Conn) clearPendingFlushCalls() {
// Clear any queued pongs, e.g. pending flush calls.
for _, ch := range nc.pongs {
if ch != nil {
close(ch)
}
}
nc.pongs = nil
} | [
"func",
"(",
"nc",
"*",
"Conn",
")",
"clearPendingFlushCalls",
"(",
")",
"{",
"for",
"_",
",",
"ch",
":=",
"range",
"nc",
".",
"pongs",
"{",
"if",
"ch",
"!=",
"nil",
"{",
"close",
"(",
"ch",
")",
"\n",
"}",
"\n",
"}",
"\n",
"nc",
".",
"pongs",
"=",
"nil",
"\n",
"}"
] | // This will clear any pending flush calls and release pending calls.
// Lock is assumed to be held by the caller. | [
"This",
"will",
"clear",
"any",
"pending",
"flush",
"calls",
"and",
"release",
"pending",
"calls",
".",
"Lock",
"is",
"assumed",
"to",
"be",
"held",
"by",
"the",
"caller",
"."
] | 36d30b0ba7aa260ae25b4f3d312b2a700106fd78 | https://github.com/nats-io/go-nats/blob/36d30b0ba7aa260ae25b4f3d312b2a700106fd78/nats.go#L3426-L3434 | train |
nats-io/go-nats | nats.go | clearPendingRequestCalls | func (nc *Conn) clearPendingRequestCalls() {
if nc.respMap == nil {
return
}
for key, ch := range nc.respMap {
if ch != nil {
close(ch)
delete(nc.respMap, key)
}
}
} | go | func (nc *Conn) clearPendingRequestCalls() {
if nc.respMap == nil {
return
}
for key, ch := range nc.respMap {
if ch != nil {
close(ch)
delete(nc.respMap, key)
}
}
} | [
"func",
"(",
"nc",
"*",
"Conn",
")",
"clearPendingRequestCalls",
"(",
")",
"{",
"if",
"nc",
".",
"respMap",
"==",
"nil",
"{",
"return",
"\n",
"}",
"\n",
"for",
"key",
",",
"ch",
":=",
"range",
"nc",
".",
"respMap",
"{",
"if",
"ch",
"!=",
"nil",
"{",
"close",
"(",
"ch",
")",
"\n",
"delete",
"(",
"nc",
".",
"respMap",
",",
"key",
")",
"\n",
"}",
"\n",
"}",
"\n",
"}"
] | // This will clear any pending Request calls.
// Lock is assumed to be held by the caller. | [
"This",
"will",
"clear",
"any",
"pending",
"Request",
"calls",
".",
"Lock",
"is",
"assumed",
"to",
"be",
"held",
"by",
"the",
"caller",
"."
] | 36d30b0ba7aa260ae25b4f3d312b2a700106fd78 | https://github.com/nats-io/go-nats/blob/36d30b0ba7aa260ae25b4f3d312b2a700106fd78/nats.go#L3438-L3448 | train |
nats-io/go-nats | nats.go | close | func (nc *Conn) close(status Status, doCBs bool) {
nc.mu.Lock()
if nc.isClosed() {
nc.status = status
nc.mu.Unlock()
return
}
nc.status = CLOSED
// Kick the Go routines so they fall out.
nc.kickFlusher()
nc.mu.Unlock()
nc.mu.Lock()
// Clear any queued pongs, e.g. pending flush calls.
nc.clearPendingFlushCalls()
// Clear any queued and blocking Requests.
nc.clearPendingRequestCalls()
// Stop ping timer if set.
nc.stopPingTimer()
nc.ptmr = nil
// Go ahead and make sure we have flushed the outbound
if nc.conn != nil {
nc.bw.Flush()
defer nc.conn.Close()
}
// Close sync subscriber channels and release any
// pending NextMsg() calls.
nc.subsMu.Lock()
for _, s := range nc.subs {
s.mu.Lock()
// Release callers on NextMsg for SyncSubscription only
if s.mch != nil && s.typ == SyncSubscription {
close(s.mch)
}
s.mch = nil
// Mark as invalid, for signaling to deliverMsgs
s.closed = true
// Mark connection closed in subscription
s.connClosed = true
// If we have an async subscription, signals it to exit
if s.typ == AsyncSubscription && s.pCond != nil {
s.pCond.Signal()
}
s.mu.Unlock()
}
nc.subs = nil
nc.subsMu.Unlock()
nc.status = status
// Perform appropriate callback if needed for a disconnect.
if doCBs {
if nc.Opts.DisconnectedCB != nil && nc.conn != nil {
nc.ach.push(func() { nc.Opts.DisconnectedCB(nc) })
}
if nc.Opts.ClosedCB != nil {
nc.ach.push(func() { nc.Opts.ClosedCB(nc) })
}
nc.ach.close()
}
nc.mu.Unlock()
} | go | func (nc *Conn) close(status Status, doCBs bool) {
nc.mu.Lock()
if nc.isClosed() {
nc.status = status
nc.mu.Unlock()
return
}
nc.status = CLOSED
// Kick the Go routines so they fall out.
nc.kickFlusher()
nc.mu.Unlock()
nc.mu.Lock()
// Clear any queued pongs, e.g. pending flush calls.
nc.clearPendingFlushCalls()
// Clear any queued and blocking Requests.
nc.clearPendingRequestCalls()
// Stop ping timer if set.
nc.stopPingTimer()
nc.ptmr = nil
// Go ahead and make sure we have flushed the outbound
if nc.conn != nil {
nc.bw.Flush()
defer nc.conn.Close()
}
// Close sync subscriber channels and release any
// pending NextMsg() calls.
nc.subsMu.Lock()
for _, s := range nc.subs {
s.mu.Lock()
// Release callers on NextMsg for SyncSubscription only
if s.mch != nil && s.typ == SyncSubscription {
close(s.mch)
}
s.mch = nil
// Mark as invalid, for signaling to deliverMsgs
s.closed = true
// Mark connection closed in subscription
s.connClosed = true
// If we have an async subscription, signals it to exit
if s.typ == AsyncSubscription && s.pCond != nil {
s.pCond.Signal()
}
s.mu.Unlock()
}
nc.subs = nil
nc.subsMu.Unlock()
nc.status = status
// Perform appropriate callback if needed for a disconnect.
if doCBs {
if nc.Opts.DisconnectedCB != nil && nc.conn != nil {
nc.ach.push(func() { nc.Opts.DisconnectedCB(nc) })
}
if nc.Opts.ClosedCB != nil {
nc.ach.push(func() { nc.Opts.ClosedCB(nc) })
}
nc.ach.close()
}
nc.mu.Unlock()
} | [
"func",
"(",
"nc",
"*",
"Conn",
")",
"close",
"(",
"status",
"Status",
",",
"doCBs",
"bool",
")",
"{",
"nc",
".",
"mu",
".",
"Lock",
"(",
")",
"\n",
"if",
"nc",
".",
"isClosed",
"(",
")",
"{",
"nc",
".",
"status",
"=",
"status",
"\n",
"nc",
".",
"mu",
".",
"Unlock",
"(",
")",
"\n",
"return",
"\n",
"}",
"\n",
"nc",
".",
"status",
"=",
"CLOSED",
"\n",
"nc",
".",
"kickFlusher",
"(",
")",
"\n",
"nc",
".",
"mu",
".",
"Unlock",
"(",
")",
"\n",
"nc",
".",
"mu",
".",
"Lock",
"(",
")",
"\n",
"nc",
".",
"clearPendingFlushCalls",
"(",
")",
"\n",
"nc",
".",
"clearPendingRequestCalls",
"(",
")",
"\n",
"nc",
".",
"stopPingTimer",
"(",
")",
"\n",
"nc",
".",
"ptmr",
"=",
"nil",
"\n",
"if",
"nc",
".",
"conn",
"!=",
"nil",
"{",
"nc",
".",
"bw",
".",
"Flush",
"(",
")",
"\n",
"defer",
"nc",
".",
"conn",
".",
"Close",
"(",
")",
"\n",
"}",
"\n",
"nc",
".",
"subsMu",
".",
"Lock",
"(",
")",
"\n",
"for",
"_",
",",
"s",
":=",
"range",
"nc",
".",
"subs",
"{",
"s",
".",
"mu",
".",
"Lock",
"(",
")",
"\n",
"if",
"s",
".",
"mch",
"!=",
"nil",
"&&",
"s",
".",
"typ",
"==",
"SyncSubscription",
"{",
"close",
"(",
"s",
".",
"mch",
")",
"\n",
"}",
"\n",
"s",
".",
"mch",
"=",
"nil",
"\n",
"s",
".",
"closed",
"=",
"true",
"\n",
"s",
".",
"connClosed",
"=",
"true",
"\n",
"if",
"s",
".",
"typ",
"==",
"AsyncSubscription",
"&&",
"s",
".",
"pCond",
"!=",
"nil",
"{",
"s",
".",
"pCond",
".",
"Signal",
"(",
")",
"\n",
"}",
"\n",
"s",
".",
"mu",
".",
"Unlock",
"(",
")",
"\n",
"}",
"\n",
"nc",
".",
"subs",
"=",
"nil",
"\n",
"nc",
".",
"subsMu",
".",
"Unlock",
"(",
")",
"\n",
"nc",
".",
"status",
"=",
"status",
"\n",
"if",
"doCBs",
"{",
"if",
"nc",
".",
"Opts",
".",
"DisconnectedCB",
"!=",
"nil",
"&&",
"nc",
".",
"conn",
"!=",
"nil",
"{",
"nc",
".",
"ach",
".",
"push",
"(",
"func",
"(",
")",
"{",
"nc",
".",
"Opts",
".",
"DisconnectedCB",
"(",
"nc",
")",
"}",
")",
"\n",
"}",
"\n",
"if",
"nc",
".",
"Opts",
".",
"ClosedCB",
"!=",
"nil",
"{",
"nc",
".",
"ach",
".",
"push",
"(",
"func",
"(",
")",
"{",
"nc",
".",
"Opts",
".",
"ClosedCB",
"(",
"nc",
")",
"}",
")",
"\n",
"}",
"\n",
"nc",
".",
"ach",
".",
"close",
"(",
")",
"\n",
"}",
"\n",
"nc",
".",
"mu",
".",
"Unlock",
"(",
")",
"\n",
"}"
] | // Low level close call that will do correct cleanup and set
// desired status. Also controls whether user defined callbacks
// will be triggered. The lock should not be held entering this
// function. This function will handle the locking manually. | [
"Low",
"level",
"close",
"call",
"that",
"will",
"do",
"correct",
"cleanup",
"and",
"set",
"desired",
"status",
".",
"Also",
"controls",
"whether",
"user",
"defined",
"callbacks",
"will",
"be",
"triggered",
".",
"The",
"lock",
"should",
"not",
"be",
"held",
"entering",
"this",
"function",
".",
"This",
"function",
"will",
"handle",
"the",
"locking",
"manually",
"."
] | 36d30b0ba7aa260ae25b4f3d312b2a700106fd78 | https://github.com/nats-io/go-nats/blob/36d30b0ba7aa260ae25b4f3d312b2a700106fd78/nats.go#L3454-L3523 | train |
nats-io/go-nats | nats.go | IsClosed | func (nc *Conn) IsClosed() bool {
nc.mu.RLock()
defer nc.mu.RUnlock()
return nc.isClosed()
} | go | func (nc *Conn) IsClosed() bool {
nc.mu.RLock()
defer nc.mu.RUnlock()
return nc.isClosed()
} | [
"func",
"(",
"nc",
"*",
"Conn",
")",
"IsClosed",
"(",
")",
"bool",
"{",
"nc",
".",
"mu",
".",
"RLock",
"(",
")",
"\n",
"defer",
"nc",
".",
"mu",
".",
"RUnlock",
"(",
")",
"\n",
"return",
"nc",
".",
"isClosed",
"(",
")",
"\n",
"}"
] | // IsClosed tests if a Conn has been closed. | [
"IsClosed",
"tests",
"if",
"a",
"Conn",
"has",
"been",
"closed",
"."
] | 36d30b0ba7aa260ae25b4f3d312b2a700106fd78 | https://github.com/nats-io/go-nats/blob/36d30b0ba7aa260ae25b4f3d312b2a700106fd78/nats.go#L3534-L3538 | train |
nats-io/go-nats | nats.go | IsReconnecting | func (nc *Conn) IsReconnecting() bool {
nc.mu.RLock()
defer nc.mu.RUnlock()
return nc.isReconnecting()
} | go | func (nc *Conn) IsReconnecting() bool {
nc.mu.RLock()
defer nc.mu.RUnlock()
return nc.isReconnecting()
} | [
"func",
"(",
"nc",
"*",
"Conn",
")",
"IsReconnecting",
"(",
")",
"bool",
"{",
"nc",
".",
"mu",
".",
"RLock",
"(",
")",
"\n",
"defer",
"nc",
".",
"mu",
".",
"RUnlock",
"(",
")",
"\n",
"return",
"nc",
".",
"isReconnecting",
"(",
")",
"\n",
"}"
] | // IsReconnecting tests if a Conn is reconnecting. | [
"IsReconnecting",
"tests",
"if",
"a",
"Conn",
"is",
"reconnecting",
"."
] | 36d30b0ba7aa260ae25b4f3d312b2a700106fd78 | https://github.com/nats-io/go-nats/blob/36d30b0ba7aa260ae25b4f3d312b2a700106fd78/nats.go#L3541-L3545 | train |
nats-io/go-nats | nats.go | IsConnected | func (nc *Conn) IsConnected() bool {
nc.mu.RLock()
defer nc.mu.RUnlock()
return nc.isConnected()
} | go | func (nc *Conn) IsConnected() bool {
nc.mu.RLock()
defer nc.mu.RUnlock()
return nc.isConnected()
} | [
"func",
"(",
"nc",
"*",
"Conn",
")",
"IsConnected",
"(",
")",
"bool",
"{",
"nc",
".",
"mu",
".",
"RLock",
"(",
")",
"\n",
"defer",
"nc",
".",
"mu",
".",
"RUnlock",
"(",
")",
"\n",
"return",
"nc",
".",
"isConnected",
"(",
")",
"\n",
"}"
] | // IsConnected tests if a Conn is connected. | [
"IsConnected",
"tests",
"if",
"a",
"Conn",
"is",
"connected",
"."
] | 36d30b0ba7aa260ae25b4f3d312b2a700106fd78 | https://github.com/nats-io/go-nats/blob/36d30b0ba7aa260ae25b4f3d312b2a700106fd78/nats.go#L3548-L3552 | train |
nats-io/go-nats | nats.go | drainConnection | func (nc *Conn) drainConnection() {
// Snapshot subs list.
nc.mu.Lock()
subs := make([]*Subscription, 0, len(nc.subs))
for _, s := range nc.subs {
subs = append(subs, s)
}
errCB := nc.Opts.AsyncErrorCB
drainWait := nc.Opts.DrainTimeout
nc.mu.Unlock()
// for pushing errors with context.
pushErr := func(err error) {
nc.mu.Lock()
nc.err = err
if errCB != nil {
nc.ach.push(func() { errCB(nc, nil, err) })
}
nc.mu.Unlock()
}
// Do subs first
for _, s := range subs {
if err := s.Drain(); err != nil {
// We will notify about these but continue.
pushErr(err)
}
}
// Wait for the subscriptions to drop to zero.
timeout := time.Now().Add(drainWait)
for time.Now().Before(timeout) {
if nc.NumSubscriptions() == 0 {
break
}
time.Sleep(10 * time.Millisecond)
}
// Check if we timed out.
if nc.NumSubscriptions() != 0 {
pushErr(ErrDrainTimeout)
}
// Flip State
nc.mu.Lock()
nc.status = DRAINING_PUBS
nc.mu.Unlock()
// Do publish drain via Flush() call.
err := nc.Flush()
if err != nil {
pushErr(err)
nc.Close()
return
}
// Move to closed state.
nc.Close()
} | go | func (nc *Conn) drainConnection() {
// Snapshot subs list.
nc.mu.Lock()
subs := make([]*Subscription, 0, len(nc.subs))
for _, s := range nc.subs {
subs = append(subs, s)
}
errCB := nc.Opts.AsyncErrorCB
drainWait := nc.Opts.DrainTimeout
nc.mu.Unlock()
// for pushing errors with context.
pushErr := func(err error) {
nc.mu.Lock()
nc.err = err
if errCB != nil {
nc.ach.push(func() { errCB(nc, nil, err) })
}
nc.mu.Unlock()
}
// Do subs first
for _, s := range subs {
if err := s.Drain(); err != nil {
// We will notify about these but continue.
pushErr(err)
}
}
// Wait for the subscriptions to drop to zero.
timeout := time.Now().Add(drainWait)
for time.Now().Before(timeout) {
if nc.NumSubscriptions() == 0 {
break
}
time.Sleep(10 * time.Millisecond)
}
// Check if we timed out.
if nc.NumSubscriptions() != 0 {
pushErr(ErrDrainTimeout)
}
// Flip State
nc.mu.Lock()
nc.status = DRAINING_PUBS
nc.mu.Unlock()
// Do publish drain via Flush() call.
err := nc.Flush()
if err != nil {
pushErr(err)
nc.Close()
return
}
// Move to closed state.
nc.Close()
} | [
"func",
"(",
"nc",
"*",
"Conn",
")",
"drainConnection",
"(",
")",
"{",
"nc",
".",
"mu",
".",
"Lock",
"(",
")",
"\n",
"subs",
":=",
"make",
"(",
"[",
"]",
"*",
"Subscription",
",",
"0",
",",
"len",
"(",
"nc",
".",
"subs",
")",
")",
"\n",
"for",
"_",
",",
"s",
":=",
"range",
"nc",
".",
"subs",
"{",
"subs",
"=",
"append",
"(",
"subs",
",",
"s",
")",
"\n",
"}",
"\n",
"errCB",
":=",
"nc",
".",
"Opts",
".",
"AsyncErrorCB",
"\n",
"drainWait",
":=",
"nc",
".",
"Opts",
".",
"DrainTimeout",
"\n",
"nc",
".",
"mu",
".",
"Unlock",
"(",
")",
"\n",
"pushErr",
":=",
"func",
"(",
"err",
"error",
")",
"{",
"nc",
".",
"mu",
".",
"Lock",
"(",
")",
"\n",
"nc",
".",
"err",
"=",
"err",
"\n",
"if",
"errCB",
"!=",
"nil",
"{",
"nc",
".",
"ach",
".",
"push",
"(",
"func",
"(",
")",
"{",
"errCB",
"(",
"nc",
",",
"nil",
",",
"err",
")",
"}",
")",
"\n",
"}",
"\n",
"nc",
".",
"mu",
".",
"Unlock",
"(",
")",
"\n",
"}",
"\n",
"for",
"_",
",",
"s",
":=",
"range",
"subs",
"{",
"if",
"err",
":=",
"s",
".",
"Drain",
"(",
")",
";",
"err",
"!=",
"nil",
"{",
"pushErr",
"(",
"err",
")",
"\n",
"}",
"\n",
"}",
"\n",
"timeout",
":=",
"time",
".",
"Now",
"(",
")",
".",
"Add",
"(",
"drainWait",
")",
"\n",
"for",
"time",
".",
"Now",
"(",
")",
".",
"Before",
"(",
"timeout",
")",
"{",
"if",
"nc",
".",
"NumSubscriptions",
"(",
")",
"==",
"0",
"{",
"break",
"\n",
"}",
"\n",
"time",
".",
"Sleep",
"(",
"10",
"*",
"time",
".",
"Millisecond",
")",
"\n",
"}",
"\n",
"if",
"nc",
".",
"NumSubscriptions",
"(",
")",
"!=",
"0",
"{",
"pushErr",
"(",
"ErrDrainTimeout",
")",
"\n",
"}",
"\n",
"nc",
".",
"mu",
".",
"Lock",
"(",
")",
"\n",
"nc",
".",
"status",
"=",
"DRAINING_PUBS",
"\n",
"nc",
".",
"mu",
".",
"Unlock",
"(",
")",
"\n",
"err",
":=",
"nc",
".",
"Flush",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"pushErr",
"(",
"err",
")",
"\n",
"nc",
".",
"Close",
"(",
")",
"\n",
"return",
"\n",
"}",
"\n",
"nc",
".",
"Close",
"(",
")",
"\n",
"}"
] | // drainConnection will run in a separate Go routine and will
// flush all publishes and drain all active subscriptions. | [
"drainConnection",
"will",
"run",
"in",
"a",
"separate",
"Go",
"routine",
"and",
"will",
"flush",
"all",
"publishes",
"and",
"drain",
"all",
"active",
"subscriptions",
"."
] | 36d30b0ba7aa260ae25b4f3d312b2a700106fd78 | https://github.com/nats-io/go-nats/blob/36d30b0ba7aa260ae25b4f3d312b2a700106fd78/nats.go#L3556-L3614 | train |
nats-io/go-nats | nats.go | IsDraining | func (nc *Conn) IsDraining() bool {
nc.mu.RLock()
defer nc.mu.RUnlock()
return nc.isDraining()
} | go | func (nc *Conn) IsDraining() bool {
nc.mu.RLock()
defer nc.mu.RUnlock()
return nc.isDraining()
} | [
"func",
"(",
"nc",
"*",
"Conn",
")",
"IsDraining",
"(",
")",
"bool",
"{",
"nc",
".",
"mu",
".",
"RLock",
"(",
")",
"\n",
"defer",
"nc",
".",
"mu",
".",
"RUnlock",
"(",
")",
"\n",
"return",
"nc",
".",
"isDraining",
"(",
")",
"\n",
"}"
] | // IsDraining tests if a Conn is in the draining state. | [
"IsDraining",
"tests",
"if",
"a",
"Conn",
"is",
"in",
"the",
"draining",
"state",
"."
] | 36d30b0ba7aa260ae25b4f3d312b2a700106fd78 | https://github.com/nats-io/go-nats/blob/36d30b0ba7aa260ae25b4f3d312b2a700106fd78/nats.go#L3641-L3645 | train |
nats-io/go-nats | nats.go | getServers | func (nc *Conn) getServers(implicitOnly bool) []string {
poolSize := len(nc.srvPool)
var servers = make([]string, 0)
for i := 0; i < poolSize; i++ {
if implicitOnly && !nc.srvPool[i].isImplicit {
continue
}
url := nc.srvPool[i].url
servers = append(servers, fmt.Sprintf("%s://%s", url.Scheme, url.Host))
}
return servers
} | go | func (nc *Conn) getServers(implicitOnly bool) []string {
poolSize := len(nc.srvPool)
var servers = make([]string, 0)
for i := 0; i < poolSize; i++ {
if implicitOnly && !nc.srvPool[i].isImplicit {
continue
}
url := nc.srvPool[i].url
servers = append(servers, fmt.Sprintf("%s://%s", url.Scheme, url.Host))
}
return servers
} | [
"func",
"(",
"nc",
"*",
"Conn",
")",
"getServers",
"(",
"implicitOnly",
"bool",
")",
"[",
"]",
"string",
"{",
"poolSize",
":=",
"len",
"(",
"nc",
".",
"srvPool",
")",
"\n",
"var",
"servers",
"=",
"make",
"(",
"[",
"]",
"string",
",",
"0",
")",
"\n",
"for",
"i",
":=",
"0",
";",
"i",
"<",
"poolSize",
";",
"i",
"++",
"{",
"if",
"implicitOnly",
"&&",
"!",
"nc",
".",
"srvPool",
"[",
"i",
"]",
".",
"isImplicit",
"{",
"continue",
"\n",
"}",
"\n",
"url",
":=",
"nc",
".",
"srvPool",
"[",
"i",
"]",
".",
"url",
"\n",
"servers",
"=",
"append",
"(",
"servers",
",",
"fmt",
".",
"Sprintf",
"(",
"\"%s://%s\"",
",",
"url",
".",
"Scheme",
",",
"url",
".",
"Host",
")",
")",
"\n",
"}",
"\n",
"return",
"servers",
"\n",
"}"
] | // caller must lock | [
"caller",
"must",
"lock"
] | 36d30b0ba7aa260ae25b4f3d312b2a700106fd78 | https://github.com/nats-io/go-nats/blob/36d30b0ba7aa260ae25b4f3d312b2a700106fd78/nats.go#L3648-L3659 | train |
nats-io/go-nats | nats.go | Servers | func (nc *Conn) Servers() []string {
nc.mu.RLock()
defer nc.mu.RUnlock()
return nc.getServers(false)
} | go | func (nc *Conn) Servers() []string {
nc.mu.RLock()
defer nc.mu.RUnlock()
return nc.getServers(false)
} | [
"func",
"(",
"nc",
"*",
"Conn",
")",
"Servers",
"(",
")",
"[",
"]",
"string",
"{",
"nc",
".",
"mu",
".",
"RLock",
"(",
")",
"\n",
"defer",
"nc",
".",
"mu",
".",
"RUnlock",
"(",
")",
"\n",
"return",
"nc",
".",
"getServers",
"(",
"false",
")",
"\n",
"}"
] | // Servers returns the list of known server urls, including additional
// servers discovered after a connection has been established. If
// authentication is enabled, use UserInfo or Token when connecting with
// these urls. | [
"Servers",
"returns",
"the",
"list",
"of",
"known",
"server",
"urls",
"including",
"additional",
"servers",
"discovered",
"after",
"a",
"connection",
"has",
"been",
"established",
".",
"If",
"authentication",
"is",
"enabled",
"use",
"UserInfo",
"or",
"Token",
"when",
"connecting",
"with",
"these",
"urls",
"."
] | 36d30b0ba7aa260ae25b4f3d312b2a700106fd78 | https://github.com/nats-io/go-nats/blob/36d30b0ba7aa260ae25b4f3d312b2a700106fd78/nats.go#L3665-L3669 | train |
nats-io/go-nats | nats.go | DiscoveredServers | func (nc *Conn) DiscoveredServers() []string {
nc.mu.RLock()
defer nc.mu.RUnlock()
return nc.getServers(true)
} | go | func (nc *Conn) DiscoveredServers() []string {
nc.mu.RLock()
defer nc.mu.RUnlock()
return nc.getServers(true)
} | [
"func",
"(",
"nc",
"*",
"Conn",
")",
"DiscoveredServers",
"(",
")",
"[",
"]",
"string",
"{",
"nc",
".",
"mu",
".",
"RLock",
"(",
")",
"\n",
"defer",
"nc",
".",
"mu",
".",
"RUnlock",
"(",
")",
"\n",
"return",
"nc",
".",
"getServers",
"(",
"true",
")",
"\n",
"}"
] | // DiscoveredServers returns only the server urls that have been discovered
// after a connection has been established. If authentication is enabled,
// use UserInfo or Token when connecting with these urls. | [
"DiscoveredServers",
"returns",
"only",
"the",
"server",
"urls",
"that",
"have",
"been",
"discovered",
"after",
"a",
"connection",
"has",
"been",
"established",
".",
"If",
"authentication",
"is",
"enabled",
"use",
"UserInfo",
"or",
"Token",
"when",
"connecting",
"with",
"these",
"urls",
"."
] | 36d30b0ba7aa260ae25b4f3d312b2a700106fd78 | https://github.com/nats-io/go-nats/blob/36d30b0ba7aa260ae25b4f3d312b2a700106fd78/nats.go#L3674-L3678 | train |
nats-io/go-nats | nats.go | Status | func (nc *Conn) Status() Status {
nc.mu.RLock()
defer nc.mu.RUnlock()
return nc.status
} | go | func (nc *Conn) Status() Status {
nc.mu.RLock()
defer nc.mu.RUnlock()
return nc.status
} | [
"func",
"(",
"nc",
"*",
"Conn",
")",
"Status",
"(",
")",
"Status",
"{",
"nc",
".",
"mu",
".",
"RLock",
"(",
")",
"\n",
"defer",
"nc",
".",
"mu",
".",
"RUnlock",
"(",
")",
"\n",
"return",
"nc",
".",
"status",
"\n",
"}"
] | // Status returns the current state of the connection. | [
"Status",
"returns",
"the",
"current",
"state",
"of",
"the",
"connection",
"."
] | 36d30b0ba7aa260ae25b4f3d312b2a700106fd78 | https://github.com/nats-io/go-nats/blob/36d30b0ba7aa260ae25b4f3d312b2a700106fd78/nats.go#L3681-L3685 | train |
nats-io/go-nats | nats.go | isDraining | func (nc *Conn) isDraining() bool {
return nc.status == DRAINING_SUBS || nc.status == DRAINING_PUBS
} | go | func (nc *Conn) isDraining() bool {
return nc.status == DRAINING_SUBS || nc.status == DRAINING_PUBS
} | [
"func",
"(",
"nc",
"*",
"Conn",
")",
"isDraining",
"(",
")",
"bool",
"{",
"return",
"nc",
".",
"status",
"==",
"DRAINING_SUBS",
"||",
"nc",
".",
"status",
"==",
"DRAINING_PUBS",
"\n",
"}"
] | // Test if Conn is in the draining state. | [
"Test",
"if",
"Conn",
"is",
"in",
"the",
"draining",
"state",
"."
] | 36d30b0ba7aa260ae25b4f3d312b2a700106fd78 | https://github.com/nats-io/go-nats/blob/36d30b0ba7aa260ae25b4f3d312b2a700106fd78/nats.go#L3708-L3710 | train |
nats-io/go-nats | nats.go | Stats | func (nc *Conn) Stats() Statistics {
// Stats are updated either under connection's mu or subsMu mutexes.
// Lock both to safely get them.
nc.mu.Lock()
nc.subsMu.RLock()
stats := Statistics{
InMsgs: nc.InMsgs,
InBytes: nc.InBytes,
OutMsgs: nc.OutMsgs,
OutBytes: nc.OutBytes,
Reconnects: nc.Reconnects,
}
nc.subsMu.RUnlock()
nc.mu.Unlock()
return stats
} | go | func (nc *Conn) Stats() Statistics {
// Stats are updated either under connection's mu or subsMu mutexes.
// Lock both to safely get them.
nc.mu.Lock()
nc.subsMu.RLock()
stats := Statistics{
InMsgs: nc.InMsgs,
InBytes: nc.InBytes,
OutMsgs: nc.OutMsgs,
OutBytes: nc.OutBytes,
Reconnects: nc.Reconnects,
}
nc.subsMu.RUnlock()
nc.mu.Unlock()
return stats
} | [
"func",
"(",
"nc",
"*",
"Conn",
")",
"Stats",
"(",
")",
"Statistics",
"{",
"nc",
".",
"mu",
".",
"Lock",
"(",
")",
"\n",
"nc",
".",
"subsMu",
".",
"RLock",
"(",
")",
"\n",
"stats",
":=",
"Statistics",
"{",
"InMsgs",
":",
"nc",
".",
"InMsgs",
",",
"InBytes",
":",
"nc",
".",
"InBytes",
",",
"OutMsgs",
":",
"nc",
".",
"OutMsgs",
",",
"OutBytes",
":",
"nc",
".",
"OutBytes",
",",
"Reconnects",
":",
"nc",
".",
"Reconnects",
",",
"}",
"\n",
"nc",
".",
"subsMu",
".",
"RUnlock",
"(",
")",
"\n",
"nc",
".",
"mu",
".",
"Unlock",
"(",
")",
"\n",
"return",
"stats",
"\n",
"}"
] | // Stats will return a race safe copy of the Statistics section for the connection. | [
"Stats",
"will",
"return",
"a",
"race",
"safe",
"copy",
"of",
"the",
"Statistics",
"section",
"for",
"the",
"connection",
"."
] | 36d30b0ba7aa260ae25b4f3d312b2a700106fd78 | https://github.com/nats-io/go-nats/blob/36d30b0ba7aa260ae25b4f3d312b2a700106fd78/nats.go#L3718-L3733 | train |
nats-io/go-nats | nats.go | MaxPayload | func (nc *Conn) MaxPayload() int64 {
nc.mu.RLock()
defer nc.mu.RUnlock()
return nc.info.MaxPayload
} | go | func (nc *Conn) MaxPayload() int64 {
nc.mu.RLock()
defer nc.mu.RUnlock()
return nc.info.MaxPayload
} | [
"func",
"(",
"nc",
"*",
"Conn",
")",
"MaxPayload",
"(",
")",
"int64",
"{",
"nc",
".",
"mu",
".",
"RLock",
"(",
")",
"\n",
"defer",
"nc",
".",
"mu",
".",
"RUnlock",
"(",
")",
"\n",
"return",
"nc",
".",
"info",
".",
"MaxPayload",
"\n",
"}"
] | // MaxPayload returns the size limit that a message payload can have.
// This is set by the server configuration and delivered to the client
// upon connect. | [
"MaxPayload",
"returns",
"the",
"size",
"limit",
"that",
"a",
"message",
"payload",
"can",
"have",
".",
"This",
"is",
"set",
"by",
"the",
"server",
"configuration",
"and",
"delivered",
"to",
"the",
"client",
"upon",
"connect",
"."
] | 36d30b0ba7aa260ae25b4f3d312b2a700106fd78 | https://github.com/nats-io/go-nats/blob/36d30b0ba7aa260ae25b4f3d312b2a700106fd78/nats.go#L3738-L3742 | train |
nats-io/go-nats | nats.go | AuthRequired | func (nc *Conn) AuthRequired() bool {
nc.mu.RLock()
defer nc.mu.RUnlock()
return nc.info.AuthRequired
} | go | func (nc *Conn) AuthRequired() bool {
nc.mu.RLock()
defer nc.mu.RUnlock()
return nc.info.AuthRequired
} | [
"func",
"(",
"nc",
"*",
"Conn",
")",
"AuthRequired",
"(",
")",
"bool",
"{",
"nc",
".",
"mu",
".",
"RLock",
"(",
")",
"\n",
"defer",
"nc",
".",
"mu",
".",
"RUnlock",
"(",
")",
"\n",
"return",
"nc",
".",
"info",
".",
"AuthRequired",
"\n",
"}"
] | // AuthRequired will return if the connected server requires authorization. | [
"AuthRequired",
"will",
"return",
"if",
"the",
"connected",
"server",
"requires",
"authorization",
"."
] | 36d30b0ba7aa260ae25b4f3d312b2a700106fd78 | https://github.com/nats-io/go-nats/blob/36d30b0ba7aa260ae25b4f3d312b2a700106fd78/nats.go#L3745-L3749 | train |
nats-io/go-nats | nats.go | TLSRequired | func (nc *Conn) TLSRequired() bool {
nc.mu.RLock()
defer nc.mu.RUnlock()
return nc.info.TLSRequired
} | go | func (nc *Conn) TLSRequired() bool {
nc.mu.RLock()
defer nc.mu.RUnlock()
return nc.info.TLSRequired
} | [
"func",
"(",
"nc",
"*",
"Conn",
")",
"TLSRequired",
"(",
")",
"bool",
"{",
"nc",
".",
"mu",
".",
"RLock",
"(",
")",
"\n",
"defer",
"nc",
".",
"mu",
".",
"RUnlock",
"(",
")",
"\n",
"return",
"nc",
".",
"info",
".",
"TLSRequired",
"\n",
"}"
] | // TLSRequired will return if the connected server requires TLS connections. | [
"TLSRequired",
"will",
"return",
"if",
"the",
"connected",
"server",
"requires",
"TLS",
"connections",
"."
] | 36d30b0ba7aa260ae25b4f3d312b2a700106fd78 | https://github.com/nats-io/go-nats/blob/36d30b0ba7aa260ae25b4f3d312b2a700106fd78/nats.go#L3752-L3756 | train |
nats-io/go-nats | nats.go | GetClientID | func (nc *Conn) GetClientID() (uint64, error) {
nc.mu.RLock()
defer nc.mu.RUnlock()
if nc.isClosed() {
return 0, ErrConnectionClosed
}
if nc.info.CID == 0 {
return 0, ErrClientIDNotSupported
}
return nc.info.CID, nil
} | go | func (nc *Conn) GetClientID() (uint64, error) {
nc.mu.RLock()
defer nc.mu.RUnlock()
if nc.isClosed() {
return 0, ErrConnectionClosed
}
if nc.info.CID == 0 {
return 0, ErrClientIDNotSupported
}
return nc.info.CID, nil
} | [
"func",
"(",
"nc",
"*",
"Conn",
")",
"GetClientID",
"(",
")",
"(",
"uint64",
",",
"error",
")",
"{",
"nc",
".",
"mu",
".",
"RLock",
"(",
")",
"\n",
"defer",
"nc",
".",
"mu",
".",
"RUnlock",
"(",
")",
"\n",
"if",
"nc",
".",
"isClosed",
"(",
")",
"{",
"return",
"0",
",",
"ErrConnectionClosed",
"\n",
"}",
"\n",
"if",
"nc",
".",
"info",
".",
"CID",
"==",
"0",
"{",
"return",
"0",
",",
"ErrClientIDNotSupported",
"\n",
"}",
"\n",
"return",
"nc",
".",
"info",
".",
"CID",
",",
"nil",
"\n",
"}"
] | // GetClientID returns the client ID assigned by the server to which
// the client is currently connected to. Note that the value may change if
// the client reconnects.
// This function returns ErrNoClientIDReturned if the server is of a
// version prior to 1.2.0. | [
"GetClientID",
"returns",
"the",
"client",
"ID",
"assigned",
"by",
"the",
"server",
"to",
"which",
"the",
"client",
"is",
"currently",
"connected",
"to",
".",
"Note",
"that",
"the",
"value",
"may",
"change",
"if",
"the",
"client",
"reconnects",
".",
"This",
"function",
"returns",
"ErrNoClientIDReturned",
"if",
"the",
"server",
"is",
"of",
"a",
"version",
"prior",
"to",
"1",
".",
"2",
".",
"0",
"."
] | 36d30b0ba7aa260ae25b4f3d312b2a700106fd78 | https://github.com/nats-io/go-nats/blob/36d30b0ba7aa260ae25b4f3d312b2a700106fd78/nats.go#L3811-L3821 | train |
nats-io/go-nats | nats.go | NkeyOptionFromSeed | func NkeyOptionFromSeed(seedFile string) (Option, error) {
kp, err := nkeyPairFromSeedFile(seedFile)
if err != nil {
return nil, err
}
// Wipe our key on exit.
defer kp.Wipe()
pub, err := kp.PublicKey()
if err != nil {
return nil, err
}
if !nkeys.IsValidPublicUserKey(pub) {
return nil, fmt.Errorf("nats: Not a valid nkey user seed")
}
sigCB := func(nonce []byte) ([]byte, error) {
return sigHandler(nonce, seedFile)
}
return Nkey(string(pub), sigCB), nil
} | go | func NkeyOptionFromSeed(seedFile string) (Option, error) {
kp, err := nkeyPairFromSeedFile(seedFile)
if err != nil {
return nil, err
}
// Wipe our key on exit.
defer kp.Wipe()
pub, err := kp.PublicKey()
if err != nil {
return nil, err
}
if !nkeys.IsValidPublicUserKey(pub) {
return nil, fmt.Errorf("nats: Not a valid nkey user seed")
}
sigCB := func(nonce []byte) ([]byte, error) {
return sigHandler(nonce, seedFile)
}
return Nkey(string(pub), sigCB), nil
} | [
"func",
"NkeyOptionFromSeed",
"(",
"seedFile",
"string",
")",
"(",
"Option",
",",
"error",
")",
"{",
"kp",
",",
"err",
":=",
"nkeyPairFromSeedFile",
"(",
"seedFile",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"defer",
"kp",
".",
"Wipe",
"(",
")",
"\n",
"pub",
",",
"err",
":=",
"kp",
".",
"PublicKey",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"if",
"!",
"nkeys",
".",
"IsValidPublicUserKey",
"(",
"pub",
")",
"{",
"return",
"nil",
",",
"fmt",
".",
"Errorf",
"(",
"\"nats: Not a valid nkey user seed\"",
")",
"\n",
"}",
"\n",
"sigCB",
":=",
"func",
"(",
"nonce",
"[",
"]",
"byte",
")",
"(",
"[",
"]",
"byte",
",",
"error",
")",
"{",
"return",
"sigHandler",
"(",
"nonce",
",",
"seedFile",
")",
"\n",
"}",
"\n",
"return",
"Nkey",
"(",
"string",
"(",
"pub",
")",
",",
"sigCB",
")",
",",
"nil",
"\n",
"}"
] | // NkeyOptionFromSeed will load an nkey pair from a seed file.
// It will return the NKey Option and will handle
// signing of nonce challenges from the server. It will take
// care to not hold keys in memory and to wipe memory. | [
"NkeyOptionFromSeed",
"will",
"load",
"an",
"nkey",
"pair",
"from",
"a",
"seed",
"file",
".",
"It",
"will",
"return",
"the",
"NKey",
"Option",
"and",
"will",
"handle",
"signing",
"of",
"nonce",
"challenges",
"from",
"the",
"server",
".",
"It",
"will",
"take",
"care",
"to",
"not",
"hold",
"keys",
"in",
"memory",
"and",
"to",
"wipe",
"memory",
"."
] | 36d30b0ba7aa260ae25b4f3d312b2a700106fd78 | https://github.com/nats-io/go-nats/blob/36d30b0ba7aa260ae25b4f3d312b2a700106fd78/nats.go#L3827-L3846 | train |
nats-io/go-nats | nats.go | sigHandler | func sigHandler(nonce []byte, seedFile string) ([]byte, error) {
kp, err := nkeyPairFromSeedFile(seedFile)
if err != nil {
return nil, err
}
// Wipe our key on exit.
defer kp.Wipe()
sig, _ := kp.Sign(nonce)
return sig, nil
} | go | func sigHandler(nonce []byte, seedFile string) ([]byte, error) {
kp, err := nkeyPairFromSeedFile(seedFile)
if err != nil {
return nil, err
}
// Wipe our key on exit.
defer kp.Wipe()
sig, _ := kp.Sign(nonce)
return sig, nil
} | [
"func",
"sigHandler",
"(",
"nonce",
"[",
"]",
"byte",
",",
"seedFile",
"string",
")",
"(",
"[",
"]",
"byte",
",",
"error",
")",
"{",
"kp",
",",
"err",
":=",
"nkeyPairFromSeedFile",
"(",
"seedFile",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"defer",
"kp",
".",
"Wipe",
"(",
")",
"\n",
"sig",
",",
"_",
":=",
"kp",
".",
"Sign",
"(",
"nonce",
")",
"\n",
"return",
"sig",
",",
"nil",
"\n",
"}"
] | // Sign authentication challenges from the server.
// Do not keep private seed in memory. | [
"Sign",
"authentication",
"challenges",
"from",
"the",
"server",
".",
"Do",
"not",
"keep",
"private",
"seed",
"in",
"memory",
"."
] | 36d30b0ba7aa260ae25b4f3d312b2a700106fd78 | https://github.com/nats-io/go-nats/blob/36d30b0ba7aa260ae25b4f3d312b2a700106fd78/nats.go#L3916-L3926 | train |
nats-io/go-nats | util/tls.go | CloneTLSConfig | func CloneTLSConfig(c *tls.Config) *tls.Config {
if c == nil {
return &tls.Config{}
}
return c.Clone()
} | go | func CloneTLSConfig(c *tls.Config) *tls.Config {
if c == nil {
return &tls.Config{}
}
return c.Clone()
} | [
"func",
"CloneTLSConfig",
"(",
"c",
"*",
"tls",
".",
"Config",
")",
"*",
"tls",
".",
"Config",
"{",
"if",
"c",
"==",
"nil",
"{",
"return",
"&",
"tls",
".",
"Config",
"{",
"}",
"\n",
"}",
"\n",
"return",
"c",
".",
"Clone",
"(",
")",
"\n",
"}"
] | // CloneTLSConfig returns a copy of c. | [
"CloneTLSConfig",
"returns",
"a",
"copy",
"of",
"c",
"."
] | 36d30b0ba7aa260ae25b4f3d312b2a700106fd78 | https://github.com/nats-io/go-nats/blob/36d30b0ba7aa260ae25b4f3d312b2a700106fd78/util/tls.go#L21-L27 | train |
nats-io/go-nats | context.go | RequestWithContext | func (nc *Conn) RequestWithContext(ctx context.Context, subj string, data []byte) (*Msg, error) {
if ctx == nil {
return nil, ErrInvalidContext
}
if nc == nil {
return nil, ErrInvalidConnection
}
// Check whether the context is done already before making
// the request.
if ctx.Err() != nil {
return nil, ctx.Err()
}
nc.mu.Lock()
// If user wants the old style.
if nc.Opts.UseOldRequestStyle {
nc.mu.Unlock()
return nc.oldRequestWithContext(ctx, subj, data)
}
// Do setup for the new style.
if nc.respMap == nil {
nc.initNewResp()
}
// Create literal Inbox and map to a chan msg.
mch := make(chan *Msg, RequestChanLen)
respInbox := nc.newRespInbox()
token := respToken(respInbox)
nc.respMap[token] = mch
createSub := nc.respMux == nil
ginbox := nc.respSub
nc.mu.Unlock()
if createSub {
// Make sure scoped subscription is setup only once.
var err error
nc.respSetup.Do(func() { err = nc.createRespMux(ginbox) })
if err != nil {
return nil, err
}
}
err := nc.PublishRequest(subj, respInbox, data)
if err != nil {
return nil, err
}
var ok bool
var msg *Msg
select {
case msg, ok = <-mch:
if !ok {
return nil, ErrConnectionClosed
}
case <-ctx.Done():
nc.mu.Lock()
delete(nc.respMap, token)
nc.mu.Unlock()
return nil, ctx.Err()
}
return msg, nil
} | go | func (nc *Conn) RequestWithContext(ctx context.Context, subj string, data []byte) (*Msg, error) {
if ctx == nil {
return nil, ErrInvalidContext
}
if nc == nil {
return nil, ErrInvalidConnection
}
// Check whether the context is done already before making
// the request.
if ctx.Err() != nil {
return nil, ctx.Err()
}
nc.mu.Lock()
// If user wants the old style.
if nc.Opts.UseOldRequestStyle {
nc.mu.Unlock()
return nc.oldRequestWithContext(ctx, subj, data)
}
// Do setup for the new style.
if nc.respMap == nil {
nc.initNewResp()
}
// Create literal Inbox and map to a chan msg.
mch := make(chan *Msg, RequestChanLen)
respInbox := nc.newRespInbox()
token := respToken(respInbox)
nc.respMap[token] = mch
createSub := nc.respMux == nil
ginbox := nc.respSub
nc.mu.Unlock()
if createSub {
// Make sure scoped subscription is setup only once.
var err error
nc.respSetup.Do(func() { err = nc.createRespMux(ginbox) })
if err != nil {
return nil, err
}
}
err := nc.PublishRequest(subj, respInbox, data)
if err != nil {
return nil, err
}
var ok bool
var msg *Msg
select {
case msg, ok = <-mch:
if !ok {
return nil, ErrConnectionClosed
}
case <-ctx.Done():
nc.mu.Lock()
delete(nc.respMap, token)
nc.mu.Unlock()
return nil, ctx.Err()
}
return msg, nil
} | [
"func",
"(",
"nc",
"*",
"Conn",
")",
"RequestWithContext",
"(",
"ctx",
"context",
".",
"Context",
",",
"subj",
"string",
",",
"data",
"[",
"]",
"byte",
")",
"(",
"*",
"Msg",
",",
"error",
")",
"{",
"if",
"ctx",
"==",
"nil",
"{",
"return",
"nil",
",",
"ErrInvalidContext",
"\n",
"}",
"\n",
"if",
"nc",
"==",
"nil",
"{",
"return",
"nil",
",",
"ErrInvalidConnection",
"\n",
"}",
"\n",
"if",
"ctx",
".",
"Err",
"(",
")",
"!=",
"nil",
"{",
"return",
"nil",
",",
"ctx",
".",
"Err",
"(",
")",
"\n",
"}",
"\n",
"nc",
".",
"mu",
".",
"Lock",
"(",
")",
"\n",
"if",
"nc",
".",
"Opts",
".",
"UseOldRequestStyle",
"{",
"nc",
".",
"mu",
".",
"Unlock",
"(",
")",
"\n",
"return",
"nc",
".",
"oldRequestWithContext",
"(",
"ctx",
",",
"subj",
",",
"data",
")",
"\n",
"}",
"\n",
"if",
"nc",
".",
"respMap",
"==",
"nil",
"{",
"nc",
".",
"initNewResp",
"(",
")",
"\n",
"}",
"\n",
"mch",
":=",
"make",
"(",
"chan",
"*",
"Msg",
",",
"RequestChanLen",
")",
"\n",
"respInbox",
":=",
"nc",
".",
"newRespInbox",
"(",
")",
"\n",
"token",
":=",
"respToken",
"(",
"respInbox",
")",
"\n",
"nc",
".",
"respMap",
"[",
"token",
"]",
"=",
"mch",
"\n",
"createSub",
":=",
"nc",
".",
"respMux",
"==",
"nil",
"\n",
"ginbox",
":=",
"nc",
".",
"respSub",
"\n",
"nc",
".",
"mu",
".",
"Unlock",
"(",
")",
"\n",
"if",
"createSub",
"{",
"var",
"err",
"error",
"\n",
"nc",
".",
"respSetup",
".",
"Do",
"(",
"func",
"(",
")",
"{",
"err",
"=",
"nc",
".",
"createRespMux",
"(",
"ginbox",
")",
"}",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"}",
"\n",
"err",
":=",
"nc",
".",
"PublishRequest",
"(",
"subj",
",",
"respInbox",
",",
"data",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"var",
"ok",
"bool",
"\n",
"var",
"msg",
"*",
"Msg",
"\n",
"select",
"{",
"case",
"msg",
",",
"ok",
"=",
"<-",
"mch",
":",
"if",
"!",
"ok",
"{",
"return",
"nil",
",",
"ErrConnectionClosed",
"\n",
"}",
"\n",
"case",
"<-",
"ctx",
".",
"Done",
"(",
")",
":",
"nc",
".",
"mu",
".",
"Lock",
"(",
")",
"\n",
"delete",
"(",
"nc",
".",
"respMap",
",",
"token",
")",
"\n",
"nc",
".",
"mu",
".",
"Unlock",
"(",
")",
"\n",
"return",
"nil",
",",
"ctx",
".",
"Err",
"(",
")",
"\n",
"}",
"\n",
"return",
"msg",
",",
"nil",
"\n",
"}"
] | // RequestWithContext takes a context, a subject and payload
// in bytes and request expecting a single response. | [
"RequestWithContext",
"takes",
"a",
"context",
"a",
"subject",
"and",
"payload",
"in",
"bytes",
"and",
"request",
"expecting",
"a",
"single",
"response",
"."
] | 36d30b0ba7aa260ae25b4f3d312b2a700106fd78 | https://github.com/nats-io/go-nats/blob/36d30b0ba7aa260ae25b4f3d312b2a700106fd78/context.go#L26-L89 | train |
nats-io/go-nats | context.go | oldRequestWithContext | func (nc *Conn) oldRequestWithContext(ctx context.Context, subj string, data []byte) (*Msg, error) {
inbox := NewInbox()
ch := make(chan *Msg, RequestChanLen)
s, err := nc.subscribe(inbox, _EMPTY_, nil, ch, true)
if err != nil {
return nil, err
}
s.AutoUnsubscribe(1)
defer s.Unsubscribe()
err = nc.PublishRequest(subj, inbox, data)
if err != nil {
return nil, err
}
return s.NextMsgWithContext(ctx)
} | go | func (nc *Conn) oldRequestWithContext(ctx context.Context, subj string, data []byte) (*Msg, error) {
inbox := NewInbox()
ch := make(chan *Msg, RequestChanLen)
s, err := nc.subscribe(inbox, _EMPTY_, nil, ch, true)
if err != nil {
return nil, err
}
s.AutoUnsubscribe(1)
defer s.Unsubscribe()
err = nc.PublishRequest(subj, inbox, data)
if err != nil {
return nil, err
}
return s.NextMsgWithContext(ctx)
} | [
"func",
"(",
"nc",
"*",
"Conn",
")",
"oldRequestWithContext",
"(",
"ctx",
"context",
".",
"Context",
",",
"subj",
"string",
",",
"data",
"[",
"]",
"byte",
")",
"(",
"*",
"Msg",
",",
"error",
")",
"{",
"inbox",
":=",
"NewInbox",
"(",
")",
"\n",
"ch",
":=",
"make",
"(",
"chan",
"*",
"Msg",
",",
"RequestChanLen",
")",
"\n",
"s",
",",
"err",
":=",
"nc",
".",
"subscribe",
"(",
"inbox",
",",
"_EMPTY_",
",",
"nil",
",",
"ch",
",",
"true",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"s",
".",
"AutoUnsubscribe",
"(",
"1",
")",
"\n",
"defer",
"s",
".",
"Unsubscribe",
"(",
")",
"\n",
"err",
"=",
"nc",
".",
"PublishRequest",
"(",
"subj",
",",
"inbox",
",",
"data",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"return",
"s",
".",
"NextMsgWithContext",
"(",
"ctx",
")",
"\n",
"}"
] | // oldRequestWithContext utilizes inbox and subscription per request. | [
"oldRequestWithContext",
"utilizes",
"inbox",
"and",
"subscription",
"per",
"request",
"."
] | 36d30b0ba7aa260ae25b4f3d312b2a700106fd78 | https://github.com/nats-io/go-nats/blob/36d30b0ba7aa260ae25b4f3d312b2a700106fd78/context.go#L92-L109 | train |
nats-io/go-nats | context.go | NextMsgWithContext | func (s *Subscription) NextMsgWithContext(ctx context.Context) (*Msg, error) {
if ctx == nil {
return nil, ErrInvalidContext
}
if s == nil {
return nil, ErrBadSubscription
}
if ctx.Err() != nil {
return nil, ctx.Err()
}
s.mu.Lock()
err := s.validateNextMsgState()
if err != nil {
s.mu.Unlock()
return nil, err
}
// snapshot
mch := s.mch
s.mu.Unlock()
var ok bool
var msg *Msg
// If something is available right away, let's optimize that case.
select {
case msg, ok = <-mch:
if !ok {
return nil, ErrConnectionClosed
}
if err := s.processNextMsgDelivered(msg); err != nil {
return nil, err
} else {
return msg, nil
}
default:
}
select {
case msg, ok = <-mch:
if !ok {
return nil, ErrConnectionClosed
}
if err := s.processNextMsgDelivered(msg); err != nil {
return nil, err
}
case <-ctx.Done():
return nil, ctx.Err()
}
return msg, nil
} | go | func (s *Subscription) NextMsgWithContext(ctx context.Context) (*Msg, error) {
if ctx == nil {
return nil, ErrInvalidContext
}
if s == nil {
return nil, ErrBadSubscription
}
if ctx.Err() != nil {
return nil, ctx.Err()
}
s.mu.Lock()
err := s.validateNextMsgState()
if err != nil {
s.mu.Unlock()
return nil, err
}
// snapshot
mch := s.mch
s.mu.Unlock()
var ok bool
var msg *Msg
// If something is available right away, let's optimize that case.
select {
case msg, ok = <-mch:
if !ok {
return nil, ErrConnectionClosed
}
if err := s.processNextMsgDelivered(msg); err != nil {
return nil, err
} else {
return msg, nil
}
default:
}
select {
case msg, ok = <-mch:
if !ok {
return nil, ErrConnectionClosed
}
if err := s.processNextMsgDelivered(msg); err != nil {
return nil, err
}
case <-ctx.Done():
return nil, ctx.Err()
}
return msg, nil
} | [
"func",
"(",
"s",
"*",
"Subscription",
")",
"NextMsgWithContext",
"(",
"ctx",
"context",
".",
"Context",
")",
"(",
"*",
"Msg",
",",
"error",
")",
"{",
"if",
"ctx",
"==",
"nil",
"{",
"return",
"nil",
",",
"ErrInvalidContext",
"\n",
"}",
"\n",
"if",
"s",
"==",
"nil",
"{",
"return",
"nil",
",",
"ErrBadSubscription",
"\n",
"}",
"\n",
"if",
"ctx",
".",
"Err",
"(",
")",
"!=",
"nil",
"{",
"return",
"nil",
",",
"ctx",
".",
"Err",
"(",
")",
"\n",
"}",
"\n",
"s",
".",
"mu",
".",
"Lock",
"(",
")",
"\n",
"err",
":=",
"s",
".",
"validateNextMsgState",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"s",
".",
"mu",
".",
"Unlock",
"(",
")",
"\n",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"mch",
":=",
"s",
".",
"mch",
"\n",
"s",
".",
"mu",
".",
"Unlock",
"(",
")",
"\n",
"var",
"ok",
"bool",
"\n",
"var",
"msg",
"*",
"Msg",
"\n",
"select",
"{",
"case",
"msg",
",",
"ok",
"=",
"<-",
"mch",
":",
"if",
"!",
"ok",
"{",
"return",
"nil",
",",
"ErrConnectionClosed",
"\n",
"}",
"\n",
"if",
"err",
":=",
"s",
".",
"processNextMsgDelivered",
"(",
"msg",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"else",
"{",
"return",
"msg",
",",
"nil",
"\n",
"}",
"\n",
"default",
":",
"}",
"\n",
"select",
"{",
"case",
"msg",
",",
"ok",
"=",
"<-",
"mch",
":",
"if",
"!",
"ok",
"{",
"return",
"nil",
",",
"ErrConnectionClosed",
"\n",
"}",
"\n",
"if",
"err",
":=",
"s",
".",
"processNextMsgDelivered",
"(",
"msg",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"case",
"<-",
"ctx",
".",
"Done",
"(",
")",
":",
"return",
"nil",
",",
"ctx",
".",
"Err",
"(",
")",
"\n",
"}",
"\n",
"return",
"msg",
",",
"nil",
"\n",
"}"
] | // NextMsgWithContext takes a context and returns the next message
// available to a synchronous subscriber, blocking until it is delivered
// or context gets canceled. | [
"NextMsgWithContext",
"takes",
"a",
"context",
"and",
"returns",
"the",
"next",
"message",
"available",
"to",
"a",
"synchronous",
"subscriber",
"blocking",
"until",
"it",
"is",
"delivered",
"or",
"context",
"gets",
"canceled",
"."
] | 36d30b0ba7aa260ae25b4f3d312b2a700106fd78 | https://github.com/nats-io/go-nats/blob/36d30b0ba7aa260ae25b4f3d312b2a700106fd78/context.go#L114-L166 | train |
nats-io/go-nats | context.go | RequestWithContext | func (c *EncodedConn) RequestWithContext(ctx context.Context, subject string, v interface{}, vPtr interface{}) error {
if ctx == nil {
return ErrInvalidContext
}
b, err := c.Enc.Encode(subject, v)
if err != nil {
return err
}
m, err := c.Conn.RequestWithContext(ctx, subject, b)
if err != nil {
return err
}
if reflect.TypeOf(vPtr) == emptyMsgType {
mPtr := vPtr.(*Msg)
*mPtr = *m
} else {
err := c.Enc.Decode(m.Subject, m.Data, vPtr)
if err != nil {
return err
}
}
return nil
} | go | func (c *EncodedConn) RequestWithContext(ctx context.Context, subject string, v interface{}, vPtr interface{}) error {
if ctx == nil {
return ErrInvalidContext
}
b, err := c.Enc.Encode(subject, v)
if err != nil {
return err
}
m, err := c.Conn.RequestWithContext(ctx, subject, b)
if err != nil {
return err
}
if reflect.TypeOf(vPtr) == emptyMsgType {
mPtr := vPtr.(*Msg)
*mPtr = *m
} else {
err := c.Enc.Decode(m.Subject, m.Data, vPtr)
if err != nil {
return err
}
}
return nil
} | [
"func",
"(",
"c",
"*",
"EncodedConn",
")",
"RequestWithContext",
"(",
"ctx",
"context",
".",
"Context",
",",
"subject",
"string",
",",
"v",
"interface",
"{",
"}",
",",
"vPtr",
"interface",
"{",
"}",
")",
"error",
"{",
"if",
"ctx",
"==",
"nil",
"{",
"return",
"ErrInvalidContext",
"\n",
"}",
"\n",
"b",
",",
"err",
":=",
"c",
".",
"Enc",
".",
"Encode",
"(",
"subject",
",",
"v",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"m",
",",
"err",
":=",
"c",
".",
"Conn",
".",
"RequestWithContext",
"(",
"ctx",
",",
"subject",
",",
"b",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"if",
"reflect",
".",
"TypeOf",
"(",
"vPtr",
")",
"==",
"emptyMsgType",
"{",
"mPtr",
":=",
"vPtr",
".",
"(",
"*",
"Msg",
")",
"\n",
"*",
"mPtr",
"=",
"*",
"m",
"\n",
"}",
"else",
"{",
"err",
":=",
"c",
".",
"Enc",
".",
"Decode",
"(",
"m",
".",
"Subject",
",",
"m",
".",
"Data",
",",
"vPtr",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}"
] | // RequestWithContext will create an Inbox and perform a Request
// using the provided cancellation context with the Inbox reply
// for the data v. A response will be decoded into the vPtrResponse. | [
"RequestWithContext",
"will",
"create",
"an",
"Inbox",
"and",
"perform",
"a",
"Request",
"using",
"the",
"provided",
"cancellation",
"context",
"with",
"the",
"Inbox",
"reply",
"for",
"the",
"data",
"v",
".",
"A",
"response",
"will",
"be",
"decoded",
"into",
"the",
"vPtrResponse",
"."
] | 36d30b0ba7aa260ae25b4f3d312b2a700106fd78 | https://github.com/nats-io/go-nats/blob/36d30b0ba7aa260ae25b4f3d312b2a700106fd78/context.go#L217-L241 | train |
nats-io/go-nats | netchan.go | BindSendChan | func (c *EncodedConn) BindSendChan(subject string, channel interface{}) error {
chVal := reflect.ValueOf(channel)
if chVal.Kind() != reflect.Chan {
return ErrChanArg
}
go chPublish(c, chVal, subject)
return nil
} | go | func (c *EncodedConn) BindSendChan(subject string, channel interface{}) error {
chVal := reflect.ValueOf(channel)
if chVal.Kind() != reflect.Chan {
return ErrChanArg
}
go chPublish(c, chVal, subject)
return nil
} | [
"func",
"(",
"c",
"*",
"EncodedConn",
")",
"BindSendChan",
"(",
"subject",
"string",
",",
"channel",
"interface",
"{",
"}",
")",
"error",
"{",
"chVal",
":=",
"reflect",
".",
"ValueOf",
"(",
"channel",
")",
"\n",
"if",
"chVal",
".",
"Kind",
"(",
")",
"!=",
"reflect",
".",
"Chan",
"{",
"return",
"ErrChanArg",
"\n",
"}",
"\n",
"go",
"chPublish",
"(",
"c",
",",
"chVal",
",",
"subject",
")",
"\n",
"return",
"nil",
"\n",
"}"
] | // This allows the functionality for network channels by binding send and receive Go chans
// to subjects and optionally queue groups.
// Data will be encoded and decoded via the EncodedConn and its associated encoders.
// BindSendChan binds a channel for send operations to NATS. | [
"This",
"allows",
"the",
"functionality",
"for",
"network",
"channels",
"by",
"binding",
"send",
"and",
"receive",
"Go",
"chans",
"to",
"subjects",
"and",
"optionally",
"queue",
"groups",
".",
"Data",
"will",
"be",
"encoded",
"and",
"decoded",
"via",
"the",
"EncodedConn",
"and",
"its",
"associated",
"encoders",
".",
"BindSendChan",
"binds",
"a",
"channel",
"for",
"send",
"operations",
"to",
"NATS",
"."
] | 36d30b0ba7aa260ae25b4f3d312b2a700106fd78 | https://github.com/nats-io/go-nats/blob/36d30b0ba7aa260ae25b4f3d312b2a700106fd78/netchan.go#L26-L33 | train |
nats-io/go-nats | netchan.go | chPublish | func chPublish(c *EncodedConn, chVal reflect.Value, subject string) {
for {
val, ok := chVal.Recv()
if !ok {
// Channel has most likely been closed.
return
}
if e := c.Publish(subject, val.Interface()); e != nil {
// Do this under lock.
c.Conn.mu.Lock()
defer c.Conn.mu.Unlock()
if c.Conn.Opts.AsyncErrorCB != nil {
// FIXME(dlc) - Not sure this is the right thing to do.
// FIXME(ivan) - If the connection is not yet closed, try to schedule the callback
if c.Conn.isClosed() {
go c.Conn.Opts.AsyncErrorCB(c.Conn, nil, e)
} else {
c.Conn.ach.push(func() { c.Conn.Opts.AsyncErrorCB(c.Conn, nil, e) })
}
}
return
}
}
} | go | func chPublish(c *EncodedConn, chVal reflect.Value, subject string) {
for {
val, ok := chVal.Recv()
if !ok {
// Channel has most likely been closed.
return
}
if e := c.Publish(subject, val.Interface()); e != nil {
// Do this under lock.
c.Conn.mu.Lock()
defer c.Conn.mu.Unlock()
if c.Conn.Opts.AsyncErrorCB != nil {
// FIXME(dlc) - Not sure this is the right thing to do.
// FIXME(ivan) - If the connection is not yet closed, try to schedule the callback
if c.Conn.isClosed() {
go c.Conn.Opts.AsyncErrorCB(c.Conn, nil, e)
} else {
c.Conn.ach.push(func() { c.Conn.Opts.AsyncErrorCB(c.Conn, nil, e) })
}
}
return
}
}
} | [
"func",
"chPublish",
"(",
"c",
"*",
"EncodedConn",
",",
"chVal",
"reflect",
".",
"Value",
",",
"subject",
"string",
")",
"{",
"for",
"{",
"val",
",",
"ok",
":=",
"chVal",
".",
"Recv",
"(",
")",
"\n",
"if",
"!",
"ok",
"{",
"return",
"\n",
"}",
"\n",
"if",
"e",
":=",
"c",
".",
"Publish",
"(",
"subject",
",",
"val",
".",
"Interface",
"(",
")",
")",
";",
"e",
"!=",
"nil",
"{",
"c",
".",
"Conn",
".",
"mu",
".",
"Lock",
"(",
")",
"\n",
"defer",
"c",
".",
"Conn",
".",
"mu",
".",
"Unlock",
"(",
")",
"\n",
"if",
"c",
".",
"Conn",
".",
"Opts",
".",
"AsyncErrorCB",
"!=",
"nil",
"{",
"if",
"c",
".",
"Conn",
".",
"isClosed",
"(",
")",
"{",
"go",
"c",
".",
"Conn",
".",
"Opts",
".",
"AsyncErrorCB",
"(",
"c",
".",
"Conn",
",",
"nil",
",",
"e",
")",
"\n",
"}",
"else",
"{",
"c",
".",
"Conn",
".",
"ach",
".",
"push",
"(",
"func",
"(",
")",
"{",
"c",
".",
"Conn",
".",
"Opts",
".",
"AsyncErrorCB",
"(",
"c",
".",
"Conn",
",",
"nil",
",",
"e",
")",
"}",
")",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"\n",
"}",
"\n",
"}",
"\n",
"}"
] | // Publish all values that arrive on the channel until it is closed or we
// encounter an error. | [
"Publish",
"all",
"values",
"that",
"arrive",
"on",
"the",
"channel",
"until",
"it",
"is",
"closed",
"or",
"we",
"encounter",
"an",
"error",
"."
] | 36d30b0ba7aa260ae25b4f3d312b2a700106fd78 | https://github.com/nats-io/go-nats/blob/36d30b0ba7aa260ae25b4f3d312b2a700106fd78/netchan.go#L37-L61 | train |
nats-io/go-nats | netchan.go | BindRecvChan | func (c *EncodedConn) BindRecvChan(subject string, channel interface{}) (*Subscription, error) {
return c.bindRecvChan(subject, _EMPTY_, channel)
} | go | func (c *EncodedConn) BindRecvChan(subject string, channel interface{}) (*Subscription, error) {
return c.bindRecvChan(subject, _EMPTY_, channel)
} | [
"func",
"(",
"c",
"*",
"EncodedConn",
")",
"BindRecvChan",
"(",
"subject",
"string",
",",
"channel",
"interface",
"{",
"}",
")",
"(",
"*",
"Subscription",
",",
"error",
")",
"{",
"return",
"c",
".",
"bindRecvChan",
"(",
"subject",
",",
"_EMPTY_",
",",
"channel",
")",
"\n",
"}"
] | // BindRecvChan binds a channel for receive operations from NATS. | [
"BindRecvChan",
"binds",
"a",
"channel",
"for",
"receive",
"operations",
"from",
"NATS",
"."
] | 36d30b0ba7aa260ae25b4f3d312b2a700106fd78 | https://github.com/nats-io/go-nats/blob/36d30b0ba7aa260ae25b4f3d312b2a700106fd78/netchan.go#L64-L66 | train |
nats-io/go-nats | netchan.go | BindRecvQueueChan | func (c *EncodedConn) BindRecvQueueChan(subject, queue string, channel interface{}) (*Subscription, error) {
return c.bindRecvChan(subject, queue, channel)
} | go | func (c *EncodedConn) BindRecvQueueChan(subject, queue string, channel interface{}) (*Subscription, error) {
return c.bindRecvChan(subject, queue, channel)
} | [
"func",
"(",
"c",
"*",
"EncodedConn",
")",
"BindRecvQueueChan",
"(",
"subject",
",",
"queue",
"string",
",",
"channel",
"interface",
"{",
"}",
")",
"(",
"*",
"Subscription",
",",
"error",
")",
"{",
"return",
"c",
".",
"bindRecvChan",
"(",
"subject",
",",
"queue",
",",
"channel",
")",
"\n",
"}"
] | // BindRecvQueueChan binds a channel for queue-based receive operations from NATS. | [
"BindRecvQueueChan",
"binds",
"a",
"channel",
"for",
"queue",
"-",
"based",
"receive",
"operations",
"from",
"NATS",
"."
] | 36d30b0ba7aa260ae25b4f3d312b2a700106fd78 | https://github.com/nats-io/go-nats/blob/36d30b0ba7aa260ae25b4f3d312b2a700106fd78/netchan.go#L69-L71 | train |
nats-io/go-nats | netchan.go | bindRecvChan | func (c *EncodedConn) bindRecvChan(subject, queue string, channel interface{}) (*Subscription, error) {
chVal := reflect.ValueOf(channel)
if chVal.Kind() != reflect.Chan {
return nil, ErrChanArg
}
argType := chVal.Type().Elem()
cb := func(m *Msg) {
var oPtr reflect.Value
if argType.Kind() != reflect.Ptr {
oPtr = reflect.New(argType)
} else {
oPtr = reflect.New(argType.Elem())
}
if err := c.Enc.Decode(m.Subject, m.Data, oPtr.Interface()); err != nil {
c.Conn.err = errors.New("nats: Got an error trying to unmarshal: " + err.Error())
if c.Conn.Opts.AsyncErrorCB != nil {
c.Conn.ach.push(func() { c.Conn.Opts.AsyncErrorCB(c.Conn, m.Sub, c.Conn.err) })
}
return
}
if argType.Kind() != reflect.Ptr {
oPtr = reflect.Indirect(oPtr)
}
// This is a bit hacky, but in this instance we may be trying to send to a closed channel.
// and the user does not know when it is safe to close the channel.
defer func() {
// If we have panicked, recover and close the subscription.
if r := recover(); r != nil {
m.Sub.Unsubscribe()
}
}()
// Actually do the send to the channel.
chVal.Send(oPtr)
}
return c.Conn.subscribe(subject, queue, cb, nil, false)
} | go | func (c *EncodedConn) bindRecvChan(subject, queue string, channel interface{}) (*Subscription, error) {
chVal := reflect.ValueOf(channel)
if chVal.Kind() != reflect.Chan {
return nil, ErrChanArg
}
argType := chVal.Type().Elem()
cb := func(m *Msg) {
var oPtr reflect.Value
if argType.Kind() != reflect.Ptr {
oPtr = reflect.New(argType)
} else {
oPtr = reflect.New(argType.Elem())
}
if err := c.Enc.Decode(m.Subject, m.Data, oPtr.Interface()); err != nil {
c.Conn.err = errors.New("nats: Got an error trying to unmarshal: " + err.Error())
if c.Conn.Opts.AsyncErrorCB != nil {
c.Conn.ach.push(func() { c.Conn.Opts.AsyncErrorCB(c.Conn, m.Sub, c.Conn.err) })
}
return
}
if argType.Kind() != reflect.Ptr {
oPtr = reflect.Indirect(oPtr)
}
// This is a bit hacky, but in this instance we may be trying to send to a closed channel.
// and the user does not know when it is safe to close the channel.
defer func() {
// If we have panicked, recover and close the subscription.
if r := recover(); r != nil {
m.Sub.Unsubscribe()
}
}()
// Actually do the send to the channel.
chVal.Send(oPtr)
}
return c.Conn.subscribe(subject, queue, cb, nil, false)
} | [
"func",
"(",
"c",
"*",
"EncodedConn",
")",
"bindRecvChan",
"(",
"subject",
",",
"queue",
"string",
",",
"channel",
"interface",
"{",
"}",
")",
"(",
"*",
"Subscription",
",",
"error",
")",
"{",
"chVal",
":=",
"reflect",
".",
"ValueOf",
"(",
"channel",
")",
"\n",
"if",
"chVal",
".",
"Kind",
"(",
")",
"!=",
"reflect",
".",
"Chan",
"{",
"return",
"nil",
",",
"ErrChanArg",
"\n",
"}",
"\n",
"argType",
":=",
"chVal",
".",
"Type",
"(",
")",
".",
"Elem",
"(",
")",
"\n",
"cb",
":=",
"func",
"(",
"m",
"*",
"Msg",
")",
"{",
"var",
"oPtr",
"reflect",
".",
"Value",
"\n",
"if",
"argType",
".",
"Kind",
"(",
")",
"!=",
"reflect",
".",
"Ptr",
"{",
"oPtr",
"=",
"reflect",
".",
"New",
"(",
"argType",
")",
"\n",
"}",
"else",
"{",
"oPtr",
"=",
"reflect",
".",
"New",
"(",
"argType",
".",
"Elem",
"(",
")",
")",
"\n",
"}",
"\n",
"if",
"err",
":=",
"c",
".",
"Enc",
".",
"Decode",
"(",
"m",
".",
"Subject",
",",
"m",
".",
"Data",
",",
"oPtr",
".",
"Interface",
"(",
")",
")",
";",
"err",
"!=",
"nil",
"{",
"c",
".",
"Conn",
".",
"err",
"=",
"errors",
".",
"New",
"(",
"\"nats: Got an error trying to unmarshal: \"",
"+",
"err",
".",
"Error",
"(",
")",
")",
"\n",
"if",
"c",
".",
"Conn",
".",
"Opts",
".",
"AsyncErrorCB",
"!=",
"nil",
"{",
"c",
".",
"Conn",
".",
"ach",
".",
"push",
"(",
"func",
"(",
")",
"{",
"c",
".",
"Conn",
".",
"Opts",
".",
"AsyncErrorCB",
"(",
"c",
".",
"Conn",
",",
"m",
".",
"Sub",
",",
"c",
".",
"Conn",
".",
"err",
")",
"}",
")",
"\n",
"}",
"\n",
"return",
"\n",
"}",
"\n",
"if",
"argType",
".",
"Kind",
"(",
")",
"!=",
"reflect",
".",
"Ptr",
"{",
"oPtr",
"=",
"reflect",
".",
"Indirect",
"(",
"oPtr",
")",
"\n",
"}",
"\n",
"defer",
"func",
"(",
")",
"{",
"if",
"r",
":=",
"recover",
"(",
")",
";",
"r",
"!=",
"nil",
"{",
"m",
".",
"Sub",
".",
"Unsubscribe",
"(",
")",
"\n",
"}",
"\n",
"}",
"(",
")",
"\n",
"chVal",
".",
"Send",
"(",
"oPtr",
")",
"\n",
"}",
"\n",
"return",
"c",
".",
"Conn",
".",
"subscribe",
"(",
"subject",
",",
"queue",
",",
"cb",
",",
"nil",
",",
"false",
")",
"\n",
"}"
] | // Internal function to bind receive operations for a channel. | [
"Internal",
"function",
"to",
"bind",
"receive",
"operations",
"for",
"a",
"channel",
"."
] | 36d30b0ba7aa260ae25b4f3d312b2a700106fd78 | https://github.com/nats-io/go-nats/blob/36d30b0ba7aa260ae25b4f3d312b2a700106fd78/netchan.go#L74-L111 | train |
nats-io/go-nats | examples/nats-echo/main.go | lookupGeo | func lookupGeo() string {
c := &http.Client{Timeout: 2 * time.Second}
resp, err := c.Get("https://ipinfo.io")
if err != nil || resp == nil {
log.Fatalf("Could not retrive geo location data: %v", err)
}
defer resp.Body.Close()
body, _ := ioutil.ReadAll(resp.Body)
g := geo{}
if err := json.Unmarshal(body, &g); err != nil {
log.Fatalf("Error unmarshalling geo: %v", err)
}
return g.Region + ", " + g.Country
} | go | func lookupGeo() string {
c := &http.Client{Timeout: 2 * time.Second}
resp, err := c.Get("https://ipinfo.io")
if err != nil || resp == nil {
log.Fatalf("Could not retrive geo location data: %v", err)
}
defer resp.Body.Close()
body, _ := ioutil.ReadAll(resp.Body)
g := geo{}
if err := json.Unmarshal(body, &g); err != nil {
log.Fatalf("Error unmarshalling geo: %v", err)
}
return g.Region + ", " + g.Country
} | [
"func",
"lookupGeo",
"(",
")",
"string",
"{",
"c",
":=",
"&",
"http",
".",
"Client",
"{",
"Timeout",
":",
"2",
"*",
"time",
".",
"Second",
"}",
"\n",
"resp",
",",
"err",
":=",
"c",
".",
"Get",
"(",
"\"https://ipinfo.io\"",
")",
"\n",
"if",
"err",
"!=",
"nil",
"||",
"resp",
"==",
"nil",
"{",
"log",
".",
"Fatalf",
"(",
"\"Could not retrive geo location data: %v\"",
",",
"err",
")",
"\n",
"}",
"\n",
"defer",
"resp",
".",
"Body",
".",
"Close",
"(",
")",
"\n",
"body",
",",
"_",
":=",
"ioutil",
".",
"ReadAll",
"(",
"resp",
".",
"Body",
")",
"\n",
"g",
":=",
"geo",
"{",
"}",
"\n",
"if",
"err",
":=",
"json",
".",
"Unmarshal",
"(",
"body",
",",
"&",
"g",
")",
";",
"err",
"!=",
"nil",
"{",
"log",
".",
"Fatalf",
"(",
"\"Error unmarshalling geo: %v\"",
",",
"err",
")",
"\n",
"}",
"\n",
"return",
"g",
".",
"Region",
"+",
"\", \"",
"+",
"g",
".",
"Country",
"\n",
"}"
] | // lookup our current region and country.. | [
"lookup",
"our",
"current",
"region",
"and",
"country",
".."
] | 36d30b0ba7aa260ae25b4f3d312b2a700106fd78 | https://github.com/nats-io/go-nats/blob/36d30b0ba7aa260ae25b4f3d312b2a700106fd78/examples/nats-echo/main.go#L153-L166 | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.