repo
stringlengths 5
54
| path
stringlengths 4
155
| func_name
stringlengths 1
118
| original_string
stringlengths 52
85.5k
| language
stringclasses 1
value | code
stringlengths 52
85.5k
| code_tokens
sequence | docstring
stringlengths 6
2.61k
| docstring_tokens
sequence | sha
stringlengths 40
40
| url
stringlengths 85
252
| partition
stringclasses 1
value |
---|---|---|---|---|---|---|---|---|---|---|---|
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\n",
"// Read the protocol",
"err",
":=",
"nc",
".",
"readOp",
"(",
"c",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n\n",
"// The nats protocol should send INFO first always.",
"if",
"c",
".",
"op",
"!=",
"_INFO_OP_",
"{",
"return",
"ErrNoInfoReceived",
"\n",
"}",
"\n\n",
"// Parse the protocol",
"if",
"err",
":=",
"nc",
".",
"processInfo",
"(",
"c",
".",
"args",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n\n",
"if",
"nc",
".",
"Opts",
".",
"Nkey",
"!=",
"\"",
"\"",
"&&",
"nc",
".",
"info",
".",
"Nonce",
"==",
"\"",
"\"",
"{",
"return",
"ErrNkeysNotSupported",
"\n",
"}",
"\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",
"{",
"// Do not report EOF error",
"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",
"(",
")",
"{",
"// We want to make sure we have the other watchers shutdown properly",
"// here before we proceed past this point.",
"nc",
".",
"waitForExits",
"(",
")",
"\n\n",
"// 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",
"(",
")",
"\n\n",
"// Clear any queued pongs, e.g. pending flush calls.",
"nc",
".",
"clearPendingFlushCalls",
"(",
")",
"\n\n",
"// Clear any errors.",
"nc",
".",
"err",
"=",
"nil",
"\n",
"// Perform appropriate callback if needed for a disconnect.",
"if",
"nc",
".",
"Opts",
".",
"DisconnectedCB",
"!=",
"nil",
"{",
"nc",
".",
"ach",
".",
"push",
"(",
"func",
"(",
")",
"{",
"nc",
".",
"Opts",
".",
"DisconnectedCB",
"(",
"nc",
")",
"}",
")",
"\n",
"}",
"\n\n",
"// This is used to wait on go routines exit if we start them in the loop",
"// but an error occurs after that.",
"waitForGoRoutines",
":=",
"false",
"\n\n",
"for",
"len",
"(",
"nc",
".",
"srvPool",
")",
">",
"0",
"{",
"cur",
",",
"err",
":=",
"nc",
".",
"selectNextServer",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"nc",
".",
"err",
"=",
"err",
"\n",
"break",
"\n",
"}",
"\n\n",
"sleepTime",
":=",
"int64",
"(",
"0",
")",
"\n\n",
"// 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",
")",
")",
"\n",
"}",
"\n\n",
"// 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",
"(",
")",
"\n",
"if",
"sleepTime",
"<=",
"0",
"{",
"runtime",
".",
"Gosched",
"(",
")",
"\n",
"}",
"else",
"{",
"time",
".",
"Sleep",
"(",
"time",
".",
"Duration",
"(",
"sleepTime",
")",
")",
"\n",
"}",
"\n",
"// If the readLoop, etc.. go routines were started, wait for them to complete.",
"if",
"waitForGoRoutines",
"{",
"nc",
".",
"waitForExits",
"(",
")",
"\n",
"waitForGoRoutines",
"=",
"false",
"\n",
"}",
"\n",
"nc",
".",
"mu",
".",
"Lock",
"(",
")",
"\n\n",
"// Check if we have been closed first.",
"if",
"nc",
".",
"isClosed",
"(",
")",
"{",
"break",
"\n",
"}",
"\n\n",
"// Mark that we tried a reconnect",
"cur",
".",
"reconnects",
"++",
"\n\n",
"// Try to create a new connection",
"err",
"=",
"nc",
".",
"createConn",
"(",
")",
"\n\n",
"// Not yet connected, retry...",
"// Continue to hold the lock",
"if",
"err",
"!=",
"nil",
"{",
"nc",
".",
"err",
"=",
"nil",
"\n",
"continue",
"\n",
"}",
"\n\n",
"// We are reconnected",
"nc",
".",
"Reconnects",
"++",
"\n\n",
"// Process connect logic",
"if",
"nc",
".",
"err",
"=",
"nc",
".",
"processConnectInit",
"(",
")",
";",
"nc",
".",
"err",
"!=",
"nil",
"{",
"nc",
".",
"status",
"=",
"RECONNECTING",
"\n",
"// Reset the buffered writer to the pending buffer",
"// (was set to a buffered writer on nc.conn in createConn)",
"nc",
".",
"bw",
".",
"Reset",
"(",
"nc",
".",
"pending",
")",
"\n",
"continue",
"\n",
"}",
"\n\n",
"// Clear out server stats for the server we connected to..",
"cur",
".",
"didConnect",
"=",
"true",
"\n",
"cur",
".",
"reconnects",
"=",
"0",
"\n\n",
"// Send existing subscription state",
"nc",
".",
"resendSubscriptions",
"(",
")",
"\n\n",
"// Now send off and clear pending buffer",
"nc",
".",
"flushReconnectPendingItems",
"(",
")",
"\n\n",
"// Flush the buffer",
"nc",
".",
"err",
"=",
"nc",
".",
"bw",
".",
"Flush",
"(",
")",
"\n",
"if",
"nc",
".",
"err",
"!=",
"nil",
"{",
"nc",
".",
"status",
"=",
"RECONNECTING",
"\n",
"// Reset the buffered writer to the pending buffer (bytes.Buffer).",
"nc",
".",
"bw",
".",
"Reset",
"(",
"nc",
".",
"pending",
")",
"\n",
"// Stop the ping timer (if set)",
"nc",
".",
"stopPingTimer",
"(",
")",
"\n",
"// 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",
"\n",
"continue",
"\n",
"}",
"\n\n",
"// Done with the pending buffer",
"nc",
".",
"pending",
"=",
"nil",
"\n\n",
"// This is where we are truly connected.",
"nc",
".",
"status",
"=",
"CONNECTED",
"\n\n",
"// Queue up the reconnect callback.",
"if",
"nc",
".",
"Opts",
".",
"ReconnectedCB",
"!=",
"nil",
"{",
"nc",
".",
"ach",
".",
"push",
"(",
"func",
"(",
")",
"{",
"nc",
".",
"Opts",
".",
"ReconnectedCB",
"(",
"nc",
")",
"}",
")",
"\n",
"}",
"\n",
"// Release lock here, we will return below.",
"nc",
".",
"mu",
".",
"Unlock",
"(",
")",
"\n\n",
"// Make sure to flush everything",
"nc",
".",
"Flush",
"(",
")",
"\n\n",
"return",
"\n",
"}",
"\n\n",
"// Call into close.. We have no servers left..",
"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\n",
"if",
"nc",
".",
"Opts",
".",
"AllowReconnect",
"&&",
"nc",
".",
"status",
"==",
"CONNECTED",
"{",
"// Set our new status",
"nc",
".",
"status",
"=",
"RECONNECTING",
"\n",
"// Stop ping timer if set",
"nc",
".",
"stopPingTimer",
"(",
")",
"\n",
"if",
"nc",
".",
"conn",
"!=",
"nil",
"{",
"nc",
".",
"bw",
".",
"Flush",
"(",
")",
"\n",
"nc",
".",
"conn",
".",
"Close",
"(",
")",
"\n",
"nc",
".",
"conn",
"=",
"nil",
"\n",
"}",
"\n\n",
"// Create pending buffer before reconnecting.",
"nc",
".",
"pending",
"=",
"new",
"(",
"bytes",
".",
"Buffer",
")",
"\n",
"nc",
".",
"bw",
".",
"Reset",
"(",
"nc",
".",
"pending",
")",
"\n\n",
"go",
"nc",
".",
"doReconnect",
"(",
")",
"\n",
"nc",
".",
"mu",
".",
"Unlock",
"(",
")",
"\n",
"return",
"\n",
"}",
"\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",
"// 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",
"(",
")",
"\n",
"}",
"\n",
"cur",
":=",
"ac",
".",
"head",
"\n",
"ac",
".",
"head",
"=",
"cur",
".",
"next",
"\n",
"if",
"cur",
"==",
"ac",
".",
"tail",
"{",
"ac",
".",
"tail",
"=",
"nil",
"\n",
"}",
"\n",
"ac",
".",
"mu",
".",
"Unlock",
"(",
")",
"\n\n",
"// This signals that the dispatcher has been closed and all",
"// previous callbacks have been dispatched.",
"if",
"cur",
".",
"f",
"==",
"nil",
"{",
"return",
"\n",
"}",
"\n",
"// Invoke callback outside of handler's lock",
"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",
"// 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",
"(",
"\"",
"\"",
")",
"\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\n",
"// Used to account for adjustments to sub.pBytes when we wrap back around.",
"msgLen",
":=",
"-",
"1",
"\n\n",
"for",
"{",
"s",
".",
"mu",
".",
"Lock",
"(",
")",
"\n",
"// 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",
"--",
"\n",
"s",
".",
"pBytes",
"-=",
"msgLen",
"\n",
"msgLen",
"=",
"-",
"1",
"\n",
"}",
"\n\n",
"if",
"s",
".",
"pHead",
"==",
"nil",
"&&",
"!",
"s",
".",
"closed",
"{",
"s",
".",
"pCond",
".",
"Wait",
"(",
")",
"\n",
"}",
"\n",
"// Pop the msg off the list",
"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\n",
"if",
"closed",
"{",
"break",
"\n",
"}",
"\n\n",
"// Deliver the message.",
"if",
"m",
"!=",
"nil",
"&&",
"(",
"max",
"==",
"0",
"||",
"delivered",
"<=",
"max",
")",
"{",
"mcb",
"(",
"m",
")",
"\n",
"}",
"\n",
"// If we have hit the max for delivered msgs, remove sub.",
"if",
"max",
">",
"0",
"&&",
"delivered",
">=",
"max",
"{",
"nc",
".",
"mu",
".",
"Lock",
"(",
")",
"\n",
"nc",
".",
"removeSub",
"(",
"s",
")",
"\n",
"nc",
".",
"mu",
".",
"Unlock",
"(",
")",
"\n",
"break",
"\n",
"}",
"\n",
"}",
"\n",
"// Check for barrier messages",
"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",
"// create error here so we can pass it as a closure to the async cb dispatcher.",
"e",
":=",
"errors",
".",
"New",
"(",
"\"",
"\"",
"+",
"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",
"(",
")",
"{",
"// Release the wait group",
"defer",
"nc",
".",
"wg",
".",
"Done",
"(",
")",
"\n\n",
"// snapshot the bw and conn since they can change from underneath of us.",
"nc",
".",
"mu",
".",
"Lock",
"(",
")",
"\n",
"bw",
":=",
"nc",
".",
"bw",
"\n",
"conn",
":=",
"nc",
".",
"conn",
"\n",
"fch",
":=",
"nc",
".",
"fch",
"\n",
"nc",
".",
"mu",
".",
"Unlock",
"(",
")",
"\n\n",
"if",
"conn",
"==",
"nil",
"||",
"bw",
"==",
"nil",
"{",
"return",
"\n",
"}",
"\n\n",
"for",
"{",
"if",
"_",
",",
"ok",
":=",
"<-",
"fch",
";",
"!",
"ok",
"{",
"return",
"\n",
"}",
"\n",
"nc",
".",
"mu",
".",
"Lock",
"(",
")",
"\n\n",
"// Check to see if we should bail out.",
"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\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\n",
"// Copy content into connection's info structure.",
"nc",
".",
"info",
"=",
"ncInfo",
"\n",
"// 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",
"\n",
"}",
"\n",
"// 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",
"\n",
"// This is what we got from the server we are connected to.",
"urls",
":=",
"nc",
".",
"info",
".",
"ConnectURLs",
"\n",
"// Transform that to a map for easy lookups",
"tmp",
":=",
"make",
"(",
"map",
"[",
"string",
"]",
"struct",
"{",
"}",
",",
"len",
"(",
"urls",
")",
")",
"\n",
"for",
"_",
",",
"curl",
":=",
"range",
"urls",
"{",
"tmp",
"[",
"curl",
"]",
"=",
"struct",
"{",
"}",
"{",
"}",
"\n",
"}",
"\n",
"// Walk the pool and removed the implicit servers that are no longer in the",
"// given array/map",
"sp",
":=",
"nc",
".",
"srvPool",
"\n",
"for",
"i",
":=",
"0",
";",
"i",
"<",
"len",
"(",
"sp",
")",
";",
"i",
"++",
"{",
"srv",
":=",
"sp",
"[",
"i",
"]",
"\n",
"curl",
":=",
"srv",
".",
"url",
".",
"Host",
"\n",
"// Check if this URL is in the INFO protocol",
"_",
",",
"inInfo",
":=",
"tmp",
"[",
"curl",
"]",
"\n",
"// 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",
")",
"\n",
"// 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",
"\n",
"}",
"\n",
"if",
"!",
"inInfo",
"{",
"// Remove from server pool. Keep current order.",
"copy",
"(",
"sp",
"[",
"i",
":",
"]",
",",
"sp",
"[",
"i",
"+",
"1",
":",
"]",
")",
"\n",
"nc",
".",
"srvPool",
"=",
"sp",
"[",
":",
"len",
"(",
"sp",
")",
"-",
"1",
"]",
"\n",
"sp",
"=",
"nc",
".",
"srvPool",
"\n",
"i",
"--",
"\n",
"}",
"\n",
"}",
"\n",
"// 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",
")",
"\n\n",
"// 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",
"\n",
"}",
"\n",
"nc",
".",
"addURLToPool",
"(",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"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\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",
"// Ignore errors, we will simply not update the server pool...",
"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",
")",
"{",
"// Trim, remove quotes",
"ne",
":=",
"normalizeErr",
"(",
"ie",
")",
"\n",
"// convert to lower case.",
"e",
":=",
"strings",
".",
"ToLower",
"(",
"ne",
")",
"\n\n",
"// FIXME(dlc) - process Slow Consumer signals special.",
"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",
"(",
"\"",
"\"",
"+",
"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\n",
"if",
"nc",
".",
"isClosed",
"(",
")",
"{",
"nc",
".",
"mu",
".",
"Unlock",
"(",
")",
"\n",
"return",
"ErrConnectionClosed",
"\n",
"}",
"\n\n",
"if",
"nc",
".",
"isDrainingPubs",
"(",
")",
"{",
"nc",
".",
"mu",
".",
"Unlock",
"(",
")",
"\n",
"return",
"ErrConnectionDraining",
"\n",
"}",
"\n\n",
"// Proactively reject payloads over the threshold set by server.",
"msgSize",
":=",
"int64",
"(",
"len",
"(",
"data",
")",
")",
"\n",
"if",
"msgSize",
">",
"nc",
".",
"info",
".",
"MaxPayload",
"{",
"nc",
".",
"mu",
".",
"Unlock",
"(",
")",
"\n",
"return",
"ErrMaxPayload",
"\n",
"}",
"\n\n",
"// 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",
"(",
")",
"\n",
"// Check if we are over",
"if",
"nc",
".",
"pending",
".",
"Len",
"(",
")",
">=",
"nc",
".",
"Opts",
".",
"ReconnectBufSize",
"{",
"nc",
".",
"mu",
".",
"Unlock",
"(",
")",
"\n",
"return",
"ErrReconnectBufExceeded",
"\n",
"}",
"\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\n",
"// 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",
"\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\n",
"msgh",
"=",
"append",
"(",
"msgh",
",",
"b",
"[",
"i",
":",
"]",
"...",
")",
"\n",
"msgh",
"=",
"append",
"(",
"msgh",
",",
"_CRLF_",
"...",
")",
"\n\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\n",
"nc",
".",
"OutMsgs",
"++",
"\n",
"nc",
".",
"OutBytes",
"+=",
"uint64",
"(",
"len",
"(",
"data",
")",
")",
"\n\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\n",
"nc",
".",
"mu",
".",
"Lock",
"(",
")",
"\n",
"// Just return if closed.",
"if",
"nc",
".",
"isClosed",
"(",
")",
"{",
"nc",
".",
"mu",
".",
"Unlock",
"(",
")",
"\n",
"return",
"\n",
"}",
"\n\n",
"// Grab mch",
"mch",
":=",
"nc",
".",
"respMap",
"[",
"rt",
"]",
"\n",
"// Delete the key regardless, one response only.",
"// FIXME(dlc) - should we track responses past 1",
"// just statistics wise?",
"delete",
"(",
"nc",
".",
"respMap",
",",
"rt",
")",
"\n",
"nc",
".",
"mu",
".",
"Unlock",
"(",
")",
"\n\n",
"// 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",
"\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\n",
"nc",
".",
"mu",
".",
"Lock",
"(",
")",
"\n",
"// If user wants the old style.",
"if",
"nc",
".",
"Opts",
".",
"UseOldRequestStyle",
"{",
"nc",
".",
"mu",
".",
"Unlock",
"(",
")",
"\n",
"return",
"nc",
".",
"oldRequest",
"(",
"subj",
",",
"data",
",",
"timeout",
")",
"\n",
"}",
"\n\n",
"// Do setup for the new style.",
"if",
"nc",
".",
"respMap",
"==",
"nil",
"{",
"nc",
".",
"initNewResp",
"(",
")",
"\n",
"}",
"\n",
"// Create literal Inbox and map to a chan msg.",
"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\n",
"if",
"createSub",
"{",
"// Make sure scoped subscription is setup only once.",
"var",
"err",
"error",
"\n",
"nc",
".",
"respSetup",
".",
"Do",
"(",
"func",
"(",
")",
"{",
"err",
"=",
"nc",
".",
"createRespMux",
"(",
"ginbox",
")",
"}",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"}",
"\n\n",
"if",
"err",
":=",
"nc",
".",
"PublishRequest",
"(",
"subj",
",",
"respInbox",
",",
"data",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n\n",
"t",
":=",
"globalTimerPool",
".",
"Get",
"(",
"timeout",
")",
"\n",
"defer",
"globalTimerPool",
".",
"Put",
"(",
"t",
")",
"\n\n",
"var",
"ok",
"bool",
"\n",
"var",
"msg",
"*",
"Msg",
"\n\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\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",
"(",
")",
"{",
"// _INBOX wildcard",
"nc",
".",
"respSub",
"=",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"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",
"// ok here, but defer is generally expensive",
"defer",
"nc",
".",
"mu",
".",
"Unlock",
"(",
")",
"\n\n",
"// Check for some error conditions.",
"if",
"nc",
".",
"isClosed",
"(",
")",
"{",
"return",
"nil",
",",
"ErrConnectionClosed",
"\n",
"}",
"\n",
"if",
"nc",
".",
"isDraining",
"(",
")",
"{",
"return",
"nil",
",",
"ErrConnectionDraining",
"\n",
"}",
"\n\n",
"if",
"cb",
"==",
"nil",
"&&",
"ch",
"==",
"nil",
"{",
"return",
"nil",
",",
"ErrBadSubscription",
"\n",
"}",
"\n\n",
"sub",
":=",
"&",
"Subscription",
"{",
"Subject",
":",
"subj",
",",
"Queue",
":",
"queue",
",",
"mcb",
":",
"cb",
",",
"conn",
":",
"nc",
"}",
"\n",
"// Set pending limits.",
"sub",
".",
"pMsgsLimit",
"=",
"DefaultSubPendingMsgsLimit",
"\n",
"sub",
".",
"pBytesLimit",
"=",
"DefaultSubPendingBytesLimit",
"\n\n",
"// If we have an async callback, start up a sub specific",
"// Go routine to deliver the messages.",
"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",
"{",
"// Sync Subscription",
"sub",
".",
"typ",
"=",
"SyncSubscription",
"\n",
"sub",
".",
"mch",
"=",
"ch",
"\n",
"}",
"\n\n",
"nc",
".",
"subsMu",
".",
"Lock",
"(",
")",
"\n",
"nc",
".",
"ssid",
"++",
"\n",
"sub",
".",
"sid",
"=",
"nc",
".",
"ssid",
"\n",
"nc",
".",
"subs",
"[",
"sub",
".",
"sid",
"]",
"=",
"sub",
"\n",
"nc",
".",
"subsMu",
".",
"Unlock",
"(",
")",
"\n\n",
"// 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",
")",
"\n",
"// Kick flusher if needed.",
"if",
"len",
"(",
"nc",
".",
"fch",
")",
"==",
"0",
"{",
"nc",
".",
"kickFlusher",
"(",
")",
"\n",
"}",
"\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",
"// Release callers on NextMsg for SyncSubscription only",
"if",
"s",
".",
"mch",
"!=",
"nil",
"&&",
"s",
".",
"typ",
"==",
"SyncSubscription",
"{",
"close",
"(",
"s",
".",
"mch",
")",
"\n",
"}",
"\n",
"s",
".",
"mch",
"=",
"nil",
"\n\n",
"// Mark as invalid",
"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\n",
"// 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",
"(",
")",
"\n\n",
"// 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",
"\n",
"}",
"\n\n",
"// Check subscription state",
"sub",
".",
"mu",
".",
"Lock",
"(",
")",
"\n",
"conn",
":=",
"sub",
".",
"conn",
"\n",
"closed",
":=",
"sub",
".",
"closed",
"\n",
"pMsgs",
":=",
"sub",
".",
"pMsgs",
"\n",
"sub",
".",
"mu",
".",
"Unlock",
"(",
")",
"\n\n",
"if",
"conn",
"==",
"nil",
"||",
"closed",
"||",
"pMsgs",
"==",
"0",
"{",
"nc",
".",
"mu",
".",
"Lock",
"(",
")",
"\n",
"nc",
".",
"removeSub",
"(",
"sub",
")",
"\n",
"nc",
".",
"mu",
".",
"Unlock",
"(",
")",
"\n",
"return",
"\n",
"}",
"\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\n",
"s",
".",
"mu",
".",
"Lock",
"(",
")",
"\n",
"err",
":=",
"s",
".",
"validateNextMsgState",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"s",
".",
"mu",
".",
"Unlock",
"(",
")",
"\n",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n\n",
"// snapshot",
"mch",
":=",
"s",
".",
"mch",
"\n",
"s",
".",
"mu",
".",
"Unlock",
"(",
")",
"\n\n",
"var",
"ok",
"bool",
"\n",
"var",
"msg",
"*",
"Msg",
"\n\n",
"// If something is available right away, let's optimize that case.",
"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\n",
"// If we are here a message was not immediately available, so lets loop",
"// with a timeout.",
"t",
":=",
"globalTimerPool",
".",
"Get",
"(",
"timeout",
")",
"\n",
"defer",
"globalTimerPool",
".",
"Put",
"(",
"t",
")",
"\n\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\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\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\n",
"// Update some stats.",
"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\n",
"if",
"max",
">",
"0",
"{",
"if",
"delivered",
">",
"max",
"{",
"return",
"ErrMaxMessages",
"\n",
"}",
"\n",
"// Remove subscription if we have reached max.",
"if",
"delivered",
"==",
"max",
"{",
"nc",
".",
"mu",
".",
"Lock",
"(",
")",
"\n",
"nc",
".",
"removeSub",
"(",
"s",
")",
"\n",
"nc",
".",
"mu",
".",
"Unlock",
"(",
")",
"\n",
"}",
"\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",
"// Flush in place.",
"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\n",
"if",
"nc",
".",
"status",
"!=",
"CONNECTED",
"{",
"nc",
".",
"mu",
".",
"Unlock",
"(",
")",
"\n",
"return",
"\n",
"}",
"\n\n",
"// Check for violation",
"nc",
".",
"pout",
"++",
"\n",
"if",
"nc",
".",
"pout",
">",
"nc",
".",
"Opts",
".",
"MaxPingsOut",
"{",
"nc",
".",
"mu",
".",
"Unlock",
"(",
")",
"\n",
"nc",
".",
"processOpErr",
"(",
"ErrStaleConnection",
")",
"\n",
"return",
"\n",
"}",
"\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",
"(",
")",
"{",
"// 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",
"(",
")",
"\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",
"// adjustedMax could be 0 here if the number of delivered msgs",
"// reached the max, if so unsubscribe.",
"if",
"adjustedMax",
"==",
"0",
"{",
"s",
".",
"mu",
".",
"Unlock",
"(",
")",
"\n",
"fmt",
".",
"Fprintf",
"(",
"nc",
".",
"bw",
",",
"unsubProto",
",",
"s",
".",
"sid",
",",
"_EMPTY_",
")",
"\n",
"continue",
"\n",
"}",
"\n",
"}",
"\n",
"s",
".",
"mu",
".",
"Unlock",
"(",
")",
"\n\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",
"(",
")",
"{",
"// Clear any queued pongs, e.g. pending flush calls.",
"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\n",
"// Kick the Go routines so they fall out.",
"nc",
".",
"kickFlusher",
"(",
")",
"\n",
"nc",
".",
"mu",
".",
"Unlock",
"(",
")",
"\n\n",
"nc",
".",
"mu",
".",
"Lock",
"(",
")",
"\n\n",
"// Clear any queued pongs, e.g. pending flush calls.",
"nc",
".",
"clearPendingFlushCalls",
"(",
")",
"\n\n",
"// Clear any queued and blocking Requests.",
"nc",
".",
"clearPendingRequestCalls",
"(",
")",
"\n\n",
"// Stop ping timer if set.",
"nc",
".",
"stopPingTimer",
"(",
")",
"\n",
"nc",
".",
"ptmr",
"=",
"nil",
"\n\n",
"// Go ahead and make sure we have flushed the outbound",
"if",
"nc",
".",
"conn",
"!=",
"nil",
"{",
"nc",
".",
"bw",
".",
"Flush",
"(",
")",
"\n",
"defer",
"nc",
".",
"conn",
".",
"Close",
"(",
")",
"\n",
"}",
"\n\n",
"// Close sync subscriber channels and release any",
"// pending NextMsg() calls.",
"nc",
".",
"subsMu",
".",
"Lock",
"(",
")",
"\n",
"for",
"_",
",",
"s",
":=",
"range",
"nc",
".",
"subs",
"{",
"s",
".",
"mu",
".",
"Lock",
"(",
")",
"\n\n",
"// Release callers on NextMsg for SyncSubscription only",
"if",
"s",
".",
"mch",
"!=",
"nil",
"&&",
"s",
".",
"typ",
"==",
"SyncSubscription",
"{",
"close",
"(",
"s",
".",
"mch",
")",
"\n",
"}",
"\n",
"s",
".",
"mch",
"=",
"nil",
"\n",
"// Mark as invalid, for signaling to deliverMsgs",
"s",
".",
"closed",
"=",
"true",
"\n",
"// Mark connection closed in subscription",
"s",
".",
"connClosed",
"=",
"true",
"\n",
"// If we have an async subscription, signals it to exit",
"if",
"s",
".",
"typ",
"==",
"AsyncSubscription",
"&&",
"s",
".",
"pCond",
"!=",
"nil",
"{",
"s",
".",
"pCond",
".",
"Signal",
"(",
")",
"\n",
"}",
"\n\n",
"s",
".",
"mu",
".",
"Unlock",
"(",
")",
"\n",
"}",
"\n",
"nc",
".",
"subs",
"=",
"nil",
"\n",
"nc",
".",
"subsMu",
".",
"Unlock",
"(",
")",
"\n\n",
"nc",
".",
"status",
"=",
"status",
"\n\n",
"// 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",
")",
"}",
")",
"\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",
"(",
")",
"{",
"// Snapshot subs list.",
"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\n",
"// for pushing errors with context.",
"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\n",
"// Do subs first",
"for",
"_",
",",
"s",
":=",
"range",
"subs",
"{",
"if",
"err",
":=",
"s",
".",
"Drain",
"(",
")",
";",
"err",
"!=",
"nil",
"{",
"// We will notify about these but continue.",
"pushErr",
"(",
"err",
")",
"\n",
"}",
"\n",
"}",
"\n\n",
"// Wait for the subscriptions to drop to zero.",
"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\n",
"// Check if we timed out.",
"if",
"nc",
".",
"NumSubscriptions",
"(",
")",
"!=",
"0",
"{",
"pushErr",
"(",
"ErrDrainTimeout",
")",
"\n",
"}",
"\n\n",
"// Flip State",
"nc",
".",
"mu",
".",
"Lock",
"(",
")",
"\n",
"nc",
".",
"status",
"=",
"DRAINING_PUBS",
"\n",
"nc",
".",
"mu",
".",
"Unlock",
"(",
")",
"\n\n",
"// Do publish drain via Flush() call.",
"err",
":=",
"nc",
".",
"Flush",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"pushErr",
"(",
"err",
")",
"\n",
"nc",
".",
"Close",
"(",
")",
"\n",
"return",
"\n",
"}",
"\n\n",
"// Move to closed state.",
"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",
"(",
"\"",
"\"",
",",
"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",
"{",
"// Stats are updated either under connection's mu or subsMu mutexes.",
"// Lock both to safely get them.",
"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",
"// Wipe our key on exit.",
"defer",
"kp",
".",
"Wipe",
"(",
")",
"\n\n",
"pub",
",",
"err",
":=",
"kp",
".",
"PublicKey",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"if",
"!",
"nkeys",
".",
"IsValidPublicUserKey",
"(",
"pub",
")",
"{",
"return",
"nil",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
")",
"\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",
"// Wipe our key on exit.",
"defer",
"kp",
".",
"Wipe",
"(",
")",
"\n\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\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",
"// Check whether the context is done already before making",
"// the request.",
"if",
"ctx",
".",
"Err",
"(",
")",
"!=",
"nil",
"{",
"return",
"nil",
",",
"ctx",
".",
"Err",
"(",
")",
"\n",
"}",
"\n\n",
"nc",
".",
"mu",
".",
"Lock",
"(",
")",
"\n",
"// If user wants the old style.",
"if",
"nc",
".",
"Opts",
".",
"UseOldRequestStyle",
"{",
"nc",
".",
"mu",
".",
"Unlock",
"(",
")",
"\n",
"return",
"nc",
".",
"oldRequestWithContext",
"(",
"ctx",
",",
"subj",
",",
"data",
")",
"\n",
"}",
"\n\n",
"// Do setup for the new style.",
"if",
"nc",
".",
"respMap",
"==",
"nil",
"{",
"nc",
".",
"initNewResp",
"(",
")",
"\n",
"}",
"\n",
"// Create literal Inbox and map to a chan msg.",
"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\n",
"if",
"createSub",
"{",
"// Make sure scoped subscription is setup only once.",
"var",
"err",
"error",
"\n",
"nc",
".",
"respSetup",
".",
"Do",
"(",
"func",
"(",
")",
"{",
"err",
"=",
"nc",
".",
"createRespMux",
"(",
"ginbox",
")",
"}",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"}",
"\n\n",
"err",
":=",
"nc",
".",
"PublishRequest",
"(",
"subj",
",",
"respInbox",
",",
"data",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n\n",
"var",
"ok",
"bool",
"\n",
"var",
"msg",
"*",
"Msg",
"\n\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\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\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\n",
"err",
"=",
"nc",
".",
"PublishRequest",
"(",
"subj",
",",
"inbox",
",",
"data",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\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\n",
"s",
".",
"mu",
".",
"Lock",
"(",
")",
"\n",
"err",
":=",
"s",
".",
"validateNextMsgState",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"s",
".",
"mu",
".",
"Unlock",
"(",
")",
"\n",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n\n",
"// snapshot",
"mch",
":=",
"s",
".",
"mch",
"\n",
"s",
".",
"mu",
".",
"Unlock",
"(",
")",
"\n\n",
"var",
"ok",
"bool",
"\n",
"var",
"msg",
"*",
"Msg",
"\n\n",
"// If something is available right away, let's optimize that case.",
"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\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\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\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\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",
"{",
"// Channel has most likely been closed.",
"return",
"\n",
"}",
"\n",
"if",
"e",
":=",
"c",
".",
"Publish",
"(",
"subject",
",",
"val",
".",
"Interface",
"(",
")",
")",
";",
"e",
"!=",
"nil",
"{",
"// Do this under lock.",
"c",
".",
"Conn",
".",
"mu",
".",
"Lock",
"(",
")",
"\n",
"defer",
"c",
".",
"Conn",
".",
"mu",
".",
"Unlock",
"(",
")",
"\n\n",
"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",
")",
"\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\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",
"(",
"\"",
"\"",
"+",
"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",
"// 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",
"(",
")",
"\n",
"}",
"\n",
"}",
"(",
")",
"\n",
"// Actually do the send to the channel.",
"chVal",
".",
"Send",
"(",
"oPtr",
")",
"\n",
"}",
"\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",
"(",
"\"",
"\"",
")",
"\n",
"if",
"err",
"!=",
"nil",
"||",
"resp",
"==",
"nil",
"{",
"log",
".",
"Fatalf",
"(",
"\"",
"\"",
",",
"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",
"(",
"\"",
"\"",
",",
"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 |
nats-io/go-nats | bench/bench.go | CSV | func (bm *Benchmark) CSV() string {
var buffer bytes.Buffer
writer := csv.NewWriter(&buffer)
headers := []string{"#RunID", "ClientID", "MsgCount", "MsgBytes", "MsgsPerSec", "BytesPerSec", "DurationSecs"}
if err := writer.Write(headers); err != nil {
log.Fatalf("Error while serializing headers %q: %v", headers, err)
}
groups := []*SampleGroup{bm.Subs, bm.Pubs}
pre := "S"
for i, g := range groups {
if i == 1 {
pre = "P"
}
for j, c := range g.Samples {
r := []string{bm.RunID, fmt.Sprintf("%s%d", pre, j), fmt.Sprintf("%d", c.MsgCnt), fmt.Sprintf("%d", c.MsgBytes), fmt.Sprintf("%d", c.Rate()), fmt.Sprintf("%f", c.Throughput()), fmt.Sprintf("%f", c.Duration().Seconds())}
if err := writer.Write(r); err != nil {
log.Fatalf("Error while serializing %v: %v", c, err)
}
}
}
writer.Flush()
return buffer.String()
} | go | func (bm *Benchmark) CSV() string {
var buffer bytes.Buffer
writer := csv.NewWriter(&buffer)
headers := []string{"#RunID", "ClientID", "MsgCount", "MsgBytes", "MsgsPerSec", "BytesPerSec", "DurationSecs"}
if err := writer.Write(headers); err != nil {
log.Fatalf("Error while serializing headers %q: %v", headers, err)
}
groups := []*SampleGroup{bm.Subs, bm.Pubs}
pre := "S"
for i, g := range groups {
if i == 1 {
pre = "P"
}
for j, c := range g.Samples {
r := []string{bm.RunID, fmt.Sprintf("%s%d", pre, j), fmt.Sprintf("%d", c.MsgCnt), fmt.Sprintf("%d", c.MsgBytes), fmt.Sprintf("%d", c.Rate()), fmt.Sprintf("%f", c.Throughput()), fmt.Sprintf("%f", c.Duration().Seconds())}
if err := writer.Write(r); err != nil {
log.Fatalf("Error while serializing %v: %v", c, err)
}
}
}
writer.Flush()
return buffer.String()
} | [
"func",
"(",
"bm",
"*",
"Benchmark",
")",
"CSV",
"(",
")",
"string",
"{",
"var",
"buffer",
"bytes",
".",
"Buffer",
"\n",
"writer",
":=",
"csv",
".",
"NewWriter",
"(",
"&",
"buffer",
")",
"\n",
"headers",
":=",
"[",
"]",
"string",
"{",
"\"",
"\"",
",",
"\"",
"\"",
",",
"\"",
"\"",
",",
"\"",
"\"",
",",
"\"",
"\"",
",",
"\"",
"\"",
",",
"\"",
"\"",
"}",
"\n",
"if",
"err",
":=",
"writer",
".",
"Write",
"(",
"headers",
")",
";",
"err",
"!=",
"nil",
"{",
"log",
".",
"Fatalf",
"(",
"\"",
"\"",
",",
"headers",
",",
"err",
")",
"\n",
"}",
"\n",
"groups",
":=",
"[",
"]",
"*",
"SampleGroup",
"{",
"bm",
".",
"Subs",
",",
"bm",
".",
"Pubs",
"}",
"\n",
"pre",
":=",
"\"",
"\"",
"\n",
"for",
"i",
",",
"g",
":=",
"range",
"groups",
"{",
"if",
"i",
"==",
"1",
"{",
"pre",
"=",
"\"",
"\"",
"\n",
"}",
"\n",
"for",
"j",
",",
"c",
":=",
"range",
"g",
".",
"Samples",
"{",
"r",
":=",
"[",
"]",
"string",
"{",
"bm",
".",
"RunID",
",",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"pre",
",",
"j",
")",
",",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"c",
".",
"MsgCnt",
")",
",",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"c",
".",
"MsgBytes",
")",
",",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"c",
".",
"Rate",
"(",
")",
")",
",",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"c",
".",
"Throughput",
"(",
")",
")",
",",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"c",
".",
"Duration",
"(",
")",
".",
"Seconds",
"(",
")",
")",
"}",
"\n",
"if",
"err",
":=",
"writer",
".",
"Write",
"(",
"r",
")",
";",
"err",
"!=",
"nil",
"{",
"log",
".",
"Fatalf",
"(",
"\"",
"\"",
",",
"c",
",",
"err",
")",
"\n",
"}",
"\n",
"}",
"\n",
"}",
"\n\n",
"writer",
".",
"Flush",
"(",
")",
"\n",
"return",
"buffer",
".",
"String",
"(",
")",
"\n",
"}"
] | // CSV generates a csv report of all the samples collected | [
"CSV",
"generates",
"a",
"csv",
"report",
"of",
"all",
"the",
"samples",
"collected"
] | 36d30b0ba7aa260ae25b4f3d312b2a700106fd78 | https://github.com/nats-io/go-nats/blob/36d30b0ba7aa260ae25b4f3d312b2a700106fd78/bench/bench.go#L120-L143 | train |
nats-io/go-nats | bench/bench.go | NewSample | func NewSample(jobCount int, msgSize int, start, end time.Time, nc *nats.Conn) *Sample {
s := Sample{JobMsgCnt: jobCount, Start: start, End: end}
s.MsgBytes = uint64(msgSize * jobCount)
s.MsgCnt = nc.OutMsgs + nc.InMsgs
s.IOBytes = nc.OutBytes + nc.InBytes
return &s
} | go | func NewSample(jobCount int, msgSize int, start, end time.Time, nc *nats.Conn) *Sample {
s := Sample{JobMsgCnt: jobCount, Start: start, End: end}
s.MsgBytes = uint64(msgSize * jobCount)
s.MsgCnt = nc.OutMsgs + nc.InMsgs
s.IOBytes = nc.OutBytes + nc.InBytes
return &s
} | [
"func",
"NewSample",
"(",
"jobCount",
"int",
",",
"msgSize",
"int",
",",
"start",
",",
"end",
"time",
".",
"Time",
",",
"nc",
"*",
"nats",
".",
"Conn",
")",
"*",
"Sample",
"{",
"s",
":=",
"Sample",
"{",
"JobMsgCnt",
":",
"jobCount",
",",
"Start",
":",
"start",
",",
"End",
":",
"end",
"}",
"\n",
"s",
".",
"MsgBytes",
"=",
"uint64",
"(",
"msgSize",
"*",
"jobCount",
")",
"\n",
"s",
".",
"MsgCnt",
"=",
"nc",
".",
"OutMsgs",
"+",
"nc",
".",
"InMsgs",
"\n",
"s",
".",
"IOBytes",
"=",
"nc",
".",
"OutBytes",
"+",
"nc",
".",
"InBytes",
"\n",
"return",
"&",
"s",
"\n",
"}"
] | // NewSample creates a new Sample initialized to the provided values. The nats.Conn information captured | [
"NewSample",
"creates",
"a",
"new",
"Sample",
"initialized",
"to",
"the",
"provided",
"values",
".",
"The",
"nats",
".",
"Conn",
"information",
"captured"
] | 36d30b0ba7aa260ae25b4f3d312b2a700106fd78 | https://github.com/nats-io/go-nats/blob/36d30b0ba7aa260ae25b4f3d312b2a700106fd78/bench/bench.go#L146-L152 | train |
nats-io/go-nats | bench/bench.go | Throughput | func (s *Sample) Throughput() float64 {
return float64(s.MsgBytes) / s.Duration().Seconds()
} | go | func (s *Sample) Throughput() float64 {
return float64(s.MsgBytes) / s.Duration().Seconds()
} | [
"func",
"(",
"s",
"*",
"Sample",
")",
"Throughput",
"(",
")",
"float64",
"{",
"return",
"float64",
"(",
"s",
".",
"MsgBytes",
")",
"/",
"s",
".",
"Duration",
"(",
")",
".",
"Seconds",
"(",
")",
"\n",
"}"
] | // Throughput of bytes per second | [
"Throughput",
"of",
"bytes",
"per",
"second"
] | 36d30b0ba7aa260ae25b4f3d312b2a700106fd78 | https://github.com/nats-io/go-nats/blob/36d30b0ba7aa260ae25b4f3d312b2a700106fd78/bench/bench.go#L155-L157 | train |
nats-io/go-nats | bench/bench.go | Rate | func (s *Sample) Rate() int64 {
return int64(float64(s.JobMsgCnt) / s.Duration().Seconds())
} | go | func (s *Sample) Rate() int64 {
return int64(float64(s.JobMsgCnt) / s.Duration().Seconds())
} | [
"func",
"(",
"s",
"*",
"Sample",
")",
"Rate",
"(",
")",
"int64",
"{",
"return",
"int64",
"(",
"float64",
"(",
"s",
".",
"JobMsgCnt",
")",
"/",
"s",
".",
"Duration",
"(",
")",
".",
"Seconds",
"(",
")",
")",
"\n",
"}"
] | // Rate of meessages in the job per second | [
"Rate",
"of",
"meessages",
"in",
"the",
"job",
"per",
"second"
] | 36d30b0ba7aa260ae25b4f3d312b2a700106fd78 | https://github.com/nats-io/go-nats/blob/36d30b0ba7aa260ae25b4f3d312b2a700106fd78/bench/bench.go#L160-L162 | train |
nats-io/go-nats | bench/bench.go | Duration | func (s *Sample) Duration() time.Duration {
return s.End.Sub(s.Start)
} | go | func (s *Sample) Duration() time.Duration {
return s.End.Sub(s.Start)
} | [
"func",
"(",
"s",
"*",
"Sample",
")",
"Duration",
"(",
")",
"time",
".",
"Duration",
"{",
"return",
"s",
".",
"End",
".",
"Sub",
"(",
"s",
".",
"Start",
")",
"\n",
"}"
] | // Duration that the sample was active | [
"Duration",
"that",
"the",
"sample",
"was",
"active"
] | 36d30b0ba7aa260ae25b4f3d312b2a700106fd78 | https://github.com/nats-io/go-nats/blob/36d30b0ba7aa260ae25b4f3d312b2a700106fd78/bench/bench.go#L171-L173 | train |
nats-io/go-nats | bench/bench.go | MinRate | func (sg *SampleGroup) MinRate() int64 {
m := int64(0)
for i, s := range sg.Samples {
if i == 0 {
m = s.Rate()
}
m = min(m, s.Rate())
}
return m
} | go | func (sg *SampleGroup) MinRate() int64 {
m := int64(0)
for i, s := range sg.Samples {
if i == 0 {
m = s.Rate()
}
m = min(m, s.Rate())
}
return m
} | [
"func",
"(",
"sg",
"*",
"SampleGroup",
")",
"MinRate",
"(",
")",
"int64",
"{",
"m",
":=",
"int64",
"(",
"0",
")",
"\n",
"for",
"i",
",",
"s",
":=",
"range",
"sg",
".",
"Samples",
"{",
"if",
"i",
"==",
"0",
"{",
"m",
"=",
"s",
".",
"Rate",
"(",
")",
"\n",
"}",
"\n",
"m",
"=",
"min",
"(",
"m",
",",
"s",
".",
"Rate",
"(",
")",
")",
"\n",
"}",
"\n",
"return",
"m",
"\n",
"}"
] | // MinRate returns the smallest message rate in the SampleGroup | [
"MinRate",
"returns",
"the",
"smallest",
"message",
"rate",
"in",
"the",
"SampleGroup"
] | 36d30b0ba7aa260ae25b4f3d312b2a700106fd78 | https://github.com/nats-io/go-nats/blob/36d30b0ba7aa260ae25b4f3d312b2a700106fd78/bench/bench.go#L193-L202 | train |
nats-io/go-nats | bench/bench.go | MaxRate | func (sg *SampleGroup) MaxRate() int64 {
m := int64(0)
for i, s := range sg.Samples {
if i == 0 {
m = s.Rate()
}
m = max(m, s.Rate())
}
return m
} | go | func (sg *SampleGroup) MaxRate() int64 {
m := int64(0)
for i, s := range sg.Samples {
if i == 0 {
m = s.Rate()
}
m = max(m, s.Rate())
}
return m
} | [
"func",
"(",
"sg",
"*",
"SampleGroup",
")",
"MaxRate",
"(",
")",
"int64",
"{",
"m",
":=",
"int64",
"(",
"0",
")",
"\n",
"for",
"i",
",",
"s",
":=",
"range",
"sg",
".",
"Samples",
"{",
"if",
"i",
"==",
"0",
"{",
"m",
"=",
"s",
".",
"Rate",
"(",
")",
"\n",
"}",
"\n",
"m",
"=",
"max",
"(",
"m",
",",
"s",
".",
"Rate",
"(",
")",
")",
"\n",
"}",
"\n",
"return",
"m",
"\n",
"}"
] | // MaxRate returns the largest message rate in the SampleGroup | [
"MaxRate",
"returns",
"the",
"largest",
"message",
"rate",
"in",
"the",
"SampleGroup"
] | 36d30b0ba7aa260ae25b4f3d312b2a700106fd78 | https://github.com/nats-io/go-nats/blob/36d30b0ba7aa260ae25b4f3d312b2a700106fd78/bench/bench.go#L205-L214 | train |
nats-io/go-nats | bench/bench.go | AvgRate | func (sg *SampleGroup) AvgRate() int64 {
sum := uint64(0)
for _, s := range sg.Samples {
sum += uint64(s.Rate())
}
return int64(sum / uint64(len(sg.Samples)))
} | go | func (sg *SampleGroup) AvgRate() int64 {
sum := uint64(0)
for _, s := range sg.Samples {
sum += uint64(s.Rate())
}
return int64(sum / uint64(len(sg.Samples)))
} | [
"func",
"(",
"sg",
"*",
"SampleGroup",
")",
"AvgRate",
"(",
")",
"int64",
"{",
"sum",
":=",
"uint64",
"(",
"0",
")",
"\n",
"for",
"_",
",",
"s",
":=",
"range",
"sg",
".",
"Samples",
"{",
"sum",
"+=",
"uint64",
"(",
"s",
".",
"Rate",
"(",
")",
")",
"\n",
"}",
"\n",
"return",
"int64",
"(",
"sum",
"/",
"uint64",
"(",
"len",
"(",
"sg",
".",
"Samples",
")",
")",
")",
"\n",
"}"
] | // AvgRate returns the average of all the message rates in the SampleGroup | [
"AvgRate",
"returns",
"the",
"average",
"of",
"all",
"the",
"message",
"rates",
"in",
"the",
"SampleGroup"
] | 36d30b0ba7aa260ae25b4f3d312b2a700106fd78 | https://github.com/nats-io/go-nats/blob/36d30b0ba7aa260ae25b4f3d312b2a700106fd78/bench/bench.go#L217-L223 | train |
nats-io/go-nats | bench/bench.go | StdDev | func (sg *SampleGroup) StdDev() float64 {
avg := float64(sg.AvgRate())
sum := float64(0)
for _, c := range sg.Samples {
sum += math.Pow(float64(c.Rate())-avg, 2)
}
variance := sum / float64(len(sg.Samples))
return math.Sqrt(variance)
} | go | func (sg *SampleGroup) StdDev() float64 {
avg := float64(sg.AvgRate())
sum := float64(0)
for _, c := range sg.Samples {
sum += math.Pow(float64(c.Rate())-avg, 2)
}
variance := sum / float64(len(sg.Samples))
return math.Sqrt(variance)
} | [
"func",
"(",
"sg",
"*",
"SampleGroup",
")",
"StdDev",
"(",
")",
"float64",
"{",
"avg",
":=",
"float64",
"(",
"sg",
".",
"AvgRate",
"(",
")",
")",
"\n",
"sum",
":=",
"float64",
"(",
"0",
")",
"\n",
"for",
"_",
",",
"c",
":=",
"range",
"sg",
".",
"Samples",
"{",
"sum",
"+=",
"math",
".",
"Pow",
"(",
"float64",
"(",
"c",
".",
"Rate",
"(",
")",
")",
"-",
"avg",
",",
"2",
")",
"\n",
"}",
"\n",
"variance",
":=",
"sum",
"/",
"float64",
"(",
"len",
"(",
"sg",
".",
"Samples",
")",
")",
"\n",
"return",
"math",
".",
"Sqrt",
"(",
"variance",
")",
"\n",
"}"
] | // StdDev returns the standard deviation the message rates in the SampleGroup | [
"StdDev",
"returns",
"the",
"standard",
"deviation",
"the",
"message",
"rates",
"in",
"the",
"SampleGroup"
] | 36d30b0ba7aa260ae25b4f3d312b2a700106fd78 | https://github.com/nats-io/go-nats/blob/36d30b0ba7aa260ae25b4f3d312b2a700106fd78/bench/bench.go#L226-L234 | train |
nats-io/go-nats | bench/bench.go | AddSample | func (sg *SampleGroup) AddSample(e *Sample) {
sg.Samples = append(sg.Samples, e)
if len(sg.Samples) == 1 {
sg.Start = e.Start
sg.End = e.End
}
sg.IOBytes += e.IOBytes
sg.JobMsgCnt += e.JobMsgCnt
sg.MsgCnt += e.MsgCnt
sg.MsgBytes += e.MsgBytes
if e.Start.Before(sg.Start) {
sg.Start = e.Start
}
if e.End.After(sg.End) {
sg.End = e.End
}
} | go | func (sg *SampleGroup) AddSample(e *Sample) {
sg.Samples = append(sg.Samples, e)
if len(sg.Samples) == 1 {
sg.Start = e.Start
sg.End = e.End
}
sg.IOBytes += e.IOBytes
sg.JobMsgCnt += e.JobMsgCnt
sg.MsgCnt += e.MsgCnt
sg.MsgBytes += e.MsgBytes
if e.Start.Before(sg.Start) {
sg.Start = e.Start
}
if e.End.After(sg.End) {
sg.End = e.End
}
} | [
"func",
"(",
"sg",
"*",
"SampleGroup",
")",
"AddSample",
"(",
"e",
"*",
"Sample",
")",
"{",
"sg",
".",
"Samples",
"=",
"append",
"(",
"sg",
".",
"Samples",
",",
"e",
")",
"\n\n",
"if",
"len",
"(",
"sg",
".",
"Samples",
")",
"==",
"1",
"{",
"sg",
".",
"Start",
"=",
"e",
".",
"Start",
"\n",
"sg",
".",
"End",
"=",
"e",
".",
"End",
"\n",
"}",
"\n",
"sg",
".",
"IOBytes",
"+=",
"e",
".",
"IOBytes",
"\n",
"sg",
".",
"JobMsgCnt",
"+=",
"e",
".",
"JobMsgCnt",
"\n",
"sg",
".",
"MsgCnt",
"+=",
"e",
".",
"MsgCnt",
"\n",
"sg",
".",
"MsgBytes",
"+=",
"e",
".",
"MsgBytes",
"\n\n",
"if",
"e",
".",
"Start",
".",
"Before",
"(",
"sg",
".",
"Start",
")",
"{",
"sg",
".",
"Start",
"=",
"e",
".",
"Start",
"\n",
"}",
"\n\n",
"if",
"e",
".",
"End",
".",
"After",
"(",
"sg",
".",
"End",
")",
"{",
"sg",
".",
"End",
"=",
"e",
".",
"End",
"\n",
"}",
"\n",
"}"
] | // AddSample adds a Sample to the SampleGroup. After adding a Sample it shouldn't be modified. | [
"AddSample",
"adds",
"a",
"Sample",
"to",
"the",
"SampleGroup",
".",
"After",
"adding",
"a",
"Sample",
"it",
"shouldn",
"t",
"be",
"modified",
"."
] | 36d30b0ba7aa260ae25b4f3d312b2a700106fd78 | https://github.com/nats-io/go-nats/blob/36d30b0ba7aa260ae25b4f3d312b2a700106fd78/bench/bench.go#L237-L256 | train |
nats-io/go-nats | bench/bench.go | Report | func (bm *Benchmark) Report() string {
var buffer bytes.Buffer
indent := ""
if !bm.Pubs.HasSamples() && !bm.Subs.HasSamples() {
return "No publisher or subscribers. Nothing to report."
}
if bm.Pubs.HasSamples() && bm.Subs.HasSamples() {
buffer.WriteString(fmt.Sprintf("%s Pub/Sub stats: %s\n", bm.Name, bm))
indent += " "
}
if bm.Pubs.HasSamples() {
buffer.WriteString(fmt.Sprintf("%sPub stats: %s\n", indent, bm.Pubs))
if len(bm.Pubs.Samples) > 1 {
for i, stat := range bm.Pubs.Samples {
buffer.WriteString(fmt.Sprintf("%s [%d] %v (%d msgs)\n", indent, i+1, stat, stat.JobMsgCnt))
}
buffer.WriteString(fmt.Sprintf("%s %s\n", indent, bm.Pubs.Statistics()))
}
}
if bm.Subs.HasSamples() {
buffer.WriteString(fmt.Sprintf("%sSub stats: %s\n", indent, bm.Subs))
if len(bm.Subs.Samples) > 1 {
for i, stat := range bm.Subs.Samples {
buffer.WriteString(fmt.Sprintf("%s [%d] %v (%d msgs)\n", indent, i+1, stat, stat.JobMsgCnt))
}
buffer.WriteString(fmt.Sprintf("%s %s\n", indent, bm.Subs.Statistics()))
}
}
return buffer.String()
} | go | func (bm *Benchmark) Report() string {
var buffer bytes.Buffer
indent := ""
if !bm.Pubs.HasSamples() && !bm.Subs.HasSamples() {
return "No publisher or subscribers. Nothing to report."
}
if bm.Pubs.HasSamples() && bm.Subs.HasSamples() {
buffer.WriteString(fmt.Sprintf("%s Pub/Sub stats: %s\n", bm.Name, bm))
indent += " "
}
if bm.Pubs.HasSamples() {
buffer.WriteString(fmt.Sprintf("%sPub stats: %s\n", indent, bm.Pubs))
if len(bm.Pubs.Samples) > 1 {
for i, stat := range bm.Pubs.Samples {
buffer.WriteString(fmt.Sprintf("%s [%d] %v (%d msgs)\n", indent, i+1, stat, stat.JobMsgCnt))
}
buffer.WriteString(fmt.Sprintf("%s %s\n", indent, bm.Pubs.Statistics()))
}
}
if bm.Subs.HasSamples() {
buffer.WriteString(fmt.Sprintf("%sSub stats: %s\n", indent, bm.Subs))
if len(bm.Subs.Samples) > 1 {
for i, stat := range bm.Subs.Samples {
buffer.WriteString(fmt.Sprintf("%s [%d] %v (%d msgs)\n", indent, i+1, stat, stat.JobMsgCnt))
}
buffer.WriteString(fmt.Sprintf("%s %s\n", indent, bm.Subs.Statistics()))
}
}
return buffer.String()
} | [
"func",
"(",
"bm",
"*",
"Benchmark",
")",
"Report",
"(",
")",
"string",
"{",
"var",
"buffer",
"bytes",
".",
"Buffer",
"\n\n",
"indent",
":=",
"\"",
"\"",
"\n",
"if",
"!",
"bm",
".",
"Pubs",
".",
"HasSamples",
"(",
")",
"&&",
"!",
"bm",
".",
"Subs",
".",
"HasSamples",
"(",
")",
"{",
"return",
"\"",
"\"",
"\n",
"}",
"\n\n",
"if",
"bm",
".",
"Pubs",
".",
"HasSamples",
"(",
")",
"&&",
"bm",
".",
"Subs",
".",
"HasSamples",
"(",
")",
"{",
"buffer",
".",
"WriteString",
"(",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\\n",
"\"",
",",
"bm",
".",
"Name",
",",
"bm",
")",
")",
"\n",
"indent",
"+=",
"\"",
"\"",
"\n",
"}",
"\n",
"if",
"bm",
".",
"Pubs",
".",
"HasSamples",
"(",
")",
"{",
"buffer",
".",
"WriteString",
"(",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\\n",
"\"",
",",
"indent",
",",
"bm",
".",
"Pubs",
")",
")",
"\n",
"if",
"len",
"(",
"bm",
".",
"Pubs",
".",
"Samples",
")",
">",
"1",
"{",
"for",
"i",
",",
"stat",
":=",
"range",
"bm",
".",
"Pubs",
".",
"Samples",
"{",
"buffer",
".",
"WriteString",
"(",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\\n",
"\"",
",",
"indent",
",",
"i",
"+",
"1",
",",
"stat",
",",
"stat",
".",
"JobMsgCnt",
")",
")",
"\n",
"}",
"\n",
"buffer",
".",
"WriteString",
"(",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\\n",
"\"",
",",
"indent",
",",
"bm",
".",
"Pubs",
".",
"Statistics",
"(",
")",
")",
")",
"\n",
"}",
"\n",
"}",
"\n\n",
"if",
"bm",
".",
"Subs",
".",
"HasSamples",
"(",
")",
"{",
"buffer",
".",
"WriteString",
"(",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\\n",
"\"",
",",
"indent",
",",
"bm",
".",
"Subs",
")",
")",
"\n",
"if",
"len",
"(",
"bm",
".",
"Subs",
".",
"Samples",
")",
">",
"1",
"{",
"for",
"i",
",",
"stat",
":=",
"range",
"bm",
".",
"Subs",
".",
"Samples",
"{",
"buffer",
".",
"WriteString",
"(",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\\n",
"\"",
",",
"indent",
",",
"i",
"+",
"1",
",",
"stat",
",",
"stat",
".",
"JobMsgCnt",
")",
")",
"\n",
"}",
"\n",
"buffer",
".",
"WriteString",
"(",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\\n",
"\"",
",",
"indent",
",",
"bm",
".",
"Subs",
".",
"Statistics",
"(",
")",
")",
")",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"buffer",
".",
"String",
"(",
")",
"\n",
"}"
] | // Report returns a human readable report of the samples taken in the Benchmark | [
"Report",
"returns",
"a",
"human",
"readable",
"report",
"of",
"the",
"samples",
"taken",
"in",
"the",
"Benchmark"
] | 36d30b0ba7aa260ae25b4f3d312b2a700106fd78 | https://github.com/nats-io/go-nats/blob/36d30b0ba7aa260ae25b4f3d312b2a700106fd78/bench/bench.go#L264-L296 | train |
nats-io/go-nats | bench/bench.go | HumanBytes | func HumanBytes(bytes float64, si bool) string {
var base = 1024
pre := []string{"K", "M", "G", "T", "P", "E"}
var post = "B"
if si {
base = 1000
pre = []string{"k", "M", "G", "T", "P", "E"}
post = "iB"
}
if bytes < float64(base) {
return fmt.Sprintf("%.2f B", bytes)
}
exp := int(math.Log(bytes) / math.Log(float64(base)))
index := exp - 1
units := pre[index] + post
return fmt.Sprintf("%.2f %s", bytes/math.Pow(float64(base), float64(exp)), units)
} | go | func HumanBytes(bytes float64, si bool) string {
var base = 1024
pre := []string{"K", "M", "G", "T", "P", "E"}
var post = "B"
if si {
base = 1000
pre = []string{"k", "M", "G", "T", "P", "E"}
post = "iB"
}
if bytes < float64(base) {
return fmt.Sprintf("%.2f B", bytes)
}
exp := int(math.Log(bytes) / math.Log(float64(base)))
index := exp - 1
units := pre[index] + post
return fmt.Sprintf("%.2f %s", bytes/math.Pow(float64(base), float64(exp)), units)
} | [
"func",
"HumanBytes",
"(",
"bytes",
"float64",
",",
"si",
"bool",
")",
"string",
"{",
"var",
"base",
"=",
"1024",
"\n",
"pre",
":=",
"[",
"]",
"string",
"{",
"\"",
"\"",
",",
"\"",
"\"",
",",
"\"",
"\"",
",",
"\"",
"\"",
",",
"\"",
"\"",
",",
"\"",
"\"",
"}",
"\n",
"var",
"post",
"=",
"\"",
"\"",
"\n",
"if",
"si",
"{",
"base",
"=",
"1000",
"\n",
"pre",
"=",
"[",
"]",
"string",
"{",
"\"",
"\"",
",",
"\"",
"\"",
",",
"\"",
"\"",
",",
"\"",
"\"",
",",
"\"",
"\"",
",",
"\"",
"\"",
"}",
"\n",
"post",
"=",
"\"",
"\"",
"\n",
"}",
"\n",
"if",
"bytes",
"<",
"float64",
"(",
"base",
")",
"{",
"return",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"bytes",
")",
"\n",
"}",
"\n",
"exp",
":=",
"int",
"(",
"math",
".",
"Log",
"(",
"bytes",
")",
"/",
"math",
".",
"Log",
"(",
"float64",
"(",
"base",
")",
")",
")",
"\n",
"index",
":=",
"exp",
"-",
"1",
"\n",
"units",
":=",
"pre",
"[",
"index",
"]",
"+",
"post",
"\n",
"return",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"bytes",
"/",
"math",
".",
"Pow",
"(",
"float64",
"(",
"base",
")",
",",
"float64",
"(",
"exp",
")",
")",
",",
"units",
")",
"\n",
"}"
] | // HumanBytes formats bytes as a human readable string | [
"HumanBytes",
"formats",
"bytes",
"as",
"a",
"human",
"readable",
"string"
] | 36d30b0ba7aa260ae25b4f3d312b2a700106fd78 | https://github.com/nats-io/go-nats/blob/36d30b0ba7aa260ae25b4f3d312b2a700106fd78/bench/bench.go#L317-L333 | train |
nats-io/go-nats | bench/bench.go | MsgsPerClient | func MsgsPerClient(numMsgs, numClients int) []int {
var counts []int
if numClients == 0 || numMsgs == 0 {
return counts
}
counts = make([]int, numClients)
mc := numMsgs / numClients
for i := 0; i < numClients; i++ {
counts[i] = mc
}
extra := numMsgs % numClients
for i := 0; i < extra; i++ {
counts[i]++
}
return counts
} | go | func MsgsPerClient(numMsgs, numClients int) []int {
var counts []int
if numClients == 0 || numMsgs == 0 {
return counts
}
counts = make([]int, numClients)
mc := numMsgs / numClients
for i := 0; i < numClients; i++ {
counts[i] = mc
}
extra := numMsgs % numClients
for i := 0; i < extra; i++ {
counts[i]++
}
return counts
} | [
"func",
"MsgsPerClient",
"(",
"numMsgs",
",",
"numClients",
"int",
")",
"[",
"]",
"int",
"{",
"var",
"counts",
"[",
"]",
"int",
"\n",
"if",
"numClients",
"==",
"0",
"||",
"numMsgs",
"==",
"0",
"{",
"return",
"counts",
"\n",
"}",
"\n",
"counts",
"=",
"make",
"(",
"[",
"]",
"int",
",",
"numClients",
")",
"\n",
"mc",
":=",
"numMsgs",
"/",
"numClients",
"\n",
"for",
"i",
":=",
"0",
";",
"i",
"<",
"numClients",
";",
"i",
"++",
"{",
"counts",
"[",
"i",
"]",
"=",
"mc",
"\n",
"}",
"\n",
"extra",
":=",
"numMsgs",
"%",
"numClients",
"\n",
"for",
"i",
":=",
"0",
";",
"i",
"<",
"extra",
";",
"i",
"++",
"{",
"counts",
"[",
"i",
"]",
"++",
"\n",
"}",
"\n",
"return",
"counts",
"\n",
"}"
] | // MsgsPerClient divides the number of messages by the number of clients and tries to distribute them as evenly as possible | [
"MsgsPerClient",
"divides",
"the",
"number",
"of",
"messages",
"by",
"the",
"number",
"of",
"clients",
"and",
"tries",
"to",
"distribute",
"them",
"as",
"evenly",
"as",
"possible"
] | 36d30b0ba7aa260ae25b4f3d312b2a700106fd78 | https://github.com/nats-io/go-nats/blob/36d30b0ba7aa260ae25b4f3d312b2a700106fd78/bench/bench.go#L350-L365 | train |
nats-io/go-nats | timer.go | Get | func (tp *timerPool) Get(d time.Duration) *time.Timer {
if t, _ := tp.p.Get().(*time.Timer); t != nil {
t.Reset(d)
return t
}
return time.NewTimer(d)
} | go | func (tp *timerPool) Get(d time.Duration) *time.Timer {
if t, _ := tp.p.Get().(*time.Timer); t != nil {
t.Reset(d)
return t
}
return time.NewTimer(d)
} | [
"func",
"(",
"tp",
"*",
"timerPool",
")",
"Get",
"(",
"d",
"time",
".",
"Duration",
")",
"*",
"time",
".",
"Timer",
"{",
"if",
"t",
",",
"_",
":=",
"tp",
".",
"p",
".",
"Get",
"(",
")",
".",
"(",
"*",
"time",
".",
"Timer",
")",
";",
"t",
"!=",
"nil",
"{",
"t",
".",
"Reset",
"(",
"d",
")",
"\n",
"return",
"t",
"\n",
"}",
"\n\n",
"return",
"time",
".",
"NewTimer",
"(",
"d",
")",
"\n",
"}"
] | // Get returns a timer that completes after the given duration. | [
"Get",
"returns",
"a",
"timer",
"that",
"completes",
"after",
"the",
"given",
"duration",
"."
] | 36d30b0ba7aa260ae25b4f3d312b2a700106fd78 | https://github.com/nats-io/go-nats/blob/36d30b0ba7aa260ae25b4f3d312b2a700106fd78/timer.go#L31-L38 | train |
securego/gosec | rules/blacklist.go | NewBlacklistedImports | func NewBlacklistedImports(id string, conf gosec.Config, blacklist map[string]string) (gosec.Rule, []ast.Node) {
return &blacklistedImport{
MetaData: gosec.MetaData{
ID: id,
Severity: gosec.Medium,
Confidence: gosec.High,
},
Blacklisted: blacklist,
}, []ast.Node{(*ast.ImportSpec)(nil)}
} | go | func NewBlacklistedImports(id string, conf gosec.Config, blacklist map[string]string) (gosec.Rule, []ast.Node) {
return &blacklistedImport{
MetaData: gosec.MetaData{
ID: id,
Severity: gosec.Medium,
Confidence: gosec.High,
},
Blacklisted: blacklist,
}, []ast.Node{(*ast.ImportSpec)(nil)}
} | [
"func",
"NewBlacklistedImports",
"(",
"id",
"string",
",",
"conf",
"gosec",
".",
"Config",
",",
"blacklist",
"map",
"[",
"string",
"]",
"string",
")",
"(",
"gosec",
".",
"Rule",
",",
"[",
"]",
"ast",
".",
"Node",
")",
"{",
"return",
"&",
"blacklistedImport",
"{",
"MetaData",
":",
"gosec",
".",
"MetaData",
"{",
"ID",
":",
"id",
",",
"Severity",
":",
"gosec",
".",
"Medium",
",",
"Confidence",
":",
"gosec",
".",
"High",
",",
"}",
",",
"Blacklisted",
":",
"blacklist",
",",
"}",
",",
"[",
"]",
"ast",
".",
"Node",
"{",
"(",
"*",
"ast",
".",
"ImportSpec",
")",
"(",
"nil",
")",
"}",
"\n",
"}"
] | // NewBlacklistedImports reports when a blacklisted import is being used.
// Typically when a deprecated technology is being used. | [
"NewBlacklistedImports",
"reports",
"when",
"a",
"blacklisted",
"import",
"is",
"being",
"used",
".",
"Typically",
"when",
"a",
"deprecated",
"technology",
"is",
"being",
"used",
"."
] | 29cec138dcc94f347e6d41550a5223571dc7d6cf | https://github.com/securego/gosec/blob/29cec138dcc94f347e6d41550a5223571dc7d6cf/rules/blacklist.go#L50-L59 | train |
securego/gosec | rules/blacklist.go | NewBlacklistedImportRC4 | func NewBlacklistedImportRC4(id string, conf gosec.Config) (gosec.Rule, []ast.Node) {
return NewBlacklistedImports(id, conf, map[string]string{
"crypto/rc4": "Blacklisted import crypto/rc4: weak cryptographic primitive",
})
} | go | func NewBlacklistedImportRC4(id string, conf gosec.Config) (gosec.Rule, []ast.Node) {
return NewBlacklistedImports(id, conf, map[string]string{
"crypto/rc4": "Blacklisted import crypto/rc4: weak cryptographic primitive",
})
} | [
"func",
"NewBlacklistedImportRC4",
"(",
"id",
"string",
",",
"conf",
"gosec",
".",
"Config",
")",
"(",
"gosec",
".",
"Rule",
",",
"[",
"]",
"ast",
".",
"Node",
")",
"{",
"return",
"NewBlacklistedImports",
"(",
"id",
",",
"conf",
",",
"map",
"[",
"string",
"]",
"string",
"{",
"\"",
"\"",
":",
"\"",
"\"",
",",
"}",
")",
"\n",
"}"
] | // NewBlacklistedImportRC4 fails if DES is imported | [
"NewBlacklistedImportRC4",
"fails",
"if",
"DES",
"is",
"imported"
] | 29cec138dcc94f347e6d41550a5223571dc7d6cf | https://github.com/securego/gosec/blob/29cec138dcc94f347e6d41550a5223571dc7d6cf/rules/blacklist.go#L76-L80 | train |
securego/gosec | rules/hardcoded_credentials.go | NewHardcodedCredentials | func NewHardcodedCredentials(id string, conf gosec.Config) (gosec.Rule, []ast.Node) {
pattern := `(?i)passwd|pass|password|pwd|secret|token`
entropyThreshold := 80.0
perCharThreshold := 3.0
ignoreEntropy := false
var truncateString = 16
if val, ok := conf["G101"]; ok {
conf := val.(map[string]string)
if configPattern, ok := conf["pattern"]; ok {
pattern = configPattern
}
if configIgnoreEntropy, ok := conf["ignore_entropy"]; ok {
if parsedBool, err := strconv.ParseBool(configIgnoreEntropy); err == nil {
ignoreEntropy = parsedBool
}
}
if configEntropyThreshold, ok := conf["entropy_threshold"]; ok {
if parsedNum, err := strconv.ParseFloat(configEntropyThreshold, 64); err == nil {
entropyThreshold = parsedNum
}
}
if configCharThreshold, ok := conf["per_char_threshold"]; ok {
if parsedNum, err := strconv.ParseFloat(configCharThreshold, 64); err == nil {
perCharThreshold = parsedNum
}
}
if configTruncate, ok := conf["truncate"]; ok {
if parsedInt, err := strconv.Atoi(configTruncate); err == nil {
truncateString = parsedInt
}
}
}
return &credentials{
pattern: regexp.MustCompile(pattern),
entropyThreshold: entropyThreshold,
perCharThreshold: perCharThreshold,
ignoreEntropy: ignoreEntropy,
truncate: truncateString,
MetaData: gosec.MetaData{
ID: id,
What: "Potential hardcoded credentials",
Confidence: gosec.Low,
Severity: gosec.High,
},
}, []ast.Node{(*ast.AssignStmt)(nil), (*ast.ValueSpec)(nil)}
} | go | func NewHardcodedCredentials(id string, conf gosec.Config) (gosec.Rule, []ast.Node) {
pattern := `(?i)passwd|pass|password|pwd|secret|token`
entropyThreshold := 80.0
perCharThreshold := 3.0
ignoreEntropy := false
var truncateString = 16
if val, ok := conf["G101"]; ok {
conf := val.(map[string]string)
if configPattern, ok := conf["pattern"]; ok {
pattern = configPattern
}
if configIgnoreEntropy, ok := conf["ignore_entropy"]; ok {
if parsedBool, err := strconv.ParseBool(configIgnoreEntropy); err == nil {
ignoreEntropy = parsedBool
}
}
if configEntropyThreshold, ok := conf["entropy_threshold"]; ok {
if parsedNum, err := strconv.ParseFloat(configEntropyThreshold, 64); err == nil {
entropyThreshold = parsedNum
}
}
if configCharThreshold, ok := conf["per_char_threshold"]; ok {
if parsedNum, err := strconv.ParseFloat(configCharThreshold, 64); err == nil {
perCharThreshold = parsedNum
}
}
if configTruncate, ok := conf["truncate"]; ok {
if parsedInt, err := strconv.Atoi(configTruncate); err == nil {
truncateString = parsedInt
}
}
}
return &credentials{
pattern: regexp.MustCompile(pattern),
entropyThreshold: entropyThreshold,
perCharThreshold: perCharThreshold,
ignoreEntropy: ignoreEntropy,
truncate: truncateString,
MetaData: gosec.MetaData{
ID: id,
What: "Potential hardcoded credentials",
Confidence: gosec.Low,
Severity: gosec.High,
},
}, []ast.Node{(*ast.AssignStmt)(nil), (*ast.ValueSpec)(nil)}
} | [
"func",
"NewHardcodedCredentials",
"(",
"id",
"string",
",",
"conf",
"gosec",
".",
"Config",
")",
"(",
"gosec",
".",
"Rule",
",",
"[",
"]",
"ast",
".",
"Node",
")",
"{",
"pattern",
":=",
"`(?i)passwd|pass|password|pwd|secret|token`",
"\n",
"entropyThreshold",
":=",
"80.0",
"\n",
"perCharThreshold",
":=",
"3.0",
"\n",
"ignoreEntropy",
":=",
"false",
"\n",
"var",
"truncateString",
"=",
"16",
"\n",
"if",
"val",
",",
"ok",
":=",
"conf",
"[",
"\"",
"\"",
"]",
";",
"ok",
"{",
"conf",
":=",
"val",
".",
"(",
"map",
"[",
"string",
"]",
"string",
")",
"\n",
"if",
"configPattern",
",",
"ok",
":=",
"conf",
"[",
"\"",
"\"",
"]",
";",
"ok",
"{",
"pattern",
"=",
"configPattern",
"\n",
"}",
"\n",
"if",
"configIgnoreEntropy",
",",
"ok",
":=",
"conf",
"[",
"\"",
"\"",
"]",
";",
"ok",
"{",
"if",
"parsedBool",
",",
"err",
":=",
"strconv",
".",
"ParseBool",
"(",
"configIgnoreEntropy",
")",
";",
"err",
"==",
"nil",
"{",
"ignoreEntropy",
"=",
"parsedBool",
"\n",
"}",
"\n",
"}",
"\n",
"if",
"configEntropyThreshold",
",",
"ok",
":=",
"conf",
"[",
"\"",
"\"",
"]",
";",
"ok",
"{",
"if",
"parsedNum",
",",
"err",
":=",
"strconv",
".",
"ParseFloat",
"(",
"configEntropyThreshold",
",",
"64",
")",
";",
"err",
"==",
"nil",
"{",
"entropyThreshold",
"=",
"parsedNum",
"\n",
"}",
"\n",
"}",
"\n",
"if",
"configCharThreshold",
",",
"ok",
":=",
"conf",
"[",
"\"",
"\"",
"]",
";",
"ok",
"{",
"if",
"parsedNum",
",",
"err",
":=",
"strconv",
".",
"ParseFloat",
"(",
"configCharThreshold",
",",
"64",
")",
";",
"err",
"==",
"nil",
"{",
"perCharThreshold",
"=",
"parsedNum",
"\n",
"}",
"\n",
"}",
"\n",
"if",
"configTruncate",
",",
"ok",
":=",
"conf",
"[",
"\"",
"\"",
"]",
";",
"ok",
"{",
"if",
"parsedInt",
",",
"err",
":=",
"strconv",
".",
"Atoi",
"(",
"configTruncate",
")",
";",
"err",
"==",
"nil",
"{",
"truncateString",
"=",
"parsedInt",
"\n",
"}",
"\n",
"}",
"\n",
"}",
"\n\n",
"return",
"&",
"credentials",
"{",
"pattern",
":",
"regexp",
".",
"MustCompile",
"(",
"pattern",
")",
",",
"entropyThreshold",
":",
"entropyThreshold",
",",
"perCharThreshold",
":",
"perCharThreshold",
",",
"ignoreEntropy",
":",
"ignoreEntropy",
",",
"truncate",
":",
"truncateString",
",",
"MetaData",
":",
"gosec",
".",
"MetaData",
"{",
"ID",
":",
"id",
",",
"What",
":",
"\"",
"\"",
",",
"Confidence",
":",
"gosec",
".",
"Low",
",",
"Severity",
":",
"gosec",
".",
"High",
",",
"}",
",",
"}",
",",
"[",
"]",
"ast",
".",
"Node",
"{",
"(",
"*",
"ast",
".",
"AssignStmt",
")",
"(",
"nil",
")",
",",
"(",
"*",
"ast",
".",
"ValueSpec",
")",
"(",
"nil",
")",
"}",
"\n",
"}"
] | // NewHardcodedCredentials attempts to find high entropy string constants being
// assigned to variables that appear to be related to credentials. | [
"NewHardcodedCredentials",
"attempts",
"to",
"find",
"high",
"entropy",
"string",
"constants",
"being",
"assigned",
"to",
"variables",
"that",
"appear",
"to",
"be",
"related",
"to",
"credentials",
"."
] | 29cec138dcc94f347e6d41550a5223571dc7d6cf | https://github.com/securego/gosec/blob/29cec138dcc94f347e6d41550a5223571dc7d6cf/rules/hardcoded_credentials.go#L101-L147 | train |
securego/gosec | rules/bind.go | NewBindsToAllNetworkInterfaces | func NewBindsToAllNetworkInterfaces(id string, conf gosec.Config) (gosec.Rule, []ast.Node) {
calls := gosec.NewCallList()
calls.Add("net", "Listen")
calls.Add("crypto/tls", "Listen")
return &bindsToAllNetworkInterfaces{
calls: calls,
pattern: regexp.MustCompile(`^(0.0.0.0|:).*$`),
MetaData: gosec.MetaData{
ID: id,
Severity: gosec.Medium,
Confidence: gosec.High,
What: "Binds to all network interfaces",
},
}, []ast.Node{(*ast.CallExpr)(nil)}
} | go | func NewBindsToAllNetworkInterfaces(id string, conf gosec.Config) (gosec.Rule, []ast.Node) {
calls := gosec.NewCallList()
calls.Add("net", "Listen")
calls.Add("crypto/tls", "Listen")
return &bindsToAllNetworkInterfaces{
calls: calls,
pattern: regexp.MustCompile(`^(0.0.0.0|:).*$`),
MetaData: gosec.MetaData{
ID: id,
Severity: gosec.Medium,
Confidence: gosec.High,
What: "Binds to all network interfaces",
},
}, []ast.Node{(*ast.CallExpr)(nil)}
} | [
"func",
"NewBindsToAllNetworkInterfaces",
"(",
"id",
"string",
",",
"conf",
"gosec",
".",
"Config",
")",
"(",
"gosec",
".",
"Rule",
",",
"[",
"]",
"ast",
".",
"Node",
")",
"{",
"calls",
":=",
"gosec",
".",
"NewCallList",
"(",
")",
"\n",
"calls",
".",
"Add",
"(",
"\"",
"\"",
",",
"\"",
"\"",
")",
"\n",
"calls",
".",
"Add",
"(",
"\"",
"\"",
",",
"\"",
"\"",
")",
"\n",
"return",
"&",
"bindsToAllNetworkInterfaces",
"{",
"calls",
":",
"calls",
",",
"pattern",
":",
"regexp",
".",
"MustCompile",
"(",
"`^(0.0.0.0|:).*$`",
")",
",",
"MetaData",
":",
"gosec",
".",
"MetaData",
"{",
"ID",
":",
"id",
",",
"Severity",
":",
"gosec",
".",
"Medium",
",",
"Confidence",
":",
"gosec",
".",
"High",
",",
"What",
":",
"\"",
"\"",
",",
"}",
",",
"}",
",",
"[",
"]",
"ast",
".",
"Node",
"{",
"(",
"*",
"ast",
".",
"CallExpr",
")",
"(",
"nil",
")",
"}",
"\n",
"}"
] | // NewBindsToAllNetworkInterfaces detects socket connections that are setup to
// listen on all network interfaces. | [
"NewBindsToAllNetworkInterfaces",
"detects",
"socket",
"connections",
"that",
"are",
"setup",
"to",
"listen",
"on",
"all",
"network",
"interfaces",
"."
] | 29cec138dcc94f347e6d41550a5223571dc7d6cf | https://github.com/securego/gosec/blob/29cec138dcc94f347e6d41550a5223571dc7d6cf/rules/bind.go#L69-L83 | train |
securego/gosec | rules/fileperms.go | NewFilePerms | func NewFilePerms(id string, conf gosec.Config) (gosec.Rule, []ast.Node) {
mode := getConfiguredMode(conf, "G302", 0600)
return &filePermissions{
mode: mode,
pkg: "os",
calls: []string{"OpenFile", "Chmod"},
MetaData: gosec.MetaData{
ID: id,
Severity: gosec.Medium,
Confidence: gosec.High,
What: fmt.Sprintf("Expect file permissions to be %#o or less", mode),
},
}, []ast.Node{(*ast.CallExpr)(nil)}
} | go | func NewFilePerms(id string, conf gosec.Config) (gosec.Rule, []ast.Node) {
mode := getConfiguredMode(conf, "G302", 0600)
return &filePermissions{
mode: mode,
pkg: "os",
calls: []string{"OpenFile", "Chmod"},
MetaData: gosec.MetaData{
ID: id,
Severity: gosec.Medium,
Confidence: gosec.High,
What: fmt.Sprintf("Expect file permissions to be %#o or less", mode),
},
}, []ast.Node{(*ast.CallExpr)(nil)}
} | [
"func",
"NewFilePerms",
"(",
"id",
"string",
",",
"conf",
"gosec",
".",
"Config",
")",
"(",
"gosec",
".",
"Rule",
",",
"[",
"]",
"ast",
".",
"Node",
")",
"{",
"mode",
":=",
"getConfiguredMode",
"(",
"conf",
",",
"\"",
"\"",
",",
"0600",
")",
"\n",
"return",
"&",
"filePermissions",
"{",
"mode",
":",
"mode",
",",
"pkg",
":",
"\"",
"\"",
",",
"calls",
":",
"[",
"]",
"string",
"{",
"\"",
"\"",
",",
"\"",
"\"",
"}",
",",
"MetaData",
":",
"gosec",
".",
"MetaData",
"{",
"ID",
":",
"id",
",",
"Severity",
":",
"gosec",
".",
"Medium",
",",
"Confidence",
":",
"gosec",
".",
"High",
",",
"What",
":",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"mode",
")",
",",
"}",
",",
"}",
",",
"[",
"]",
"ast",
".",
"Node",
"{",
"(",
"*",
"ast",
".",
"CallExpr",
")",
"(",
"nil",
")",
"}",
"\n",
"}"
] | // NewFilePerms creates a rule to detect file creation with a more permissive than configured
// permission mask. | [
"NewFilePerms",
"creates",
"a",
"rule",
"to",
"detect",
"file",
"creation",
"with",
"a",
"more",
"permissive",
"than",
"configured",
"permission",
"mask",
"."
] | 29cec138dcc94f347e6d41550a5223571dc7d6cf | https://github.com/securego/gosec/blob/29cec138dcc94f347e6d41550a5223571dc7d6cf/rules/fileperms.go#L65-L78 | train |
securego/gosec | rules/rsa.go | NewWeakKeyStrength | func NewWeakKeyStrength(id string, conf gosec.Config) (gosec.Rule, []ast.Node) {
calls := gosec.NewCallList()
calls.Add("crypto/rsa", "GenerateKey")
bits := 2048
return &weakKeyStrength{
calls: calls,
bits: bits,
MetaData: gosec.MetaData{
ID: id,
Severity: gosec.Medium,
Confidence: gosec.High,
What: fmt.Sprintf("RSA keys should be at least %d bits", bits),
},
}, []ast.Node{(*ast.CallExpr)(nil)}
} | go | func NewWeakKeyStrength(id string, conf gosec.Config) (gosec.Rule, []ast.Node) {
calls := gosec.NewCallList()
calls.Add("crypto/rsa", "GenerateKey")
bits := 2048
return &weakKeyStrength{
calls: calls,
bits: bits,
MetaData: gosec.MetaData{
ID: id,
Severity: gosec.Medium,
Confidence: gosec.High,
What: fmt.Sprintf("RSA keys should be at least %d bits", bits),
},
}, []ast.Node{(*ast.CallExpr)(nil)}
} | [
"func",
"NewWeakKeyStrength",
"(",
"id",
"string",
",",
"conf",
"gosec",
".",
"Config",
")",
"(",
"gosec",
".",
"Rule",
",",
"[",
"]",
"ast",
".",
"Node",
")",
"{",
"calls",
":=",
"gosec",
".",
"NewCallList",
"(",
")",
"\n",
"calls",
".",
"Add",
"(",
"\"",
"\"",
",",
"\"",
"\"",
")",
"\n",
"bits",
":=",
"2048",
"\n",
"return",
"&",
"weakKeyStrength",
"{",
"calls",
":",
"calls",
",",
"bits",
":",
"bits",
",",
"MetaData",
":",
"gosec",
".",
"MetaData",
"{",
"ID",
":",
"id",
",",
"Severity",
":",
"gosec",
".",
"Medium",
",",
"Confidence",
":",
"gosec",
".",
"High",
",",
"What",
":",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"bits",
")",
",",
"}",
",",
"}",
",",
"[",
"]",
"ast",
".",
"Node",
"{",
"(",
"*",
"ast",
".",
"CallExpr",
")",
"(",
"nil",
")",
"}",
"\n",
"}"
] | // NewWeakKeyStrength builds a rule that detects RSA keys < 2048 bits | [
"NewWeakKeyStrength",
"builds",
"a",
"rule",
"that",
"detects",
"RSA",
"keys",
"<",
"2048",
"bits"
] | 29cec138dcc94f347e6d41550a5223571dc7d6cf | https://github.com/securego/gosec/blob/29cec138dcc94f347e6d41550a5223571dc7d6cf/rules/rsa.go#L44-L58 | train |
securego/gosec | rules/subproc.go | NewSubproc | func NewSubproc(id string, conf gosec.Config) (gosec.Rule, []ast.Node) {
rule := &subprocess{gosec.MetaData{ID: id}, gosec.NewCallList()}
rule.Add("os/exec", "Command")
rule.Add("os/exec", "CommandContext")
rule.Add("syscall", "Exec")
return rule, []ast.Node{(*ast.CallExpr)(nil)}
} | go | func NewSubproc(id string, conf gosec.Config) (gosec.Rule, []ast.Node) {
rule := &subprocess{gosec.MetaData{ID: id}, gosec.NewCallList()}
rule.Add("os/exec", "Command")
rule.Add("os/exec", "CommandContext")
rule.Add("syscall", "Exec")
return rule, []ast.Node{(*ast.CallExpr)(nil)}
} | [
"func",
"NewSubproc",
"(",
"id",
"string",
",",
"conf",
"gosec",
".",
"Config",
")",
"(",
"gosec",
".",
"Rule",
",",
"[",
"]",
"ast",
".",
"Node",
")",
"{",
"rule",
":=",
"&",
"subprocess",
"{",
"gosec",
".",
"MetaData",
"{",
"ID",
":",
"id",
"}",
",",
"gosec",
".",
"NewCallList",
"(",
")",
"}",
"\n",
"rule",
".",
"Add",
"(",
"\"",
"\"",
",",
"\"",
"\"",
")",
"\n",
"rule",
".",
"Add",
"(",
"\"",
"\"",
",",
"\"",
"\"",
")",
"\n",
"rule",
".",
"Add",
"(",
"\"",
"\"",
",",
"\"",
"\"",
")",
"\n",
"return",
"rule",
",",
"[",
"]",
"ast",
".",
"Node",
"{",
"(",
"*",
"ast",
".",
"CallExpr",
")",
"(",
"nil",
")",
"}",
"\n",
"}"
] | // NewSubproc detects cases where we are forking out to an external process | [
"NewSubproc",
"detects",
"cases",
"where",
"we",
"are",
"forking",
"out",
"to",
"an",
"external",
"process"
] | 29cec138dcc94f347e6d41550a5223571dc7d6cf | https://github.com/securego/gosec/blob/29cec138dcc94f347e6d41550a5223571dc7d6cf/rules/subproc.go#L58-L64 | train |
securego/gosec | rules/archive.go | Match | func (a *archive) Match(n ast.Node, c *gosec.Context) (*gosec.Issue, error) {
if node := a.calls.ContainsCallExpr(n, c, false); node != nil {
for _, arg := range node.Args {
var argType types.Type
if selector, ok := arg.(*ast.SelectorExpr); ok {
argType = c.Info.TypeOf(selector.X)
} else if ident, ok := arg.(*ast.Ident); ok {
if ident.Obj != nil && ident.Obj.Kind == ast.Var {
decl := ident.Obj.Decl
if assign, ok := decl.(*ast.AssignStmt); ok {
if selector, ok := assign.Rhs[0].(*ast.SelectorExpr); ok {
argType = c.Info.TypeOf(selector.X)
}
}
}
}
if argType != nil && argType.String() == a.argType {
return gosec.NewIssue(c, n, a.ID(), a.What, a.Severity, a.Confidence), nil
}
}
}
return nil, nil
} | go | func (a *archive) Match(n ast.Node, c *gosec.Context) (*gosec.Issue, error) {
if node := a.calls.ContainsCallExpr(n, c, false); node != nil {
for _, arg := range node.Args {
var argType types.Type
if selector, ok := arg.(*ast.SelectorExpr); ok {
argType = c.Info.TypeOf(selector.X)
} else if ident, ok := arg.(*ast.Ident); ok {
if ident.Obj != nil && ident.Obj.Kind == ast.Var {
decl := ident.Obj.Decl
if assign, ok := decl.(*ast.AssignStmt); ok {
if selector, ok := assign.Rhs[0].(*ast.SelectorExpr); ok {
argType = c.Info.TypeOf(selector.X)
}
}
}
}
if argType != nil && argType.String() == a.argType {
return gosec.NewIssue(c, n, a.ID(), a.What, a.Severity, a.Confidence), nil
}
}
}
return nil, nil
} | [
"func",
"(",
"a",
"*",
"archive",
")",
"Match",
"(",
"n",
"ast",
".",
"Node",
",",
"c",
"*",
"gosec",
".",
"Context",
")",
"(",
"*",
"gosec",
".",
"Issue",
",",
"error",
")",
"{",
"if",
"node",
":=",
"a",
".",
"calls",
".",
"ContainsCallExpr",
"(",
"n",
",",
"c",
",",
"false",
")",
";",
"node",
"!=",
"nil",
"{",
"for",
"_",
",",
"arg",
":=",
"range",
"node",
".",
"Args",
"{",
"var",
"argType",
"types",
".",
"Type",
"\n",
"if",
"selector",
",",
"ok",
":=",
"arg",
".",
"(",
"*",
"ast",
".",
"SelectorExpr",
")",
";",
"ok",
"{",
"argType",
"=",
"c",
".",
"Info",
".",
"TypeOf",
"(",
"selector",
".",
"X",
")",
"\n",
"}",
"else",
"if",
"ident",
",",
"ok",
":=",
"arg",
".",
"(",
"*",
"ast",
".",
"Ident",
")",
";",
"ok",
"{",
"if",
"ident",
".",
"Obj",
"!=",
"nil",
"&&",
"ident",
".",
"Obj",
".",
"Kind",
"==",
"ast",
".",
"Var",
"{",
"decl",
":=",
"ident",
".",
"Obj",
".",
"Decl",
"\n",
"if",
"assign",
",",
"ok",
":=",
"decl",
".",
"(",
"*",
"ast",
".",
"AssignStmt",
")",
";",
"ok",
"{",
"if",
"selector",
",",
"ok",
":=",
"assign",
".",
"Rhs",
"[",
"0",
"]",
".",
"(",
"*",
"ast",
".",
"SelectorExpr",
")",
";",
"ok",
"{",
"argType",
"=",
"c",
".",
"Info",
".",
"TypeOf",
"(",
"selector",
".",
"X",
")",
"\n",
"}",
"\n",
"}",
"\n",
"}",
"\n",
"}",
"\n\n",
"if",
"argType",
"!=",
"nil",
"&&",
"argType",
".",
"String",
"(",
")",
"==",
"a",
".",
"argType",
"{",
"return",
"gosec",
".",
"NewIssue",
"(",
"c",
",",
"n",
",",
"a",
".",
"ID",
"(",
")",
",",
"a",
".",
"What",
",",
"a",
".",
"Severity",
",",
"a",
".",
"Confidence",
")",
",",
"nil",
"\n",
"}",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"nil",
",",
"nil",
"\n",
"}"
] | // Match inspects AST nodes to determine if the filepath.Joins uses any argument derived from type zip.File | [
"Match",
"inspects",
"AST",
"nodes",
"to",
"determine",
"if",
"the",
"filepath",
".",
"Joins",
"uses",
"any",
"argument",
"derived",
"from",
"type",
"zip",
".",
"File"
] | 29cec138dcc94f347e6d41550a5223571dc7d6cf | https://github.com/securego/gosec/blob/29cec138dcc94f347e6d41550a5223571dc7d6cf/rules/archive.go#L21-L44 | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.