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 |
---|---|---|---|---|---|---|---|---|---|---|---|
xtaci/kcp-go | crypt.go | encrypt | func encrypt(block cipher.Block, dst, src, buf []byte) {
switch block.BlockSize() {
case 8:
encrypt8(block, dst, src, buf)
case 16:
encrypt16(block, dst, src, buf)
default:
encryptVariant(block, dst, src, buf)
}
} | go | func encrypt(block cipher.Block, dst, src, buf []byte) {
switch block.BlockSize() {
case 8:
encrypt8(block, dst, src, buf)
case 16:
encrypt16(block, dst, src, buf)
default:
encryptVariant(block, dst, src, buf)
}
} | [
"func",
"encrypt",
"(",
"block",
"cipher",
".",
"Block",
",",
"dst",
",",
"src",
",",
"buf",
"[",
"]",
"byte",
")",
"{",
"switch",
"block",
".",
"BlockSize",
"(",
")",
"{",
"case",
"8",
":",
"encrypt8",
"(",
"block",
",",
"dst",
",",
"src",
",",
"buf",
")",
"\n",
"case",
"16",
":",
"encrypt16",
"(",
"block",
",",
"dst",
",",
"src",
",",
"buf",
")",
"\n",
"default",
":",
"encryptVariant",
"(",
"block",
",",
"dst",
",",
"src",
",",
"buf",
")",
"\n",
"}",
"\n",
"}"
] | // packet encryption with local CFB mode | [
"packet",
"encryption",
"with",
"local",
"CFB",
"mode"
] | 88b8a1475ba14b58f41457c9c89b5ccd919f1c24 | https://github.com/xtaci/kcp-go/blob/88b8a1475ba14b58f41457c9c89b5ccd919f1c24/crypt.go#L244-L253 | train |
hashicorp/yamux | addr.go | LocalAddr | func (s *Session) LocalAddr() net.Addr {
addr, ok := s.conn.(hasAddr)
if !ok {
return &yamuxAddr{"local"}
}
return addr.LocalAddr()
} | go | func (s *Session) LocalAddr() net.Addr {
addr, ok := s.conn.(hasAddr)
if !ok {
return &yamuxAddr{"local"}
}
return addr.LocalAddr()
} | [
"func",
"(",
"s",
"*",
"Session",
")",
"LocalAddr",
"(",
")",
"net",
".",
"Addr",
"{",
"addr",
",",
"ok",
":=",
"s",
".",
"conn",
".",
"(",
"hasAddr",
")",
"\n",
"if",
"!",
"ok",
"{",
"return",
"&",
"yamuxAddr",
"{",
"\"",
"\"",
"}",
"\n",
"}",
"\n",
"return",
"addr",
".",
"LocalAddr",
"(",
")",
"\n",
"}"
] | // LocalAddr is used to get the local address of the
// underlying connection. | [
"LocalAddr",
"is",
"used",
"to",
"get",
"the",
"local",
"address",
"of",
"the",
"underlying",
"connection",
"."
] | 2f1d1f20f75d5404f53b9edf6b53ed5505508675 | https://github.com/hashicorp/yamux/blob/2f1d1f20f75d5404f53b9edf6b53ed5505508675/addr.go#L34-L40 | train |
hashicorp/yamux | stream.go | newStream | func newStream(session *Session, id uint32, state streamState) *Stream {
s := &Stream{
id: id,
session: session,
state: state,
controlHdr: header(make([]byte, headerSize)),
controlErr: make(chan error, 1),
sendHdr: header(make([]byte, headerSize)),
sendErr: make(chan error, 1),
recvWindow: initialStreamWindow,
sendWindow: initialStreamWindow,
recvNotifyCh: make(chan struct{}, 1),
sendNotifyCh: make(chan struct{}, 1),
}
s.readDeadline.Store(time.Time{})
s.writeDeadline.Store(time.Time{})
return s
} | go | func newStream(session *Session, id uint32, state streamState) *Stream {
s := &Stream{
id: id,
session: session,
state: state,
controlHdr: header(make([]byte, headerSize)),
controlErr: make(chan error, 1),
sendHdr: header(make([]byte, headerSize)),
sendErr: make(chan error, 1),
recvWindow: initialStreamWindow,
sendWindow: initialStreamWindow,
recvNotifyCh: make(chan struct{}, 1),
sendNotifyCh: make(chan struct{}, 1),
}
s.readDeadline.Store(time.Time{})
s.writeDeadline.Store(time.Time{})
return s
} | [
"func",
"newStream",
"(",
"session",
"*",
"Session",
",",
"id",
"uint32",
",",
"state",
"streamState",
")",
"*",
"Stream",
"{",
"s",
":=",
"&",
"Stream",
"{",
"id",
":",
"id",
",",
"session",
":",
"session",
",",
"state",
":",
"state",
",",
"controlHdr",
":",
"header",
"(",
"make",
"(",
"[",
"]",
"byte",
",",
"headerSize",
")",
")",
",",
"controlErr",
":",
"make",
"(",
"chan",
"error",
",",
"1",
")",
",",
"sendHdr",
":",
"header",
"(",
"make",
"(",
"[",
"]",
"byte",
",",
"headerSize",
")",
")",
",",
"sendErr",
":",
"make",
"(",
"chan",
"error",
",",
"1",
")",
",",
"recvWindow",
":",
"initialStreamWindow",
",",
"sendWindow",
":",
"initialStreamWindow",
",",
"recvNotifyCh",
":",
"make",
"(",
"chan",
"struct",
"{",
"}",
",",
"1",
")",
",",
"sendNotifyCh",
":",
"make",
"(",
"chan",
"struct",
"{",
"}",
",",
"1",
")",
",",
"}",
"\n",
"s",
".",
"readDeadline",
".",
"Store",
"(",
"time",
".",
"Time",
"{",
"}",
")",
"\n",
"s",
".",
"writeDeadline",
".",
"Store",
"(",
"time",
".",
"Time",
"{",
"}",
")",
"\n",
"return",
"s",
"\n",
"}"
] | // newStream is used to construct a new stream within
// a given session for an ID | [
"newStream",
"is",
"used",
"to",
"construct",
"a",
"new",
"stream",
"within",
"a",
"given",
"session",
"for",
"an",
"ID"
] | 2f1d1f20f75d5404f53b9edf6b53ed5505508675 | https://github.com/hashicorp/yamux/blob/2f1d1f20f75d5404f53b9edf6b53ed5505508675/stream.go#L56-L73 | train |
hashicorp/yamux | stream.go | Read | func (s *Stream) Read(b []byte) (n int, err error) {
defer asyncNotify(s.recvNotifyCh)
START:
s.stateLock.Lock()
switch s.state {
case streamLocalClose:
fallthrough
case streamRemoteClose:
fallthrough
case streamClosed:
s.recvLock.Lock()
if s.recvBuf == nil || s.recvBuf.Len() == 0 {
s.recvLock.Unlock()
s.stateLock.Unlock()
return 0, io.EOF
}
s.recvLock.Unlock()
case streamReset:
s.stateLock.Unlock()
return 0, ErrConnectionReset
}
s.stateLock.Unlock()
// If there is no data available, block
s.recvLock.Lock()
if s.recvBuf == nil || s.recvBuf.Len() == 0 {
s.recvLock.Unlock()
goto WAIT
}
// Read any bytes
n, _ = s.recvBuf.Read(b)
s.recvLock.Unlock()
// Send a window update potentially
err = s.sendWindowUpdate()
return n, err
WAIT:
var timeout <-chan time.Time
var timer *time.Timer
readDeadline := s.readDeadline.Load().(time.Time)
if !readDeadline.IsZero() {
delay := readDeadline.Sub(time.Now())
timer = time.NewTimer(delay)
timeout = timer.C
}
select {
case <-s.recvNotifyCh:
if timer != nil {
timer.Stop()
}
goto START
case <-timeout:
return 0, ErrTimeout
}
} | go | func (s *Stream) Read(b []byte) (n int, err error) {
defer asyncNotify(s.recvNotifyCh)
START:
s.stateLock.Lock()
switch s.state {
case streamLocalClose:
fallthrough
case streamRemoteClose:
fallthrough
case streamClosed:
s.recvLock.Lock()
if s.recvBuf == nil || s.recvBuf.Len() == 0 {
s.recvLock.Unlock()
s.stateLock.Unlock()
return 0, io.EOF
}
s.recvLock.Unlock()
case streamReset:
s.stateLock.Unlock()
return 0, ErrConnectionReset
}
s.stateLock.Unlock()
// If there is no data available, block
s.recvLock.Lock()
if s.recvBuf == nil || s.recvBuf.Len() == 0 {
s.recvLock.Unlock()
goto WAIT
}
// Read any bytes
n, _ = s.recvBuf.Read(b)
s.recvLock.Unlock()
// Send a window update potentially
err = s.sendWindowUpdate()
return n, err
WAIT:
var timeout <-chan time.Time
var timer *time.Timer
readDeadline := s.readDeadline.Load().(time.Time)
if !readDeadline.IsZero() {
delay := readDeadline.Sub(time.Now())
timer = time.NewTimer(delay)
timeout = timer.C
}
select {
case <-s.recvNotifyCh:
if timer != nil {
timer.Stop()
}
goto START
case <-timeout:
return 0, ErrTimeout
}
} | [
"func",
"(",
"s",
"*",
"Stream",
")",
"Read",
"(",
"b",
"[",
"]",
"byte",
")",
"(",
"n",
"int",
",",
"err",
"error",
")",
"{",
"defer",
"asyncNotify",
"(",
"s",
".",
"recvNotifyCh",
")",
"\n",
"START",
":",
"s",
".",
"stateLock",
".",
"Lock",
"(",
")",
"\n",
"switch",
"s",
".",
"state",
"{",
"case",
"streamLocalClose",
":",
"fallthrough",
"\n",
"case",
"streamRemoteClose",
":",
"fallthrough",
"\n",
"case",
"streamClosed",
":",
"s",
".",
"recvLock",
".",
"Lock",
"(",
")",
"\n",
"if",
"s",
".",
"recvBuf",
"==",
"nil",
"||",
"s",
".",
"recvBuf",
".",
"Len",
"(",
")",
"==",
"0",
"{",
"s",
".",
"recvLock",
".",
"Unlock",
"(",
")",
"\n",
"s",
".",
"stateLock",
".",
"Unlock",
"(",
")",
"\n",
"return",
"0",
",",
"io",
".",
"EOF",
"\n",
"}",
"\n",
"s",
".",
"recvLock",
".",
"Unlock",
"(",
")",
"\n",
"case",
"streamReset",
":",
"s",
".",
"stateLock",
".",
"Unlock",
"(",
")",
"\n",
"return",
"0",
",",
"ErrConnectionReset",
"\n",
"}",
"\n",
"s",
".",
"stateLock",
".",
"Unlock",
"(",
")",
"\n\n",
"// If there is no data available, block",
"s",
".",
"recvLock",
".",
"Lock",
"(",
")",
"\n",
"if",
"s",
".",
"recvBuf",
"==",
"nil",
"||",
"s",
".",
"recvBuf",
".",
"Len",
"(",
")",
"==",
"0",
"{",
"s",
".",
"recvLock",
".",
"Unlock",
"(",
")",
"\n",
"goto",
"WAIT",
"\n",
"}",
"\n\n",
"// Read any bytes",
"n",
",",
"_",
"=",
"s",
".",
"recvBuf",
".",
"Read",
"(",
"b",
")",
"\n",
"s",
".",
"recvLock",
".",
"Unlock",
"(",
")",
"\n\n",
"// Send a window update potentially",
"err",
"=",
"s",
".",
"sendWindowUpdate",
"(",
")",
"\n",
"return",
"n",
",",
"err",
"\n\n",
"WAIT",
":",
"var",
"timeout",
"<-",
"chan",
"time",
".",
"Time",
"\n",
"var",
"timer",
"*",
"time",
".",
"Timer",
"\n",
"readDeadline",
":=",
"s",
".",
"readDeadline",
".",
"Load",
"(",
")",
".",
"(",
"time",
".",
"Time",
")",
"\n",
"if",
"!",
"readDeadline",
".",
"IsZero",
"(",
")",
"{",
"delay",
":=",
"readDeadline",
".",
"Sub",
"(",
"time",
".",
"Now",
"(",
")",
")",
"\n",
"timer",
"=",
"time",
".",
"NewTimer",
"(",
"delay",
")",
"\n",
"timeout",
"=",
"timer",
".",
"C",
"\n",
"}",
"\n",
"select",
"{",
"case",
"<-",
"s",
".",
"recvNotifyCh",
":",
"if",
"timer",
"!=",
"nil",
"{",
"timer",
".",
"Stop",
"(",
")",
"\n",
"}",
"\n",
"goto",
"START",
"\n",
"case",
"<-",
"timeout",
":",
"return",
"0",
",",
"ErrTimeout",
"\n",
"}",
"\n",
"}"
] | // Read is used to read from the stream | [
"Read",
"is",
"used",
"to",
"read",
"from",
"the",
"stream"
] | 2f1d1f20f75d5404f53b9edf6b53ed5505508675 | https://github.com/hashicorp/yamux/blob/2f1d1f20f75d5404f53b9edf6b53ed5505508675/stream.go#L86-L142 | train |
hashicorp/yamux | stream.go | Write | func (s *Stream) Write(b []byte) (n int, err error) {
s.sendLock.Lock()
defer s.sendLock.Unlock()
total := 0
for total < len(b) {
n, err := s.write(b[total:])
total += n
if err != nil {
return total, err
}
}
return total, nil
} | go | func (s *Stream) Write(b []byte) (n int, err error) {
s.sendLock.Lock()
defer s.sendLock.Unlock()
total := 0
for total < len(b) {
n, err := s.write(b[total:])
total += n
if err != nil {
return total, err
}
}
return total, nil
} | [
"func",
"(",
"s",
"*",
"Stream",
")",
"Write",
"(",
"b",
"[",
"]",
"byte",
")",
"(",
"n",
"int",
",",
"err",
"error",
")",
"{",
"s",
".",
"sendLock",
".",
"Lock",
"(",
")",
"\n",
"defer",
"s",
".",
"sendLock",
".",
"Unlock",
"(",
")",
"\n",
"total",
":=",
"0",
"\n",
"for",
"total",
"<",
"len",
"(",
"b",
")",
"{",
"n",
",",
"err",
":=",
"s",
".",
"write",
"(",
"b",
"[",
"total",
":",
"]",
")",
"\n",
"total",
"+=",
"n",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"total",
",",
"err",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"total",
",",
"nil",
"\n",
"}"
] | // Write is used to write to the stream | [
"Write",
"is",
"used",
"to",
"write",
"to",
"the",
"stream"
] | 2f1d1f20f75d5404f53b9edf6b53ed5505508675 | https://github.com/hashicorp/yamux/blob/2f1d1f20f75d5404f53b9edf6b53ed5505508675/stream.go#L145-L157 | train |
hashicorp/yamux | stream.go | write | func (s *Stream) write(b []byte) (n int, err error) {
var flags uint16
var max uint32
var body io.Reader
START:
s.stateLock.Lock()
switch s.state {
case streamLocalClose:
fallthrough
case streamClosed:
s.stateLock.Unlock()
return 0, ErrStreamClosed
case streamReset:
s.stateLock.Unlock()
return 0, ErrConnectionReset
}
s.stateLock.Unlock()
// If there is no data available, block
window := atomic.LoadUint32(&s.sendWindow)
if window == 0 {
goto WAIT
}
// Determine the flags if any
flags = s.sendFlags()
// Send up to our send window
max = min(window, uint32(len(b)))
body = bytes.NewReader(b[:max])
// Send the header
s.sendHdr.encode(typeData, flags, s.id, max)
if err = s.session.waitForSendErr(s.sendHdr, body, s.sendErr); err != nil {
return 0, err
}
// Reduce our send window
atomic.AddUint32(&s.sendWindow, ^uint32(max-1))
// Unlock
return int(max), err
WAIT:
var timeout <-chan time.Time
writeDeadline := s.writeDeadline.Load().(time.Time)
if !writeDeadline.IsZero() {
delay := writeDeadline.Sub(time.Now())
timeout = time.After(delay)
}
select {
case <-s.sendNotifyCh:
goto START
case <-timeout:
return 0, ErrTimeout
}
return 0, nil
} | go | func (s *Stream) write(b []byte) (n int, err error) {
var flags uint16
var max uint32
var body io.Reader
START:
s.stateLock.Lock()
switch s.state {
case streamLocalClose:
fallthrough
case streamClosed:
s.stateLock.Unlock()
return 0, ErrStreamClosed
case streamReset:
s.stateLock.Unlock()
return 0, ErrConnectionReset
}
s.stateLock.Unlock()
// If there is no data available, block
window := atomic.LoadUint32(&s.sendWindow)
if window == 0 {
goto WAIT
}
// Determine the flags if any
flags = s.sendFlags()
// Send up to our send window
max = min(window, uint32(len(b)))
body = bytes.NewReader(b[:max])
// Send the header
s.sendHdr.encode(typeData, flags, s.id, max)
if err = s.session.waitForSendErr(s.sendHdr, body, s.sendErr); err != nil {
return 0, err
}
// Reduce our send window
atomic.AddUint32(&s.sendWindow, ^uint32(max-1))
// Unlock
return int(max), err
WAIT:
var timeout <-chan time.Time
writeDeadline := s.writeDeadline.Load().(time.Time)
if !writeDeadline.IsZero() {
delay := writeDeadline.Sub(time.Now())
timeout = time.After(delay)
}
select {
case <-s.sendNotifyCh:
goto START
case <-timeout:
return 0, ErrTimeout
}
return 0, nil
} | [
"func",
"(",
"s",
"*",
"Stream",
")",
"write",
"(",
"b",
"[",
"]",
"byte",
")",
"(",
"n",
"int",
",",
"err",
"error",
")",
"{",
"var",
"flags",
"uint16",
"\n",
"var",
"max",
"uint32",
"\n",
"var",
"body",
"io",
".",
"Reader",
"\n",
"START",
":",
"s",
".",
"stateLock",
".",
"Lock",
"(",
")",
"\n",
"switch",
"s",
".",
"state",
"{",
"case",
"streamLocalClose",
":",
"fallthrough",
"\n",
"case",
"streamClosed",
":",
"s",
".",
"stateLock",
".",
"Unlock",
"(",
")",
"\n",
"return",
"0",
",",
"ErrStreamClosed",
"\n",
"case",
"streamReset",
":",
"s",
".",
"stateLock",
".",
"Unlock",
"(",
")",
"\n",
"return",
"0",
",",
"ErrConnectionReset",
"\n",
"}",
"\n",
"s",
".",
"stateLock",
".",
"Unlock",
"(",
")",
"\n\n",
"// If there is no data available, block",
"window",
":=",
"atomic",
".",
"LoadUint32",
"(",
"&",
"s",
".",
"sendWindow",
")",
"\n",
"if",
"window",
"==",
"0",
"{",
"goto",
"WAIT",
"\n",
"}",
"\n\n",
"// Determine the flags if any",
"flags",
"=",
"s",
".",
"sendFlags",
"(",
")",
"\n\n",
"// Send up to our send window",
"max",
"=",
"min",
"(",
"window",
",",
"uint32",
"(",
"len",
"(",
"b",
")",
")",
")",
"\n",
"body",
"=",
"bytes",
".",
"NewReader",
"(",
"b",
"[",
":",
"max",
"]",
")",
"\n\n",
"// Send the header",
"s",
".",
"sendHdr",
".",
"encode",
"(",
"typeData",
",",
"flags",
",",
"s",
".",
"id",
",",
"max",
")",
"\n",
"if",
"err",
"=",
"s",
".",
"session",
".",
"waitForSendErr",
"(",
"s",
".",
"sendHdr",
",",
"body",
",",
"s",
".",
"sendErr",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"0",
",",
"err",
"\n",
"}",
"\n\n",
"// Reduce our send window",
"atomic",
".",
"AddUint32",
"(",
"&",
"s",
".",
"sendWindow",
",",
"^",
"uint32",
"(",
"max",
"-",
"1",
")",
")",
"\n\n",
"// Unlock",
"return",
"int",
"(",
"max",
")",
",",
"err",
"\n\n",
"WAIT",
":",
"var",
"timeout",
"<-",
"chan",
"time",
".",
"Time",
"\n",
"writeDeadline",
":=",
"s",
".",
"writeDeadline",
".",
"Load",
"(",
")",
".",
"(",
"time",
".",
"Time",
")",
"\n",
"if",
"!",
"writeDeadline",
".",
"IsZero",
"(",
")",
"{",
"delay",
":=",
"writeDeadline",
".",
"Sub",
"(",
"time",
".",
"Now",
"(",
")",
")",
"\n",
"timeout",
"=",
"time",
".",
"After",
"(",
"delay",
")",
"\n",
"}",
"\n",
"select",
"{",
"case",
"<-",
"s",
".",
"sendNotifyCh",
":",
"goto",
"START",
"\n",
"case",
"<-",
"timeout",
":",
"return",
"0",
",",
"ErrTimeout",
"\n",
"}",
"\n",
"return",
"0",
",",
"nil",
"\n",
"}"
] | // write is used to write to the stream, may return on
// a short write. | [
"write",
"is",
"used",
"to",
"write",
"to",
"the",
"stream",
"may",
"return",
"on",
"a",
"short",
"write",
"."
] | 2f1d1f20f75d5404f53b9edf6b53ed5505508675 | https://github.com/hashicorp/yamux/blob/2f1d1f20f75d5404f53b9edf6b53ed5505508675/stream.go#L161-L218 | train |
hashicorp/yamux | stream.go | sendFlags | func (s *Stream) sendFlags() uint16 {
s.stateLock.Lock()
defer s.stateLock.Unlock()
var flags uint16
switch s.state {
case streamInit:
flags |= flagSYN
s.state = streamSYNSent
case streamSYNReceived:
flags |= flagACK
s.state = streamEstablished
}
return flags
} | go | func (s *Stream) sendFlags() uint16 {
s.stateLock.Lock()
defer s.stateLock.Unlock()
var flags uint16
switch s.state {
case streamInit:
flags |= flagSYN
s.state = streamSYNSent
case streamSYNReceived:
flags |= flagACK
s.state = streamEstablished
}
return flags
} | [
"func",
"(",
"s",
"*",
"Stream",
")",
"sendFlags",
"(",
")",
"uint16",
"{",
"s",
".",
"stateLock",
".",
"Lock",
"(",
")",
"\n",
"defer",
"s",
".",
"stateLock",
".",
"Unlock",
"(",
")",
"\n",
"var",
"flags",
"uint16",
"\n",
"switch",
"s",
".",
"state",
"{",
"case",
"streamInit",
":",
"flags",
"|=",
"flagSYN",
"\n",
"s",
".",
"state",
"=",
"streamSYNSent",
"\n",
"case",
"streamSYNReceived",
":",
"flags",
"|=",
"flagACK",
"\n",
"s",
".",
"state",
"=",
"streamEstablished",
"\n",
"}",
"\n",
"return",
"flags",
"\n",
"}"
] | // sendFlags determines any flags that are appropriate
// based on the current stream state | [
"sendFlags",
"determines",
"any",
"flags",
"that",
"are",
"appropriate",
"based",
"on",
"the",
"current",
"stream",
"state"
] | 2f1d1f20f75d5404f53b9edf6b53ed5505508675 | https://github.com/hashicorp/yamux/blob/2f1d1f20f75d5404f53b9edf6b53ed5505508675/stream.go#L222-L235 | train |
hashicorp/yamux | stream.go | sendWindowUpdate | func (s *Stream) sendWindowUpdate() error {
s.controlHdrLock.Lock()
defer s.controlHdrLock.Unlock()
// Determine the delta update
max := s.session.config.MaxStreamWindowSize
var bufLen uint32
s.recvLock.Lock()
if s.recvBuf != nil {
bufLen = uint32(s.recvBuf.Len())
}
delta := (max - bufLen) - s.recvWindow
// Determine the flags if any
flags := s.sendFlags()
// Check if we can omit the update
if delta < (max/2) && flags == 0 {
s.recvLock.Unlock()
return nil
}
// Update our window
s.recvWindow += delta
s.recvLock.Unlock()
// Send the header
s.controlHdr.encode(typeWindowUpdate, flags, s.id, delta)
if err := s.session.waitForSendErr(s.controlHdr, nil, s.controlErr); err != nil {
return err
}
return nil
} | go | func (s *Stream) sendWindowUpdate() error {
s.controlHdrLock.Lock()
defer s.controlHdrLock.Unlock()
// Determine the delta update
max := s.session.config.MaxStreamWindowSize
var bufLen uint32
s.recvLock.Lock()
if s.recvBuf != nil {
bufLen = uint32(s.recvBuf.Len())
}
delta := (max - bufLen) - s.recvWindow
// Determine the flags if any
flags := s.sendFlags()
// Check if we can omit the update
if delta < (max/2) && flags == 0 {
s.recvLock.Unlock()
return nil
}
// Update our window
s.recvWindow += delta
s.recvLock.Unlock()
// Send the header
s.controlHdr.encode(typeWindowUpdate, flags, s.id, delta)
if err := s.session.waitForSendErr(s.controlHdr, nil, s.controlErr); err != nil {
return err
}
return nil
} | [
"func",
"(",
"s",
"*",
"Stream",
")",
"sendWindowUpdate",
"(",
")",
"error",
"{",
"s",
".",
"controlHdrLock",
".",
"Lock",
"(",
")",
"\n",
"defer",
"s",
".",
"controlHdrLock",
".",
"Unlock",
"(",
")",
"\n\n",
"// Determine the delta update",
"max",
":=",
"s",
".",
"session",
".",
"config",
".",
"MaxStreamWindowSize",
"\n",
"var",
"bufLen",
"uint32",
"\n",
"s",
".",
"recvLock",
".",
"Lock",
"(",
")",
"\n",
"if",
"s",
".",
"recvBuf",
"!=",
"nil",
"{",
"bufLen",
"=",
"uint32",
"(",
"s",
".",
"recvBuf",
".",
"Len",
"(",
")",
")",
"\n",
"}",
"\n",
"delta",
":=",
"(",
"max",
"-",
"bufLen",
")",
"-",
"s",
".",
"recvWindow",
"\n\n",
"// Determine the flags if any",
"flags",
":=",
"s",
".",
"sendFlags",
"(",
")",
"\n\n",
"// Check if we can omit the update",
"if",
"delta",
"<",
"(",
"max",
"/",
"2",
")",
"&&",
"flags",
"==",
"0",
"{",
"s",
".",
"recvLock",
".",
"Unlock",
"(",
")",
"\n",
"return",
"nil",
"\n",
"}",
"\n\n",
"// Update our window",
"s",
".",
"recvWindow",
"+=",
"delta",
"\n",
"s",
".",
"recvLock",
".",
"Unlock",
"(",
")",
"\n\n",
"// Send the header",
"s",
".",
"controlHdr",
".",
"encode",
"(",
"typeWindowUpdate",
",",
"flags",
",",
"s",
".",
"id",
",",
"delta",
")",
"\n",
"if",
"err",
":=",
"s",
".",
"session",
".",
"waitForSendErr",
"(",
"s",
".",
"controlHdr",
",",
"nil",
",",
"s",
".",
"controlErr",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}"
] | // sendWindowUpdate potentially sends a window update enabling
// further writes to take place. Must be invoked with the lock. | [
"sendWindowUpdate",
"potentially",
"sends",
"a",
"window",
"update",
"enabling",
"further",
"writes",
"to",
"take",
"place",
".",
"Must",
"be",
"invoked",
"with",
"the",
"lock",
"."
] | 2f1d1f20f75d5404f53b9edf6b53ed5505508675 | https://github.com/hashicorp/yamux/blob/2f1d1f20f75d5404f53b9edf6b53ed5505508675/stream.go#L239-L271 | train |
hashicorp/yamux | stream.go | sendClose | func (s *Stream) sendClose() error {
s.controlHdrLock.Lock()
defer s.controlHdrLock.Unlock()
flags := s.sendFlags()
flags |= flagFIN
s.controlHdr.encode(typeWindowUpdate, flags, s.id, 0)
if err := s.session.waitForSendErr(s.controlHdr, nil, s.controlErr); err != nil {
return err
}
return nil
} | go | func (s *Stream) sendClose() error {
s.controlHdrLock.Lock()
defer s.controlHdrLock.Unlock()
flags := s.sendFlags()
flags |= flagFIN
s.controlHdr.encode(typeWindowUpdate, flags, s.id, 0)
if err := s.session.waitForSendErr(s.controlHdr, nil, s.controlErr); err != nil {
return err
}
return nil
} | [
"func",
"(",
"s",
"*",
"Stream",
")",
"sendClose",
"(",
")",
"error",
"{",
"s",
".",
"controlHdrLock",
".",
"Lock",
"(",
")",
"\n",
"defer",
"s",
".",
"controlHdrLock",
".",
"Unlock",
"(",
")",
"\n\n",
"flags",
":=",
"s",
".",
"sendFlags",
"(",
")",
"\n",
"flags",
"|=",
"flagFIN",
"\n",
"s",
".",
"controlHdr",
".",
"encode",
"(",
"typeWindowUpdate",
",",
"flags",
",",
"s",
".",
"id",
",",
"0",
")",
"\n",
"if",
"err",
":=",
"s",
".",
"session",
".",
"waitForSendErr",
"(",
"s",
".",
"controlHdr",
",",
"nil",
",",
"s",
".",
"controlErr",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}"
] | // sendClose is used to send a FIN | [
"sendClose",
"is",
"used",
"to",
"send",
"a",
"FIN"
] | 2f1d1f20f75d5404f53b9edf6b53ed5505508675 | https://github.com/hashicorp/yamux/blob/2f1d1f20f75d5404f53b9edf6b53ed5505508675/stream.go#L274-L285 | train |
hashicorp/yamux | stream.go | Close | func (s *Stream) Close() error {
closeStream := false
s.stateLock.Lock()
switch s.state {
// Opened means we need to signal a close
case streamSYNSent:
fallthrough
case streamSYNReceived:
fallthrough
case streamEstablished:
s.state = streamLocalClose
goto SEND_CLOSE
case streamLocalClose:
case streamRemoteClose:
s.state = streamClosed
closeStream = true
goto SEND_CLOSE
case streamClosed:
case streamReset:
default:
panic("unhandled state")
}
s.stateLock.Unlock()
return nil
SEND_CLOSE:
s.stateLock.Unlock()
s.sendClose()
s.notifyWaiting()
if closeStream {
s.session.closeStream(s.id)
}
return nil
} | go | func (s *Stream) Close() error {
closeStream := false
s.stateLock.Lock()
switch s.state {
// Opened means we need to signal a close
case streamSYNSent:
fallthrough
case streamSYNReceived:
fallthrough
case streamEstablished:
s.state = streamLocalClose
goto SEND_CLOSE
case streamLocalClose:
case streamRemoteClose:
s.state = streamClosed
closeStream = true
goto SEND_CLOSE
case streamClosed:
case streamReset:
default:
panic("unhandled state")
}
s.stateLock.Unlock()
return nil
SEND_CLOSE:
s.stateLock.Unlock()
s.sendClose()
s.notifyWaiting()
if closeStream {
s.session.closeStream(s.id)
}
return nil
} | [
"func",
"(",
"s",
"*",
"Stream",
")",
"Close",
"(",
")",
"error",
"{",
"closeStream",
":=",
"false",
"\n",
"s",
".",
"stateLock",
".",
"Lock",
"(",
")",
"\n",
"switch",
"s",
".",
"state",
"{",
"// Opened means we need to signal a close",
"case",
"streamSYNSent",
":",
"fallthrough",
"\n",
"case",
"streamSYNReceived",
":",
"fallthrough",
"\n",
"case",
"streamEstablished",
":",
"s",
".",
"state",
"=",
"streamLocalClose",
"\n",
"goto",
"SEND_CLOSE",
"\n\n",
"case",
"streamLocalClose",
":",
"case",
"streamRemoteClose",
":",
"s",
".",
"state",
"=",
"streamClosed",
"\n",
"closeStream",
"=",
"true",
"\n",
"goto",
"SEND_CLOSE",
"\n\n",
"case",
"streamClosed",
":",
"case",
"streamReset",
":",
"default",
":",
"panic",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"s",
".",
"stateLock",
".",
"Unlock",
"(",
")",
"\n",
"return",
"nil",
"\n",
"SEND_CLOSE",
":",
"s",
".",
"stateLock",
".",
"Unlock",
"(",
")",
"\n",
"s",
".",
"sendClose",
"(",
")",
"\n",
"s",
".",
"notifyWaiting",
"(",
")",
"\n",
"if",
"closeStream",
"{",
"s",
".",
"session",
".",
"closeStream",
"(",
"s",
".",
"id",
")",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}"
] | // Close is used to close the stream | [
"Close",
"is",
"used",
"to",
"close",
"the",
"stream"
] | 2f1d1f20f75d5404f53b9edf6b53ed5505508675 | https://github.com/hashicorp/yamux/blob/2f1d1f20f75d5404f53b9edf6b53ed5505508675/stream.go#L288-L322 | train |
hashicorp/yamux | stream.go | forceClose | func (s *Stream) forceClose() {
s.stateLock.Lock()
s.state = streamClosed
s.stateLock.Unlock()
s.notifyWaiting()
} | go | func (s *Stream) forceClose() {
s.stateLock.Lock()
s.state = streamClosed
s.stateLock.Unlock()
s.notifyWaiting()
} | [
"func",
"(",
"s",
"*",
"Stream",
")",
"forceClose",
"(",
")",
"{",
"s",
".",
"stateLock",
".",
"Lock",
"(",
")",
"\n",
"s",
".",
"state",
"=",
"streamClosed",
"\n",
"s",
".",
"stateLock",
".",
"Unlock",
"(",
")",
"\n",
"s",
".",
"notifyWaiting",
"(",
")",
"\n",
"}"
] | // forceClose is used for when the session is exiting | [
"forceClose",
"is",
"used",
"for",
"when",
"the",
"session",
"is",
"exiting"
] | 2f1d1f20f75d5404f53b9edf6b53ed5505508675 | https://github.com/hashicorp/yamux/blob/2f1d1f20f75d5404f53b9edf6b53ed5505508675/stream.go#L325-L330 | train |
hashicorp/yamux | stream.go | processFlags | func (s *Stream) processFlags(flags uint16) error {
// Close the stream without holding the state lock
closeStream := false
defer func() {
if closeStream {
s.session.closeStream(s.id)
}
}()
s.stateLock.Lock()
defer s.stateLock.Unlock()
if flags&flagACK == flagACK {
if s.state == streamSYNSent {
s.state = streamEstablished
}
s.session.establishStream(s.id)
}
if flags&flagFIN == flagFIN {
switch s.state {
case streamSYNSent:
fallthrough
case streamSYNReceived:
fallthrough
case streamEstablished:
s.state = streamRemoteClose
s.notifyWaiting()
case streamLocalClose:
s.state = streamClosed
closeStream = true
s.notifyWaiting()
default:
s.session.logger.Printf("[ERR] yamux: unexpected FIN flag in state %d", s.state)
return ErrUnexpectedFlag
}
}
if flags&flagRST == flagRST {
s.state = streamReset
closeStream = true
s.notifyWaiting()
}
return nil
} | go | func (s *Stream) processFlags(flags uint16) error {
// Close the stream without holding the state lock
closeStream := false
defer func() {
if closeStream {
s.session.closeStream(s.id)
}
}()
s.stateLock.Lock()
defer s.stateLock.Unlock()
if flags&flagACK == flagACK {
if s.state == streamSYNSent {
s.state = streamEstablished
}
s.session.establishStream(s.id)
}
if flags&flagFIN == flagFIN {
switch s.state {
case streamSYNSent:
fallthrough
case streamSYNReceived:
fallthrough
case streamEstablished:
s.state = streamRemoteClose
s.notifyWaiting()
case streamLocalClose:
s.state = streamClosed
closeStream = true
s.notifyWaiting()
default:
s.session.logger.Printf("[ERR] yamux: unexpected FIN flag in state %d", s.state)
return ErrUnexpectedFlag
}
}
if flags&flagRST == flagRST {
s.state = streamReset
closeStream = true
s.notifyWaiting()
}
return nil
} | [
"func",
"(",
"s",
"*",
"Stream",
")",
"processFlags",
"(",
"flags",
"uint16",
")",
"error",
"{",
"// Close the stream without holding the state lock",
"closeStream",
":=",
"false",
"\n",
"defer",
"func",
"(",
")",
"{",
"if",
"closeStream",
"{",
"s",
".",
"session",
".",
"closeStream",
"(",
"s",
".",
"id",
")",
"\n",
"}",
"\n",
"}",
"(",
")",
"\n\n",
"s",
".",
"stateLock",
".",
"Lock",
"(",
")",
"\n",
"defer",
"s",
".",
"stateLock",
".",
"Unlock",
"(",
")",
"\n",
"if",
"flags",
"&",
"flagACK",
"==",
"flagACK",
"{",
"if",
"s",
".",
"state",
"==",
"streamSYNSent",
"{",
"s",
".",
"state",
"=",
"streamEstablished",
"\n",
"}",
"\n",
"s",
".",
"session",
".",
"establishStream",
"(",
"s",
".",
"id",
")",
"\n",
"}",
"\n",
"if",
"flags",
"&",
"flagFIN",
"==",
"flagFIN",
"{",
"switch",
"s",
".",
"state",
"{",
"case",
"streamSYNSent",
":",
"fallthrough",
"\n",
"case",
"streamSYNReceived",
":",
"fallthrough",
"\n",
"case",
"streamEstablished",
":",
"s",
".",
"state",
"=",
"streamRemoteClose",
"\n",
"s",
".",
"notifyWaiting",
"(",
")",
"\n",
"case",
"streamLocalClose",
":",
"s",
".",
"state",
"=",
"streamClosed",
"\n",
"closeStream",
"=",
"true",
"\n",
"s",
".",
"notifyWaiting",
"(",
")",
"\n",
"default",
":",
"s",
".",
"session",
".",
"logger",
".",
"Printf",
"(",
"\"",
"\"",
",",
"s",
".",
"state",
")",
"\n",
"return",
"ErrUnexpectedFlag",
"\n",
"}",
"\n",
"}",
"\n",
"if",
"flags",
"&",
"flagRST",
"==",
"flagRST",
"{",
"s",
".",
"state",
"=",
"streamReset",
"\n",
"closeStream",
"=",
"true",
"\n",
"s",
".",
"notifyWaiting",
"(",
")",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}"
] | // processFlags is used to update the state of the stream
// based on set flags, if any. Lock must be held | [
"processFlags",
"is",
"used",
"to",
"update",
"the",
"state",
"of",
"the",
"stream",
"based",
"on",
"set",
"flags",
"if",
"any",
".",
"Lock",
"must",
"be",
"held"
] | 2f1d1f20f75d5404f53b9edf6b53ed5505508675 | https://github.com/hashicorp/yamux/blob/2f1d1f20f75d5404f53b9edf6b53ed5505508675/stream.go#L334-L375 | train |
hashicorp/yamux | stream.go | incrSendWindow | func (s *Stream) incrSendWindow(hdr header, flags uint16) error {
if err := s.processFlags(flags); err != nil {
return err
}
// Increase window, unblock a sender
atomic.AddUint32(&s.sendWindow, hdr.Length())
asyncNotify(s.sendNotifyCh)
return nil
} | go | func (s *Stream) incrSendWindow(hdr header, flags uint16) error {
if err := s.processFlags(flags); err != nil {
return err
}
// Increase window, unblock a sender
atomic.AddUint32(&s.sendWindow, hdr.Length())
asyncNotify(s.sendNotifyCh)
return nil
} | [
"func",
"(",
"s",
"*",
"Stream",
")",
"incrSendWindow",
"(",
"hdr",
"header",
",",
"flags",
"uint16",
")",
"error",
"{",
"if",
"err",
":=",
"s",
".",
"processFlags",
"(",
"flags",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n\n",
"// Increase window, unblock a sender",
"atomic",
".",
"AddUint32",
"(",
"&",
"s",
".",
"sendWindow",
",",
"hdr",
".",
"Length",
"(",
")",
")",
"\n",
"asyncNotify",
"(",
"s",
".",
"sendNotifyCh",
")",
"\n",
"return",
"nil",
"\n",
"}"
] | // incrSendWindow updates the size of our send window | [
"incrSendWindow",
"updates",
"the",
"size",
"of",
"our",
"send",
"window"
] | 2f1d1f20f75d5404f53b9edf6b53ed5505508675 | https://github.com/hashicorp/yamux/blob/2f1d1f20f75d5404f53b9edf6b53ed5505508675/stream.go#L384-L393 | train |
hashicorp/yamux | stream.go | readData | func (s *Stream) readData(hdr header, flags uint16, conn io.Reader) error {
if err := s.processFlags(flags); err != nil {
return err
}
// Check that our recv window is not exceeded
length := hdr.Length()
if length == 0 {
return nil
}
// Wrap in a limited reader
conn = &io.LimitedReader{R: conn, N: int64(length)}
// Copy into buffer
s.recvLock.Lock()
if length > s.recvWindow {
s.session.logger.Printf("[ERR] yamux: receive window exceeded (stream: %d, remain: %d, recv: %d)", s.id, s.recvWindow, length)
return ErrRecvWindowExceeded
}
if s.recvBuf == nil {
// Allocate the receive buffer just-in-time to fit the full data frame.
// This way we can read in the whole packet without further allocations.
s.recvBuf = bytes.NewBuffer(make([]byte, 0, length))
}
if _, err := io.Copy(s.recvBuf, conn); err != nil {
s.session.logger.Printf("[ERR] yamux: Failed to read stream data: %v", err)
s.recvLock.Unlock()
return err
}
// Decrement the receive window
s.recvWindow -= length
s.recvLock.Unlock()
// Unblock any readers
asyncNotify(s.recvNotifyCh)
return nil
} | go | func (s *Stream) readData(hdr header, flags uint16, conn io.Reader) error {
if err := s.processFlags(flags); err != nil {
return err
}
// Check that our recv window is not exceeded
length := hdr.Length()
if length == 0 {
return nil
}
// Wrap in a limited reader
conn = &io.LimitedReader{R: conn, N: int64(length)}
// Copy into buffer
s.recvLock.Lock()
if length > s.recvWindow {
s.session.logger.Printf("[ERR] yamux: receive window exceeded (stream: %d, remain: %d, recv: %d)", s.id, s.recvWindow, length)
return ErrRecvWindowExceeded
}
if s.recvBuf == nil {
// Allocate the receive buffer just-in-time to fit the full data frame.
// This way we can read in the whole packet without further allocations.
s.recvBuf = bytes.NewBuffer(make([]byte, 0, length))
}
if _, err := io.Copy(s.recvBuf, conn); err != nil {
s.session.logger.Printf("[ERR] yamux: Failed to read stream data: %v", err)
s.recvLock.Unlock()
return err
}
// Decrement the receive window
s.recvWindow -= length
s.recvLock.Unlock()
// Unblock any readers
asyncNotify(s.recvNotifyCh)
return nil
} | [
"func",
"(",
"s",
"*",
"Stream",
")",
"readData",
"(",
"hdr",
"header",
",",
"flags",
"uint16",
",",
"conn",
"io",
".",
"Reader",
")",
"error",
"{",
"if",
"err",
":=",
"s",
".",
"processFlags",
"(",
"flags",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n\n",
"// Check that our recv window is not exceeded",
"length",
":=",
"hdr",
".",
"Length",
"(",
")",
"\n",
"if",
"length",
"==",
"0",
"{",
"return",
"nil",
"\n",
"}",
"\n\n",
"// Wrap in a limited reader",
"conn",
"=",
"&",
"io",
".",
"LimitedReader",
"{",
"R",
":",
"conn",
",",
"N",
":",
"int64",
"(",
"length",
")",
"}",
"\n\n",
"// Copy into buffer",
"s",
".",
"recvLock",
".",
"Lock",
"(",
")",
"\n\n",
"if",
"length",
">",
"s",
".",
"recvWindow",
"{",
"s",
".",
"session",
".",
"logger",
".",
"Printf",
"(",
"\"",
"\"",
",",
"s",
".",
"id",
",",
"s",
".",
"recvWindow",
",",
"length",
")",
"\n",
"return",
"ErrRecvWindowExceeded",
"\n",
"}",
"\n\n",
"if",
"s",
".",
"recvBuf",
"==",
"nil",
"{",
"// Allocate the receive buffer just-in-time to fit the full data frame.",
"// This way we can read in the whole packet without further allocations.",
"s",
".",
"recvBuf",
"=",
"bytes",
".",
"NewBuffer",
"(",
"make",
"(",
"[",
"]",
"byte",
",",
"0",
",",
"length",
")",
")",
"\n",
"}",
"\n",
"if",
"_",
",",
"err",
":=",
"io",
".",
"Copy",
"(",
"s",
".",
"recvBuf",
",",
"conn",
")",
";",
"err",
"!=",
"nil",
"{",
"s",
".",
"session",
".",
"logger",
".",
"Printf",
"(",
"\"",
"\"",
",",
"err",
")",
"\n",
"s",
".",
"recvLock",
".",
"Unlock",
"(",
")",
"\n",
"return",
"err",
"\n",
"}",
"\n\n",
"// Decrement the receive window",
"s",
".",
"recvWindow",
"-=",
"length",
"\n",
"s",
".",
"recvLock",
".",
"Unlock",
"(",
")",
"\n\n",
"// Unblock any readers",
"asyncNotify",
"(",
"s",
".",
"recvNotifyCh",
")",
"\n",
"return",
"nil",
"\n",
"}"
] | // readData is used to handle a data frame | [
"readData",
"is",
"used",
"to",
"handle",
"a",
"data",
"frame"
] | 2f1d1f20f75d5404f53b9edf6b53ed5505508675 | https://github.com/hashicorp/yamux/blob/2f1d1f20f75d5404f53b9edf6b53ed5505508675/stream.go#L396-L436 | train |
hashicorp/yamux | stream.go | SetDeadline | func (s *Stream) SetDeadline(t time.Time) error {
if err := s.SetReadDeadline(t); err != nil {
return err
}
if err := s.SetWriteDeadline(t); err != nil {
return err
}
return nil
} | go | func (s *Stream) SetDeadline(t time.Time) error {
if err := s.SetReadDeadline(t); err != nil {
return err
}
if err := s.SetWriteDeadline(t); err != nil {
return err
}
return nil
} | [
"func",
"(",
"s",
"*",
"Stream",
")",
"SetDeadline",
"(",
"t",
"time",
".",
"Time",
")",
"error",
"{",
"if",
"err",
":=",
"s",
".",
"SetReadDeadline",
"(",
"t",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"if",
"err",
":=",
"s",
".",
"SetWriteDeadline",
"(",
"t",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}"
] | // SetDeadline sets the read and write deadlines | [
"SetDeadline",
"sets",
"the",
"read",
"and",
"write",
"deadlines"
] | 2f1d1f20f75d5404f53b9edf6b53ed5505508675 | https://github.com/hashicorp/yamux/blob/2f1d1f20f75d5404f53b9edf6b53ed5505508675/stream.go#L439-L447 | train |
hashicorp/yamux | stream.go | SetWriteDeadline | func (s *Stream) SetWriteDeadline(t time.Time) error {
s.writeDeadline.Store(t)
return nil
} | go | func (s *Stream) SetWriteDeadline(t time.Time) error {
s.writeDeadline.Store(t)
return nil
} | [
"func",
"(",
"s",
"*",
"Stream",
")",
"SetWriteDeadline",
"(",
"t",
"time",
".",
"Time",
")",
"error",
"{",
"s",
".",
"writeDeadline",
".",
"Store",
"(",
"t",
")",
"\n",
"return",
"nil",
"\n",
"}"
] | // SetWriteDeadline sets the deadline for future Write calls | [
"SetWriteDeadline",
"sets",
"the",
"deadline",
"for",
"future",
"Write",
"calls"
] | 2f1d1f20f75d5404f53b9edf6b53ed5505508675 | https://github.com/hashicorp/yamux/blob/2f1d1f20f75d5404f53b9edf6b53ed5505508675/stream.go#L456-L459 | train |
hashicorp/yamux | stream.go | Shrink | func (s *Stream) Shrink() {
s.recvLock.Lock()
if s.recvBuf != nil && s.recvBuf.Len() == 0 {
s.recvBuf = nil
}
s.recvLock.Unlock()
} | go | func (s *Stream) Shrink() {
s.recvLock.Lock()
if s.recvBuf != nil && s.recvBuf.Len() == 0 {
s.recvBuf = nil
}
s.recvLock.Unlock()
} | [
"func",
"(",
"s",
"*",
"Stream",
")",
"Shrink",
"(",
")",
"{",
"s",
".",
"recvLock",
".",
"Lock",
"(",
")",
"\n",
"if",
"s",
".",
"recvBuf",
"!=",
"nil",
"&&",
"s",
".",
"recvBuf",
".",
"Len",
"(",
")",
"==",
"0",
"{",
"s",
".",
"recvBuf",
"=",
"nil",
"\n",
"}",
"\n",
"s",
".",
"recvLock",
".",
"Unlock",
"(",
")",
"\n",
"}"
] | // Shrink is used to compact the amount of buffers utilized
// This is useful when using Yamux in a connection pool to reduce
// the idle memory utilization. | [
"Shrink",
"is",
"used",
"to",
"compact",
"the",
"amount",
"of",
"buffers",
"utilized",
"This",
"is",
"useful",
"when",
"using",
"Yamux",
"in",
"a",
"connection",
"pool",
"to",
"reduce",
"the",
"idle",
"memory",
"utilization",
"."
] | 2f1d1f20f75d5404f53b9edf6b53ed5505508675 | https://github.com/hashicorp/yamux/blob/2f1d1f20f75d5404f53b9edf6b53ed5505508675/stream.go#L464-L470 | train |
hashicorp/yamux | mux.go | Server | func Server(conn io.ReadWriteCloser, config *Config) (*Session, error) {
if config == nil {
config = DefaultConfig()
}
if err := VerifyConfig(config); err != nil {
return nil, err
}
return newSession(config, conn, false), nil
} | go | func Server(conn io.ReadWriteCloser, config *Config) (*Session, error) {
if config == nil {
config = DefaultConfig()
}
if err := VerifyConfig(config); err != nil {
return nil, err
}
return newSession(config, conn, false), nil
} | [
"func",
"Server",
"(",
"conn",
"io",
".",
"ReadWriteCloser",
",",
"config",
"*",
"Config",
")",
"(",
"*",
"Session",
",",
"error",
")",
"{",
"if",
"config",
"==",
"nil",
"{",
"config",
"=",
"DefaultConfig",
"(",
")",
"\n",
"}",
"\n",
"if",
"err",
":=",
"VerifyConfig",
"(",
"config",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"return",
"newSession",
"(",
"config",
",",
"conn",
",",
"false",
")",
",",
"nil",
"\n",
"}"
] | // Server is used to initialize a new server-side connection.
// There must be at most one server-side connection. If a nil config is
// provided, the DefaultConfiguration will be used. | [
"Server",
"is",
"used",
"to",
"initialize",
"a",
"new",
"server",
"-",
"side",
"connection",
".",
"There",
"must",
"be",
"at",
"most",
"one",
"server",
"-",
"side",
"connection",
".",
"If",
"a",
"nil",
"config",
"is",
"provided",
"the",
"DefaultConfiguration",
"will",
"be",
"used",
"."
] | 2f1d1f20f75d5404f53b9edf6b53ed5505508675 | https://github.com/hashicorp/yamux/blob/2f1d1f20f75d5404f53b9edf6b53ed5505508675/mux.go#L77-L85 | train |
hashicorp/yamux | mux.go | Client | func Client(conn io.ReadWriteCloser, config *Config) (*Session, error) {
if config == nil {
config = DefaultConfig()
}
if err := VerifyConfig(config); err != nil {
return nil, err
}
return newSession(config, conn, true), nil
} | go | func Client(conn io.ReadWriteCloser, config *Config) (*Session, error) {
if config == nil {
config = DefaultConfig()
}
if err := VerifyConfig(config); err != nil {
return nil, err
}
return newSession(config, conn, true), nil
} | [
"func",
"Client",
"(",
"conn",
"io",
".",
"ReadWriteCloser",
",",
"config",
"*",
"Config",
")",
"(",
"*",
"Session",
",",
"error",
")",
"{",
"if",
"config",
"==",
"nil",
"{",
"config",
"=",
"DefaultConfig",
"(",
")",
"\n",
"}",
"\n\n",
"if",
"err",
":=",
"VerifyConfig",
"(",
"config",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"return",
"newSession",
"(",
"config",
",",
"conn",
",",
"true",
")",
",",
"nil",
"\n",
"}"
] | // Client is used to initialize a new client-side connection.
// There must be at most one client-side connection. | [
"Client",
"is",
"used",
"to",
"initialize",
"a",
"new",
"client",
"-",
"side",
"connection",
".",
"There",
"must",
"be",
"at",
"most",
"one",
"client",
"-",
"side",
"connection",
"."
] | 2f1d1f20f75d5404f53b9edf6b53ed5505508675 | https://github.com/hashicorp/yamux/blob/2f1d1f20f75d5404f53b9edf6b53ed5505508675/mux.go#L89-L98 | train |
hashicorp/yamux | session.go | newSession | func newSession(config *Config, conn io.ReadWriteCloser, client bool) *Session {
logger := config.Logger
if logger == nil {
logger = log.New(config.LogOutput, "", log.LstdFlags)
}
s := &Session{
config: config,
logger: logger,
conn: conn,
bufRead: bufio.NewReader(conn),
pings: make(map[uint32]chan struct{}),
streams: make(map[uint32]*Stream),
inflight: make(map[uint32]struct{}),
synCh: make(chan struct{}, config.AcceptBacklog),
acceptCh: make(chan *Stream, config.AcceptBacklog),
sendCh: make(chan sendReady, 64),
recvDoneCh: make(chan struct{}),
shutdownCh: make(chan struct{}),
}
if client {
s.nextStreamID = 1
} else {
s.nextStreamID = 2
}
go s.recv()
go s.send()
if config.EnableKeepAlive {
go s.keepalive()
}
return s
} | go | func newSession(config *Config, conn io.ReadWriteCloser, client bool) *Session {
logger := config.Logger
if logger == nil {
logger = log.New(config.LogOutput, "", log.LstdFlags)
}
s := &Session{
config: config,
logger: logger,
conn: conn,
bufRead: bufio.NewReader(conn),
pings: make(map[uint32]chan struct{}),
streams: make(map[uint32]*Stream),
inflight: make(map[uint32]struct{}),
synCh: make(chan struct{}, config.AcceptBacklog),
acceptCh: make(chan *Stream, config.AcceptBacklog),
sendCh: make(chan sendReady, 64),
recvDoneCh: make(chan struct{}),
shutdownCh: make(chan struct{}),
}
if client {
s.nextStreamID = 1
} else {
s.nextStreamID = 2
}
go s.recv()
go s.send()
if config.EnableKeepAlive {
go s.keepalive()
}
return s
} | [
"func",
"newSession",
"(",
"config",
"*",
"Config",
",",
"conn",
"io",
".",
"ReadWriteCloser",
",",
"client",
"bool",
")",
"*",
"Session",
"{",
"logger",
":=",
"config",
".",
"Logger",
"\n",
"if",
"logger",
"==",
"nil",
"{",
"logger",
"=",
"log",
".",
"New",
"(",
"config",
".",
"LogOutput",
",",
"\"",
"\"",
",",
"log",
".",
"LstdFlags",
")",
"\n",
"}",
"\n\n",
"s",
":=",
"&",
"Session",
"{",
"config",
":",
"config",
",",
"logger",
":",
"logger",
",",
"conn",
":",
"conn",
",",
"bufRead",
":",
"bufio",
".",
"NewReader",
"(",
"conn",
")",
",",
"pings",
":",
"make",
"(",
"map",
"[",
"uint32",
"]",
"chan",
"struct",
"{",
"}",
")",
",",
"streams",
":",
"make",
"(",
"map",
"[",
"uint32",
"]",
"*",
"Stream",
")",
",",
"inflight",
":",
"make",
"(",
"map",
"[",
"uint32",
"]",
"struct",
"{",
"}",
")",
",",
"synCh",
":",
"make",
"(",
"chan",
"struct",
"{",
"}",
",",
"config",
".",
"AcceptBacklog",
")",
",",
"acceptCh",
":",
"make",
"(",
"chan",
"*",
"Stream",
",",
"config",
".",
"AcceptBacklog",
")",
",",
"sendCh",
":",
"make",
"(",
"chan",
"sendReady",
",",
"64",
")",
",",
"recvDoneCh",
":",
"make",
"(",
"chan",
"struct",
"{",
"}",
")",
",",
"shutdownCh",
":",
"make",
"(",
"chan",
"struct",
"{",
"}",
")",
",",
"}",
"\n",
"if",
"client",
"{",
"s",
".",
"nextStreamID",
"=",
"1",
"\n",
"}",
"else",
"{",
"s",
".",
"nextStreamID",
"=",
"2",
"\n",
"}",
"\n",
"go",
"s",
".",
"recv",
"(",
")",
"\n",
"go",
"s",
".",
"send",
"(",
")",
"\n",
"if",
"config",
".",
"EnableKeepAlive",
"{",
"go",
"s",
".",
"keepalive",
"(",
")",
"\n",
"}",
"\n",
"return",
"s",
"\n",
"}"
] | // newSession is used to construct a new session | [
"newSession",
"is",
"used",
"to",
"construct",
"a",
"new",
"session"
] | 2f1d1f20f75d5404f53b9edf6b53ed5505508675 | https://github.com/hashicorp/yamux/blob/2f1d1f20f75d5404f53b9edf6b53ed5505508675/session.go#L88-L119 | train |
hashicorp/yamux | session.go | NumStreams | func (s *Session) NumStreams() int {
s.streamLock.Lock()
num := len(s.streams)
s.streamLock.Unlock()
return num
} | go | func (s *Session) NumStreams() int {
s.streamLock.Lock()
num := len(s.streams)
s.streamLock.Unlock()
return num
} | [
"func",
"(",
"s",
"*",
"Session",
")",
"NumStreams",
"(",
")",
"int",
"{",
"s",
".",
"streamLock",
".",
"Lock",
"(",
")",
"\n",
"num",
":=",
"len",
"(",
"s",
".",
"streams",
")",
"\n",
"s",
".",
"streamLock",
".",
"Unlock",
"(",
")",
"\n",
"return",
"num",
"\n",
"}"
] | // NumStreams returns the number of currently open streams | [
"NumStreams",
"returns",
"the",
"number",
"of",
"currently",
"open",
"streams"
] | 2f1d1f20f75d5404f53b9edf6b53ed5505508675 | https://github.com/hashicorp/yamux/blob/2f1d1f20f75d5404f53b9edf6b53ed5505508675/session.go#L138-L143 | train |
hashicorp/yamux | session.go | Open | func (s *Session) Open() (net.Conn, error) {
conn, err := s.OpenStream()
if err != nil {
return nil, err
}
return conn, nil
} | go | func (s *Session) Open() (net.Conn, error) {
conn, err := s.OpenStream()
if err != nil {
return nil, err
}
return conn, nil
} | [
"func",
"(",
"s",
"*",
"Session",
")",
"Open",
"(",
")",
"(",
"net",
".",
"Conn",
",",
"error",
")",
"{",
"conn",
",",
"err",
":=",
"s",
".",
"OpenStream",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"return",
"conn",
",",
"nil",
"\n",
"}"
] | // Open is used to create a new stream as a net.Conn | [
"Open",
"is",
"used",
"to",
"create",
"a",
"new",
"stream",
"as",
"a",
"net",
".",
"Conn"
] | 2f1d1f20f75d5404f53b9edf6b53ed5505508675 | https://github.com/hashicorp/yamux/blob/2f1d1f20f75d5404f53b9edf6b53ed5505508675/session.go#L146-L152 | train |
hashicorp/yamux | session.go | Accept | func (s *Session) Accept() (net.Conn, error) {
conn, err := s.AcceptStream()
if err != nil {
return nil, err
}
return conn, err
} | go | func (s *Session) Accept() (net.Conn, error) {
conn, err := s.AcceptStream()
if err != nil {
return nil, err
}
return conn, err
} | [
"func",
"(",
"s",
"*",
"Session",
")",
"Accept",
"(",
")",
"(",
"net",
".",
"Conn",
",",
"error",
")",
"{",
"conn",
",",
"err",
":=",
"s",
".",
"AcceptStream",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"return",
"conn",
",",
"err",
"\n",
"}"
] | // Accept is used to block until the next available stream
// is ready to be accepted. | [
"Accept",
"is",
"used",
"to",
"block",
"until",
"the",
"next",
"available",
"stream",
"is",
"ready",
"to",
"be",
"accepted",
"."
] | 2f1d1f20f75d5404f53b9edf6b53ed5505508675 | https://github.com/hashicorp/yamux/blob/2f1d1f20f75d5404f53b9edf6b53ed5505508675/session.go#L201-L207 | train |
hashicorp/yamux | session.go | Close | func (s *Session) Close() error {
s.shutdownLock.Lock()
defer s.shutdownLock.Unlock()
if s.shutdown {
return nil
}
s.shutdown = true
if s.shutdownErr == nil {
s.shutdownErr = ErrSessionShutdown
}
close(s.shutdownCh)
s.conn.Close()
<-s.recvDoneCh
s.streamLock.Lock()
defer s.streamLock.Unlock()
for _, stream := range s.streams {
stream.forceClose()
}
return nil
} | go | func (s *Session) Close() error {
s.shutdownLock.Lock()
defer s.shutdownLock.Unlock()
if s.shutdown {
return nil
}
s.shutdown = true
if s.shutdownErr == nil {
s.shutdownErr = ErrSessionShutdown
}
close(s.shutdownCh)
s.conn.Close()
<-s.recvDoneCh
s.streamLock.Lock()
defer s.streamLock.Unlock()
for _, stream := range s.streams {
stream.forceClose()
}
return nil
} | [
"func",
"(",
"s",
"*",
"Session",
")",
"Close",
"(",
")",
"error",
"{",
"s",
".",
"shutdownLock",
".",
"Lock",
"(",
")",
"\n",
"defer",
"s",
".",
"shutdownLock",
".",
"Unlock",
"(",
")",
"\n\n",
"if",
"s",
".",
"shutdown",
"{",
"return",
"nil",
"\n",
"}",
"\n",
"s",
".",
"shutdown",
"=",
"true",
"\n",
"if",
"s",
".",
"shutdownErr",
"==",
"nil",
"{",
"s",
".",
"shutdownErr",
"=",
"ErrSessionShutdown",
"\n",
"}",
"\n",
"close",
"(",
"s",
".",
"shutdownCh",
")",
"\n",
"s",
".",
"conn",
".",
"Close",
"(",
")",
"\n",
"<-",
"s",
".",
"recvDoneCh",
"\n\n",
"s",
".",
"streamLock",
".",
"Lock",
"(",
")",
"\n",
"defer",
"s",
".",
"streamLock",
".",
"Unlock",
"(",
")",
"\n",
"for",
"_",
",",
"stream",
":=",
"range",
"s",
".",
"streams",
"{",
"stream",
".",
"forceClose",
"(",
")",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}"
] | // Close is used to close the session and all streams.
// Attempts to send a GoAway before closing the connection. | [
"Close",
"is",
"used",
"to",
"close",
"the",
"session",
"and",
"all",
"streams",
".",
"Attempts",
"to",
"send",
"a",
"GoAway",
"before",
"closing",
"the",
"connection",
"."
] | 2f1d1f20f75d5404f53b9edf6b53ed5505508675 | https://github.com/hashicorp/yamux/blob/2f1d1f20f75d5404f53b9edf6b53ed5505508675/session.go#L225-L246 | train |
hashicorp/yamux | session.go | exitErr | func (s *Session) exitErr(err error) {
s.shutdownLock.Lock()
if s.shutdownErr == nil {
s.shutdownErr = err
}
s.shutdownLock.Unlock()
s.Close()
} | go | func (s *Session) exitErr(err error) {
s.shutdownLock.Lock()
if s.shutdownErr == nil {
s.shutdownErr = err
}
s.shutdownLock.Unlock()
s.Close()
} | [
"func",
"(",
"s",
"*",
"Session",
")",
"exitErr",
"(",
"err",
"error",
")",
"{",
"s",
".",
"shutdownLock",
".",
"Lock",
"(",
")",
"\n",
"if",
"s",
".",
"shutdownErr",
"==",
"nil",
"{",
"s",
".",
"shutdownErr",
"=",
"err",
"\n",
"}",
"\n",
"s",
".",
"shutdownLock",
".",
"Unlock",
"(",
")",
"\n",
"s",
".",
"Close",
"(",
")",
"\n",
"}"
] | // exitErr is used to handle an error that is causing the
// session to terminate. | [
"exitErr",
"is",
"used",
"to",
"handle",
"an",
"error",
"that",
"is",
"causing",
"the",
"session",
"to",
"terminate",
"."
] | 2f1d1f20f75d5404f53b9edf6b53ed5505508675 | https://github.com/hashicorp/yamux/blob/2f1d1f20f75d5404f53b9edf6b53ed5505508675/session.go#L250-L257 | train |
hashicorp/yamux | session.go | GoAway | func (s *Session) GoAway() error {
return s.waitForSend(s.goAway(goAwayNormal), nil)
} | go | func (s *Session) GoAway() error {
return s.waitForSend(s.goAway(goAwayNormal), nil)
} | [
"func",
"(",
"s",
"*",
"Session",
")",
"GoAway",
"(",
")",
"error",
"{",
"return",
"s",
".",
"waitForSend",
"(",
"s",
".",
"goAway",
"(",
"goAwayNormal",
")",
",",
"nil",
")",
"\n",
"}"
] | // GoAway can be used to prevent accepting further
// connections. It does not close the underlying conn. | [
"GoAway",
"can",
"be",
"used",
"to",
"prevent",
"accepting",
"further",
"connections",
".",
"It",
"does",
"not",
"close",
"the",
"underlying",
"conn",
"."
] | 2f1d1f20f75d5404f53b9edf6b53ed5505508675 | https://github.com/hashicorp/yamux/blob/2f1d1f20f75d5404f53b9edf6b53ed5505508675/session.go#L261-L263 | train |
hashicorp/yamux | session.go | goAway | func (s *Session) goAway(reason uint32) header {
atomic.SwapInt32(&s.localGoAway, 1)
hdr := header(make([]byte, headerSize))
hdr.encode(typeGoAway, 0, 0, reason)
return hdr
} | go | func (s *Session) goAway(reason uint32) header {
atomic.SwapInt32(&s.localGoAway, 1)
hdr := header(make([]byte, headerSize))
hdr.encode(typeGoAway, 0, 0, reason)
return hdr
} | [
"func",
"(",
"s",
"*",
"Session",
")",
"goAway",
"(",
"reason",
"uint32",
")",
"header",
"{",
"atomic",
".",
"SwapInt32",
"(",
"&",
"s",
".",
"localGoAway",
",",
"1",
")",
"\n",
"hdr",
":=",
"header",
"(",
"make",
"(",
"[",
"]",
"byte",
",",
"headerSize",
")",
")",
"\n",
"hdr",
".",
"encode",
"(",
"typeGoAway",
",",
"0",
",",
"0",
",",
"reason",
")",
"\n",
"return",
"hdr",
"\n",
"}"
] | // goAway is used to send a goAway message | [
"goAway",
"is",
"used",
"to",
"send",
"a",
"goAway",
"message"
] | 2f1d1f20f75d5404f53b9edf6b53ed5505508675 | https://github.com/hashicorp/yamux/blob/2f1d1f20f75d5404f53b9edf6b53ed5505508675/session.go#L266-L271 | train |
hashicorp/yamux | session.go | Ping | func (s *Session) Ping() (time.Duration, error) {
// Get a channel for the ping
ch := make(chan struct{})
// Get a new ping id, mark as pending
s.pingLock.Lock()
id := s.pingID
s.pingID++
s.pings[id] = ch
s.pingLock.Unlock()
// Send the ping request
hdr := header(make([]byte, headerSize))
hdr.encode(typePing, flagSYN, 0, id)
if err := s.waitForSend(hdr, nil); err != nil {
return 0, err
}
// Wait for a response
start := time.Now()
select {
case <-ch:
case <-time.After(s.config.ConnectionWriteTimeout):
s.pingLock.Lock()
delete(s.pings, id) // Ignore it if a response comes later.
s.pingLock.Unlock()
return 0, ErrTimeout
case <-s.shutdownCh:
return 0, ErrSessionShutdown
}
// Compute the RTT
return time.Now().Sub(start), nil
} | go | func (s *Session) Ping() (time.Duration, error) {
// Get a channel for the ping
ch := make(chan struct{})
// Get a new ping id, mark as pending
s.pingLock.Lock()
id := s.pingID
s.pingID++
s.pings[id] = ch
s.pingLock.Unlock()
// Send the ping request
hdr := header(make([]byte, headerSize))
hdr.encode(typePing, flagSYN, 0, id)
if err := s.waitForSend(hdr, nil); err != nil {
return 0, err
}
// Wait for a response
start := time.Now()
select {
case <-ch:
case <-time.After(s.config.ConnectionWriteTimeout):
s.pingLock.Lock()
delete(s.pings, id) // Ignore it if a response comes later.
s.pingLock.Unlock()
return 0, ErrTimeout
case <-s.shutdownCh:
return 0, ErrSessionShutdown
}
// Compute the RTT
return time.Now().Sub(start), nil
} | [
"func",
"(",
"s",
"*",
"Session",
")",
"Ping",
"(",
")",
"(",
"time",
".",
"Duration",
",",
"error",
")",
"{",
"// Get a channel for the ping",
"ch",
":=",
"make",
"(",
"chan",
"struct",
"{",
"}",
")",
"\n\n",
"// Get a new ping id, mark as pending",
"s",
".",
"pingLock",
".",
"Lock",
"(",
")",
"\n",
"id",
":=",
"s",
".",
"pingID",
"\n",
"s",
".",
"pingID",
"++",
"\n",
"s",
".",
"pings",
"[",
"id",
"]",
"=",
"ch",
"\n",
"s",
".",
"pingLock",
".",
"Unlock",
"(",
")",
"\n\n",
"// Send the ping request",
"hdr",
":=",
"header",
"(",
"make",
"(",
"[",
"]",
"byte",
",",
"headerSize",
")",
")",
"\n",
"hdr",
".",
"encode",
"(",
"typePing",
",",
"flagSYN",
",",
"0",
",",
"id",
")",
"\n",
"if",
"err",
":=",
"s",
".",
"waitForSend",
"(",
"hdr",
",",
"nil",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"0",
",",
"err",
"\n",
"}",
"\n\n",
"// Wait for a response",
"start",
":=",
"time",
".",
"Now",
"(",
")",
"\n",
"select",
"{",
"case",
"<-",
"ch",
":",
"case",
"<-",
"time",
".",
"After",
"(",
"s",
".",
"config",
".",
"ConnectionWriteTimeout",
")",
":",
"s",
".",
"pingLock",
".",
"Lock",
"(",
")",
"\n",
"delete",
"(",
"s",
".",
"pings",
",",
"id",
")",
"// Ignore it if a response comes later.",
"\n",
"s",
".",
"pingLock",
".",
"Unlock",
"(",
")",
"\n",
"return",
"0",
",",
"ErrTimeout",
"\n",
"case",
"<-",
"s",
".",
"shutdownCh",
":",
"return",
"0",
",",
"ErrSessionShutdown",
"\n",
"}",
"\n\n",
"// Compute the RTT",
"return",
"time",
".",
"Now",
"(",
")",
".",
"Sub",
"(",
"start",
")",
",",
"nil",
"\n",
"}"
] | // Ping is used to measure the RTT response time | [
"Ping",
"is",
"used",
"to",
"measure",
"the",
"RTT",
"response",
"time"
] | 2f1d1f20f75d5404f53b9edf6b53ed5505508675 | https://github.com/hashicorp/yamux/blob/2f1d1f20f75d5404f53b9edf6b53ed5505508675/session.go#L274-L307 | train |
hashicorp/yamux | session.go | keepalive | func (s *Session) keepalive() {
for {
select {
case <-time.After(s.config.KeepAliveInterval):
_, err := s.Ping()
if err != nil {
if err != ErrSessionShutdown {
s.logger.Printf("[ERR] yamux: keepalive failed: %v", err)
s.exitErr(ErrKeepAliveTimeout)
}
return
}
case <-s.shutdownCh:
return
}
}
} | go | func (s *Session) keepalive() {
for {
select {
case <-time.After(s.config.KeepAliveInterval):
_, err := s.Ping()
if err != nil {
if err != ErrSessionShutdown {
s.logger.Printf("[ERR] yamux: keepalive failed: %v", err)
s.exitErr(ErrKeepAliveTimeout)
}
return
}
case <-s.shutdownCh:
return
}
}
} | [
"func",
"(",
"s",
"*",
"Session",
")",
"keepalive",
"(",
")",
"{",
"for",
"{",
"select",
"{",
"case",
"<-",
"time",
".",
"After",
"(",
"s",
".",
"config",
".",
"KeepAliveInterval",
")",
":",
"_",
",",
"err",
":=",
"s",
".",
"Ping",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"if",
"err",
"!=",
"ErrSessionShutdown",
"{",
"s",
".",
"logger",
".",
"Printf",
"(",
"\"",
"\"",
",",
"err",
")",
"\n",
"s",
".",
"exitErr",
"(",
"ErrKeepAliveTimeout",
")",
"\n",
"}",
"\n",
"return",
"\n",
"}",
"\n",
"case",
"<-",
"s",
".",
"shutdownCh",
":",
"return",
"\n",
"}",
"\n",
"}",
"\n",
"}"
] | // keepalive is a long running goroutine that periodically does
// a ping to keep the connection alive. | [
"keepalive",
"is",
"a",
"long",
"running",
"goroutine",
"that",
"periodically",
"does",
"a",
"ping",
"to",
"keep",
"the",
"connection",
"alive",
"."
] | 2f1d1f20f75d5404f53b9edf6b53ed5505508675 | https://github.com/hashicorp/yamux/blob/2f1d1f20f75d5404f53b9edf6b53ed5505508675/session.go#L311-L327 | train |
hashicorp/yamux | session.go | waitForSend | func (s *Session) waitForSend(hdr header, body io.Reader) error {
errCh := make(chan error, 1)
return s.waitForSendErr(hdr, body, errCh)
} | go | func (s *Session) waitForSend(hdr header, body io.Reader) error {
errCh := make(chan error, 1)
return s.waitForSendErr(hdr, body, errCh)
} | [
"func",
"(",
"s",
"*",
"Session",
")",
"waitForSend",
"(",
"hdr",
"header",
",",
"body",
"io",
".",
"Reader",
")",
"error",
"{",
"errCh",
":=",
"make",
"(",
"chan",
"error",
",",
"1",
")",
"\n",
"return",
"s",
".",
"waitForSendErr",
"(",
"hdr",
",",
"body",
",",
"errCh",
")",
"\n",
"}"
] | // waitForSendErr waits to send a header, checking for a potential shutdown | [
"waitForSendErr",
"waits",
"to",
"send",
"a",
"header",
"checking",
"for",
"a",
"potential",
"shutdown"
] | 2f1d1f20f75d5404f53b9edf6b53ed5505508675 | https://github.com/hashicorp/yamux/blob/2f1d1f20f75d5404f53b9edf6b53ed5505508675/session.go#L330-L333 | train |
hashicorp/yamux | session.go | waitForSendErr | func (s *Session) waitForSendErr(hdr header, body io.Reader, errCh chan error) error {
t := timerPool.Get()
timer := t.(*time.Timer)
timer.Reset(s.config.ConnectionWriteTimeout)
defer func() {
timer.Stop()
select {
case <-timer.C:
default:
}
timerPool.Put(t)
}()
ready := sendReady{Hdr: hdr, Body: body, Err: errCh}
select {
case s.sendCh <- ready:
case <-s.shutdownCh:
return ErrSessionShutdown
case <-timer.C:
return ErrConnectionWriteTimeout
}
select {
case err := <-errCh:
return err
case <-s.shutdownCh:
return ErrSessionShutdown
case <-timer.C:
return ErrConnectionWriteTimeout
}
} | go | func (s *Session) waitForSendErr(hdr header, body io.Reader, errCh chan error) error {
t := timerPool.Get()
timer := t.(*time.Timer)
timer.Reset(s.config.ConnectionWriteTimeout)
defer func() {
timer.Stop()
select {
case <-timer.C:
default:
}
timerPool.Put(t)
}()
ready := sendReady{Hdr: hdr, Body: body, Err: errCh}
select {
case s.sendCh <- ready:
case <-s.shutdownCh:
return ErrSessionShutdown
case <-timer.C:
return ErrConnectionWriteTimeout
}
select {
case err := <-errCh:
return err
case <-s.shutdownCh:
return ErrSessionShutdown
case <-timer.C:
return ErrConnectionWriteTimeout
}
} | [
"func",
"(",
"s",
"*",
"Session",
")",
"waitForSendErr",
"(",
"hdr",
"header",
",",
"body",
"io",
".",
"Reader",
",",
"errCh",
"chan",
"error",
")",
"error",
"{",
"t",
":=",
"timerPool",
".",
"Get",
"(",
")",
"\n",
"timer",
":=",
"t",
".",
"(",
"*",
"time",
".",
"Timer",
")",
"\n",
"timer",
".",
"Reset",
"(",
"s",
".",
"config",
".",
"ConnectionWriteTimeout",
")",
"\n",
"defer",
"func",
"(",
")",
"{",
"timer",
".",
"Stop",
"(",
")",
"\n",
"select",
"{",
"case",
"<-",
"timer",
".",
"C",
":",
"default",
":",
"}",
"\n",
"timerPool",
".",
"Put",
"(",
"t",
")",
"\n",
"}",
"(",
")",
"\n\n",
"ready",
":=",
"sendReady",
"{",
"Hdr",
":",
"hdr",
",",
"Body",
":",
"body",
",",
"Err",
":",
"errCh",
"}",
"\n",
"select",
"{",
"case",
"s",
".",
"sendCh",
"<-",
"ready",
":",
"case",
"<-",
"s",
".",
"shutdownCh",
":",
"return",
"ErrSessionShutdown",
"\n",
"case",
"<-",
"timer",
".",
"C",
":",
"return",
"ErrConnectionWriteTimeout",
"\n",
"}",
"\n\n",
"select",
"{",
"case",
"err",
":=",
"<-",
"errCh",
":",
"return",
"err",
"\n",
"case",
"<-",
"s",
".",
"shutdownCh",
":",
"return",
"ErrSessionShutdown",
"\n",
"case",
"<-",
"timer",
".",
"C",
":",
"return",
"ErrConnectionWriteTimeout",
"\n",
"}",
"\n",
"}"
] | // waitForSendErr waits to send a header with optional data, checking for a
// potential shutdown. Since there's the expectation that sends can happen
// in a timely manner, we enforce the connection write timeout here. | [
"waitForSendErr",
"waits",
"to",
"send",
"a",
"header",
"with",
"optional",
"data",
"checking",
"for",
"a",
"potential",
"shutdown",
".",
"Since",
"there",
"s",
"the",
"expectation",
"that",
"sends",
"can",
"happen",
"in",
"a",
"timely",
"manner",
"we",
"enforce",
"the",
"connection",
"write",
"timeout",
"here",
"."
] | 2f1d1f20f75d5404f53b9edf6b53ed5505508675 | https://github.com/hashicorp/yamux/blob/2f1d1f20f75d5404f53b9edf6b53ed5505508675/session.go#L338-L368 | train |
hashicorp/yamux | session.go | sendNoWait | func (s *Session) sendNoWait(hdr header) error {
t := timerPool.Get()
timer := t.(*time.Timer)
timer.Reset(s.config.ConnectionWriteTimeout)
defer func() {
timer.Stop()
select {
case <-timer.C:
default:
}
timerPool.Put(t)
}()
select {
case s.sendCh <- sendReady{Hdr: hdr}:
return nil
case <-s.shutdownCh:
return ErrSessionShutdown
case <-timer.C:
return ErrConnectionWriteTimeout
}
} | go | func (s *Session) sendNoWait(hdr header) error {
t := timerPool.Get()
timer := t.(*time.Timer)
timer.Reset(s.config.ConnectionWriteTimeout)
defer func() {
timer.Stop()
select {
case <-timer.C:
default:
}
timerPool.Put(t)
}()
select {
case s.sendCh <- sendReady{Hdr: hdr}:
return nil
case <-s.shutdownCh:
return ErrSessionShutdown
case <-timer.C:
return ErrConnectionWriteTimeout
}
} | [
"func",
"(",
"s",
"*",
"Session",
")",
"sendNoWait",
"(",
"hdr",
"header",
")",
"error",
"{",
"t",
":=",
"timerPool",
".",
"Get",
"(",
")",
"\n",
"timer",
":=",
"t",
".",
"(",
"*",
"time",
".",
"Timer",
")",
"\n",
"timer",
".",
"Reset",
"(",
"s",
".",
"config",
".",
"ConnectionWriteTimeout",
")",
"\n",
"defer",
"func",
"(",
")",
"{",
"timer",
".",
"Stop",
"(",
")",
"\n",
"select",
"{",
"case",
"<-",
"timer",
".",
"C",
":",
"default",
":",
"}",
"\n",
"timerPool",
".",
"Put",
"(",
"t",
")",
"\n",
"}",
"(",
")",
"\n\n",
"select",
"{",
"case",
"s",
".",
"sendCh",
"<-",
"sendReady",
"{",
"Hdr",
":",
"hdr",
"}",
":",
"return",
"nil",
"\n",
"case",
"<-",
"s",
".",
"shutdownCh",
":",
"return",
"ErrSessionShutdown",
"\n",
"case",
"<-",
"timer",
".",
"C",
":",
"return",
"ErrConnectionWriteTimeout",
"\n",
"}",
"\n",
"}"
] | // sendNoWait does a send without waiting. Since there's the expectation that
// the send happens right here, we enforce the connection write timeout if we
// can't queue the header to be sent. | [
"sendNoWait",
"does",
"a",
"send",
"without",
"waiting",
".",
"Since",
"there",
"s",
"the",
"expectation",
"that",
"the",
"send",
"happens",
"right",
"here",
"we",
"enforce",
"the",
"connection",
"write",
"timeout",
"if",
"we",
"can",
"t",
"queue",
"the",
"header",
"to",
"be",
"sent",
"."
] | 2f1d1f20f75d5404f53b9edf6b53ed5505508675 | https://github.com/hashicorp/yamux/blob/2f1d1f20f75d5404f53b9edf6b53ed5505508675/session.go#L373-L394 | train |
hashicorp/yamux | session.go | send | func (s *Session) send() {
for {
select {
case ready := <-s.sendCh:
// Send a header if ready
if ready.Hdr != nil {
sent := 0
for sent < len(ready.Hdr) {
n, err := s.conn.Write(ready.Hdr[sent:])
if err != nil {
s.logger.Printf("[ERR] yamux: Failed to write header: %v", err)
asyncSendErr(ready.Err, err)
s.exitErr(err)
return
}
sent += n
}
}
// Send data from a body if given
if ready.Body != nil {
_, err := io.Copy(s.conn, ready.Body)
if err != nil {
s.logger.Printf("[ERR] yamux: Failed to write body: %v", err)
asyncSendErr(ready.Err, err)
s.exitErr(err)
return
}
}
// No error, successful send
asyncSendErr(ready.Err, nil)
case <-s.shutdownCh:
return
}
}
} | go | func (s *Session) send() {
for {
select {
case ready := <-s.sendCh:
// Send a header if ready
if ready.Hdr != nil {
sent := 0
for sent < len(ready.Hdr) {
n, err := s.conn.Write(ready.Hdr[sent:])
if err != nil {
s.logger.Printf("[ERR] yamux: Failed to write header: %v", err)
asyncSendErr(ready.Err, err)
s.exitErr(err)
return
}
sent += n
}
}
// Send data from a body if given
if ready.Body != nil {
_, err := io.Copy(s.conn, ready.Body)
if err != nil {
s.logger.Printf("[ERR] yamux: Failed to write body: %v", err)
asyncSendErr(ready.Err, err)
s.exitErr(err)
return
}
}
// No error, successful send
asyncSendErr(ready.Err, nil)
case <-s.shutdownCh:
return
}
}
} | [
"func",
"(",
"s",
"*",
"Session",
")",
"send",
"(",
")",
"{",
"for",
"{",
"select",
"{",
"case",
"ready",
":=",
"<-",
"s",
".",
"sendCh",
":",
"// Send a header if ready",
"if",
"ready",
".",
"Hdr",
"!=",
"nil",
"{",
"sent",
":=",
"0",
"\n",
"for",
"sent",
"<",
"len",
"(",
"ready",
".",
"Hdr",
")",
"{",
"n",
",",
"err",
":=",
"s",
".",
"conn",
".",
"Write",
"(",
"ready",
".",
"Hdr",
"[",
"sent",
":",
"]",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"s",
".",
"logger",
".",
"Printf",
"(",
"\"",
"\"",
",",
"err",
")",
"\n",
"asyncSendErr",
"(",
"ready",
".",
"Err",
",",
"err",
")",
"\n",
"s",
".",
"exitErr",
"(",
"err",
")",
"\n",
"return",
"\n",
"}",
"\n",
"sent",
"+=",
"n",
"\n",
"}",
"\n",
"}",
"\n\n",
"// Send data from a body if given",
"if",
"ready",
".",
"Body",
"!=",
"nil",
"{",
"_",
",",
"err",
":=",
"io",
".",
"Copy",
"(",
"s",
".",
"conn",
",",
"ready",
".",
"Body",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"s",
".",
"logger",
".",
"Printf",
"(",
"\"",
"\"",
",",
"err",
")",
"\n",
"asyncSendErr",
"(",
"ready",
".",
"Err",
",",
"err",
")",
"\n",
"s",
".",
"exitErr",
"(",
"err",
")",
"\n",
"return",
"\n",
"}",
"\n",
"}",
"\n\n",
"// No error, successful send",
"asyncSendErr",
"(",
"ready",
".",
"Err",
",",
"nil",
")",
"\n",
"case",
"<-",
"s",
".",
"shutdownCh",
":",
"return",
"\n",
"}",
"\n",
"}",
"\n",
"}"
] | // send is a long running goroutine that sends data | [
"send",
"is",
"a",
"long",
"running",
"goroutine",
"that",
"sends",
"data"
] | 2f1d1f20f75d5404f53b9edf6b53ed5505508675 | https://github.com/hashicorp/yamux/blob/2f1d1f20f75d5404f53b9edf6b53ed5505508675/session.go#L397-L433 | train |
hashicorp/yamux | session.go | recv | func (s *Session) recv() {
if err := s.recvLoop(); err != nil {
s.exitErr(err)
}
} | go | func (s *Session) recv() {
if err := s.recvLoop(); err != nil {
s.exitErr(err)
}
} | [
"func",
"(",
"s",
"*",
"Session",
")",
"recv",
"(",
")",
"{",
"if",
"err",
":=",
"s",
".",
"recvLoop",
"(",
")",
";",
"err",
"!=",
"nil",
"{",
"s",
".",
"exitErr",
"(",
"err",
")",
"\n",
"}",
"\n",
"}"
] | // recv is a long running goroutine that accepts new data | [
"recv",
"is",
"a",
"long",
"running",
"goroutine",
"that",
"accepts",
"new",
"data"
] | 2f1d1f20f75d5404f53b9edf6b53ed5505508675 | https://github.com/hashicorp/yamux/blob/2f1d1f20f75d5404f53b9edf6b53ed5505508675/session.go#L436-L440 | train |
hashicorp/yamux | session.go | recvLoop | func (s *Session) recvLoop() error {
defer close(s.recvDoneCh)
hdr := header(make([]byte, headerSize))
for {
// Read the header
if _, err := io.ReadFull(s.bufRead, hdr); err != nil {
if err != io.EOF && !strings.Contains(err.Error(), "closed") && !strings.Contains(err.Error(), "reset by peer") {
s.logger.Printf("[ERR] yamux: Failed to read header: %v", err)
}
return err
}
// Verify the version
if hdr.Version() != protoVersion {
s.logger.Printf("[ERR] yamux: Invalid protocol version: %d", hdr.Version())
return ErrInvalidVersion
}
mt := hdr.MsgType()
if mt < typeData || mt > typeGoAway {
return ErrInvalidMsgType
}
if err := handlers[mt](s, hdr); err != nil {
return err
}
}
} | go | func (s *Session) recvLoop() error {
defer close(s.recvDoneCh)
hdr := header(make([]byte, headerSize))
for {
// Read the header
if _, err := io.ReadFull(s.bufRead, hdr); err != nil {
if err != io.EOF && !strings.Contains(err.Error(), "closed") && !strings.Contains(err.Error(), "reset by peer") {
s.logger.Printf("[ERR] yamux: Failed to read header: %v", err)
}
return err
}
// Verify the version
if hdr.Version() != protoVersion {
s.logger.Printf("[ERR] yamux: Invalid protocol version: %d", hdr.Version())
return ErrInvalidVersion
}
mt := hdr.MsgType()
if mt < typeData || mt > typeGoAway {
return ErrInvalidMsgType
}
if err := handlers[mt](s, hdr); err != nil {
return err
}
}
} | [
"func",
"(",
"s",
"*",
"Session",
")",
"recvLoop",
"(",
")",
"error",
"{",
"defer",
"close",
"(",
"s",
".",
"recvDoneCh",
")",
"\n",
"hdr",
":=",
"header",
"(",
"make",
"(",
"[",
"]",
"byte",
",",
"headerSize",
")",
")",
"\n",
"for",
"{",
"// Read the header",
"if",
"_",
",",
"err",
":=",
"io",
".",
"ReadFull",
"(",
"s",
".",
"bufRead",
",",
"hdr",
")",
";",
"err",
"!=",
"nil",
"{",
"if",
"err",
"!=",
"io",
".",
"EOF",
"&&",
"!",
"strings",
".",
"Contains",
"(",
"err",
".",
"Error",
"(",
")",
",",
"\"",
"\"",
")",
"&&",
"!",
"strings",
".",
"Contains",
"(",
"err",
".",
"Error",
"(",
")",
",",
"\"",
"\"",
")",
"{",
"s",
".",
"logger",
".",
"Printf",
"(",
"\"",
"\"",
",",
"err",
")",
"\n",
"}",
"\n",
"return",
"err",
"\n",
"}",
"\n\n",
"// Verify the version",
"if",
"hdr",
".",
"Version",
"(",
")",
"!=",
"protoVersion",
"{",
"s",
".",
"logger",
".",
"Printf",
"(",
"\"",
"\"",
",",
"hdr",
".",
"Version",
"(",
")",
")",
"\n",
"return",
"ErrInvalidVersion",
"\n",
"}",
"\n\n",
"mt",
":=",
"hdr",
".",
"MsgType",
"(",
")",
"\n",
"if",
"mt",
"<",
"typeData",
"||",
"mt",
">",
"typeGoAway",
"{",
"return",
"ErrInvalidMsgType",
"\n",
"}",
"\n\n",
"if",
"err",
":=",
"handlers",
"[",
"mt",
"]",
"(",
"s",
",",
"hdr",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"}",
"\n",
"}"
] | // recvLoop continues to receive data until a fatal error is encountered | [
"recvLoop",
"continues",
"to",
"receive",
"data",
"until",
"a",
"fatal",
"error",
"is",
"encountered"
] | 2f1d1f20f75d5404f53b9edf6b53ed5505508675 | https://github.com/hashicorp/yamux/blob/2f1d1f20f75d5404f53b9edf6b53ed5505508675/session.go#L453-L480 | train |
hashicorp/yamux | session.go | handleStreamMessage | func (s *Session) handleStreamMessage(hdr header) error {
// Check for a new stream creation
id := hdr.StreamID()
flags := hdr.Flags()
if flags&flagSYN == flagSYN {
if err := s.incomingStream(id); err != nil {
return err
}
}
// Get the stream
s.streamLock.Lock()
stream := s.streams[id]
s.streamLock.Unlock()
// If we do not have a stream, likely we sent a RST
if stream == nil {
// Drain any data on the wire
if hdr.MsgType() == typeData && hdr.Length() > 0 {
s.logger.Printf("[WARN] yamux: Discarding data for stream: %d", id)
if _, err := io.CopyN(ioutil.Discard, s.bufRead, int64(hdr.Length())); err != nil {
s.logger.Printf("[ERR] yamux: Failed to discard data: %v", err)
return nil
}
} else {
s.logger.Printf("[WARN] yamux: frame for missing stream: %v", hdr)
}
return nil
}
// Check if this is a window update
if hdr.MsgType() == typeWindowUpdate {
if err := stream.incrSendWindow(hdr, flags); err != nil {
if sendErr := s.sendNoWait(s.goAway(goAwayProtoErr)); sendErr != nil {
s.logger.Printf("[WARN] yamux: failed to send go away: %v", sendErr)
}
return err
}
return nil
}
// Read the new data
if err := stream.readData(hdr, flags, s.bufRead); err != nil {
if sendErr := s.sendNoWait(s.goAway(goAwayProtoErr)); sendErr != nil {
s.logger.Printf("[WARN] yamux: failed to send go away: %v", sendErr)
}
return err
}
return nil
} | go | func (s *Session) handleStreamMessage(hdr header) error {
// Check for a new stream creation
id := hdr.StreamID()
flags := hdr.Flags()
if flags&flagSYN == flagSYN {
if err := s.incomingStream(id); err != nil {
return err
}
}
// Get the stream
s.streamLock.Lock()
stream := s.streams[id]
s.streamLock.Unlock()
// If we do not have a stream, likely we sent a RST
if stream == nil {
// Drain any data on the wire
if hdr.MsgType() == typeData && hdr.Length() > 0 {
s.logger.Printf("[WARN] yamux: Discarding data for stream: %d", id)
if _, err := io.CopyN(ioutil.Discard, s.bufRead, int64(hdr.Length())); err != nil {
s.logger.Printf("[ERR] yamux: Failed to discard data: %v", err)
return nil
}
} else {
s.logger.Printf("[WARN] yamux: frame for missing stream: %v", hdr)
}
return nil
}
// Check if this is a window update
if hdr.MsgType() == typeWindowUpdate {
if err := stream.incrSendWindow(hdr, flags); err != nil {
if sendErr := s.sendNoWait(s.goAway(goAwayProtoErr)); sendErr != nil {
s.logger.Printf("[WARN] yamux: failed to send go away: %v", sendErr)
}
return err
}
return nil
}
// Read the new data
if err := stream.readData(hdr, flags, s.bufRead); err != nil {
if sendErr := s.sendNoWait(s.goAway(goAwayProtoErr)); sendErr != nil {
s.logger.Printf("[WARN] yamux: failed to send go away: %v", sendErr)
}
return err
}
return nil
} | [
"func",
"(",
"s",
"*",
"Session",
")",
"handleStreamMessage",
"(",
"hdr",
"header",
")",
"error",
"{",
"// Check for a new stream creation",
"id",
":=",
"hdr",
".",
"StreamID",
"(",
")",
"\n",
"flags",
":=",
"hdr",
".",
"Flags",
"(",
")",
"\n",
"if",
"flags",
"&",
"flagSYN",
"==",
"flagSYN",
"{",
"if",
"err",
":=",
"s",
".",
"incomingStream",
"(",
"id",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"}",
"\n\n",
"// Get the stream",
"s",
".",
"streamLock",
".",
"Lock",
"(",
")",
"\n",
"stream",
":=",
"s",
".",
"streams",
"[",
"id",
"]",
"\n",
"s",
".",
"streamLock",
".",
"Unlock",
"(",
")",
"\n\n",
"// If we do not have a stream, likely we sent a RST",
"if",
"stream",
"==",
"nil",
"{",
"// Drain any data on the wire",
"if",
"hdr",
".",
"MsgType",
"(",
")",
"==",
"typeData",
"&&",
"hdr",
".",
"Length",
"(",
")",
">",
"0",
"{",
"s",
".",
"logger",
".",
"Printf",
"(",
"\"",
"\"",
",",
"id",
")",
"\n",
"if",
"_",
",",
"err",
":=",
"io",
".",
"CopyN",
"(",
"ioutil",
".",
"Discard",
",",
"s",
".",
"bufRead",
",",
"int64",
"(",
"hdr",
".",
"Length",
"(",
")",
")",
")",
";",
"err",
"!=",
"nil",
"{",
"s",
".",
"logger",
".",
"Printf",
"(",
"\"",
"\"",
",",
"err",
")",
"\n",
"return",
"nil",
"\n",
"}",
"\n",
"}",
"else",
"{",
"s",
".",
"logger",
".",
"Printf",
"(",
"\"",
"\"",
",",
"hdr",
")",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}",
"\n\n",
"// Check if this is a window update",
"if",
"hdr",
".",
"MsgType",
"(",
")",
"==",
"typeWindowUpdate",
"{",
"if",
"err",
":=",
"stream",
".",
"incrSendWindow",
"(",
"hdr",
",",
"flags",
")",
";",
"err",
"!=",
"nil",
"{",
"if",
"sendErr",
":=",
"s",
".",
"sendNoWait",
"(",
"s",
".",
"goAway",
"(",
"goAwayProtoErr",
")",
")",
";",
"sendErr",
"!=",
"nil",
"{",
"s",
".",
"logger",
".",
"Printf",
"(",
"\"",
"\"",
",",
"sendErr",
")",
"\n",
"}",
"\n",
"return",
"err",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}",
"\n\n",
"// Read the new data",
"if",
"err",
":=",
"stream",
".",
"readData",
"(",
"hdr",
",",
"flags",
",",
"s",
".",
"bufRead",
")",
";",
"err",
"!=",
"nil",
"{",
"if",
"sendErr",
":=",
"s",
".",
"sendNoWait",
"(",
"s",
".",
"goAway",
"(",
"goAwayProtoErr",
")",
")",
";",
"sendErr",
"!=",
"nil",
"{",
"s",
".",
"logger",
".",
"Printf",
"(",
"\"",
"\"",
",",
"sendErr",
")",
"\n",
"}",
"\n",
"return",
"err",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}"
] | // handleStreamMessage handles either a data or window update frame | [
"handleStreamMessage",
"handles",
"either",
"a",
"data",
"or",
"window",
"update",
"frame"
] | 2f1d1f20f75d5404f53b9edf6b53ed5505508675 | https://github.com/hashicorp/yamux/blob/2f1d1f20f75d5404f53b9edf6b53ed5505508675/session.go#L483-L532 | train |
hashicorp/yamux | session.go | handlePing | func (s *Session) handlePing(hdr header) error {
flags := hdr.Flags()
pingID := hdr.Length()
// Check if this is a query, respond back in a separate context so we
// don't interfere with the receiving thread blocking for the write.
if flags&flagSYN == flagSYN {
go func() {
hdr := header(make([]byte, headerSize))
hdr.encode(typePing, flagACK, 0, pingID)
if err := s.sendNoWait(hdr); err != nil {
s.logger.Printf("[WARN] yamux: failed to send ping reply: %v", err)
}
}()
return nil
}
// Handle a response
s.pingLock.Lock()
ch := s.pings[pingID]
if ch != nil {
delete(s.pings, pingID)
close(ch)
}
s.pingLock.Unlock()
return nil
} | go | func (s *Session) handlePing(hdr header) error {
flags := hdr.Flags()
pingID := hdr.Length()
// Check if this is a query, respond back in a separate context so we
// don't interfere with the receiving thread blocking for the write.
if flags&flagSYN == flagSYN {
go func() {
hdr := header(make([]byte, headerSize))
hdr.encode(typePing, flagACK, 0, pingID)
if err := s.sendNoWait(hdr); err != nil {
s.logger.Printf("[WARN] yamux: failed to send ping reply: %v", err)
}
}()
return nil
}
// Handle a response
s.pingLock.Lock()
ch := s.pings[pingID]
if ch != nil {
delete(s.pings, pingID)
close(ch)
}
s.pingLock.Unlock()
return nil
} | [
"func",
"(",
"s",
"*",
"Session",
")",
"handlePing",
"(",
"hdr",
"header",
")",
"error",
"{",
"flags",
":=",
"hdr",
".",
"Flags",
"(",
")",
"\n",
"pingID",
":=",
"hdr",
".",
"Length",
"(",
")",
"\n\n",
"// Check if this is a query, respond back in a separate context so we",
"// don't interfere with the receiving thread blocking for the write.",
"if",
"flags",
"&",
"flagSYN",
"==",
"flagSYN",
"{",
"go",
"func",
"(",
")",
"{",
"hdr",
":=",
"header",
"(",
"make",
"(",
"[",
"]",
"byte",
",",
"headerSize",
")",
")",
"\n",
"hdr",
".",
"encode",
"(",
"typePing",
",",
"flagACK",
",",
"0",
",",
"pingID",
")",
"\n",
"if",
"err",
":=",
"s",
".",
"sendNoWait",
"(",
"hdr",
")",
";",
"err",
"!=",
"nil",
"{",
"s",
".",
"logger",
".",
"Printf",
"(",
"\"",
"\"",
",",
"err",
")",
"\n",
"}",
"\n",
"}",
"(",
")",
"\n",
"return",
"nil",
"\n",
"}",
"\n\n",
"// Handle a response",
"s",
".",
"pingLock",
".",
"Lock",
"(",
")",
"\n",
"ch",
":=",
"s",
".",
"pings",
"[",
"pingID",
"]",
"\n",
"if",
"ch",
"!=",
"nil",
"{",
"delete",
"(",
"s",
".",
"pings",
",",
"pingID",
")",
"\n",
"close",
"(",
"ch",
")",
"\n",
"}",
"\n",
"s",
".",
"pingLock",
".",
"Unlock",
"(",
")",
"\n",
"return",
"nil",
"\n",
"}"
] | // handlePing is invokde for a typePing frame | [
"handlePing",
"is",
"invokde",
"for",
"a",
"typePing",
"frame"
] | 2f1d1f20f75d5404f53b9edf6b53ed5505508675 | https://github.com/hashicorp/yamux/blob/2f1d1f20f75d5404f53b9edf6b53ed5505508675/session.go#L535-L561 | train |
hashicorp/yamux | session.go | handleGoAway | func (s *Session) handleGoAway(hdr header) error {
code := hdr.Length()
switch code {
case goAwayNormal:
atomic.SwapInt32(&s.remoteGoAway, 1)
case goAwayProtoErr:
s.logger.Printf("[ERR] yamux: received protocol error go away")
return fmt.Errorf("yamux protocol error")
case goAwayInternalErr:
s.logger.Printf("[ERR] yamux: received internal error go away")
return fmt.Errorf("remote yamux internal error")
default:
s.logger.Printf("[ERR] yamux: received unexpected go away")
return fmt.Errorf("unexpected go away received")
}
return nil
} | go | func (s *Session) handleGoAway(hdr header) error {
code := hdr.Length()
switch code {
case goAwayNormal:
atomic.SwapInt32(&s.remoteGoAway, 1)
case goAwayProtoErr:
s.logger.Printf("[ERR] yamux: received protocol error go away")
return fmt.Errorf("yamux protocol error")
case goAwayInternalErr:
s.logger.Printf("[ERR] yamux: received internal error go away")
return fmt.Errorf("remote yamux internal error")
default:
s.logger.Printf("[ERR] yamux: received unexpected go away")
return fmt.Errorf("unexpected go away received")
}
return nil
} | [
"func",
"(",
"s",
"*",
"Session",
")",
"handleGoAway",
"(",
"hdr",
"header",
")",
"error",
"{",
"code",
":=",
"hdr",
".",
"Length",
"(",
")",
"\n",
"switch",
"code",
"{",
"case",
"goAwayNormal",
":",
"atomic",
".",
"SwapInt32",
"(",
"&",
"s",
".",
"remoteGoAway",
",",
"1",
")",
"\n",
"case",
"goAwayProtoErr",
":",
"s",
".",
"logger",
".",
"Printf",
"(",
"\"",
"\"",
")",
"\n",
"return",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
")",
"\n",
"case",
"goAwayInternalErr",
":",
"s",
".",
"logger",
".",
"Printf",
"(",
"\"",
"\"",
")",
"\n",
"return",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
")",
"\n",
"default",
":",
"s",
".",
"logger",
".",
"Printf",
"(",
"\"",
"\"",
")",
"\n",
"return",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}"
] | // handleGoAway is invokde for a typeGoAway frame | [
"handleGoAway",
"is",
"invokde",
"for",
"a",
"typeGoAway",
"frame"
] | 2f1d1f20f75d5404f53b9edf6b53ed5505508675 | https://github.com/hashicorp/yamux/blob/2f1d1f20f75d5404f53b9edf6b53ed5505508675/session.go#L564-L580 | train |
hashicorp/yamux | session.go | incomingStream | func (s *Session) incomingStream(id uint32) error {
// Reject immediately if we are doing a go away
if atomic.LoadInt32(&s.localGoAway) == 1 {
hdr := header(make([]byte, headerSize))
hdr.encode(typeWindowUpdate, flagRST, id, 0)
return s.sendNoWait(hdr)
}
// Allocate a new stream
stream := newStream(s, id, streamSYNReceived)
s.streamLock.Lock()
defer s.streamLock.Unlock()
// Check if stream already exists
if _, ok := s.streams[id]; ok {
s.logger.Printf("[ERR] yamux: duplicate stream declared")
if sendErr := s.sendNoWait(s.goAway(goAwayProtoErr)); sendErr != nil {
s.logger.Printf("[WARN] yamux: failed to send go away: %v", sendErr)
}
return ErrDuplicateStream
}
// Register the stream
s.streams[id] = stream
// Check if we've exceeded the backlog
select {
case s.acceptCh <- stream:
return nil
default:
// Backlog exceeded! RST the stream
s.logger.Printf("[WARN] yamux: backlog exceeded, forcing connection reset")
delete(s.streams, id)
stream.sendHdr.encode(typeWindowUpdate, flagRST, id, 0)
return s.sendNoWait(stream.sendHdr)
}
} | go | func (s *Session) incomingStream(id uint32) error {
// Reject immediately if we are doing a go away
if atomic.LoadInt32(&s.localGoAway) == 1 {
hdr := header(make([]byte, headerSize))
hdr.encode(typeWindowUpdate, flagRST, id, 0)
return s.sendNoWait(hdr)
}
// Allocate a new stream
stream := newStream(s, id, streamSYNReceived)
s.streamLock.Lock()
defer s.streamLock.Unlock()
// Check if stream already exists
if _, ok := s.streams[id]; ok {
s.logger.Printf("[ERR] yamux: duplicate stream declared")
if sendErr := s.sendNoWait(s.goAway(goAwayProtoErr)); sendErr != nil {
s.logger.Printf("[WARN] yamux: failed to send go away: %v", sendErr)
}
return ErrDuplicateStream
}
// Register the stream
s.streams[id] = stream
// Check if we've exceeded the backlog
select {
case s.acceptCh <- stream:
return nil
default:
// Backlog exceeded! RST the stream
s.logger.Printf("[WARN] yamux: backlog exceeded, forcing connection reset")
delete(s.streams, id)
stream.sendHdr.encode(typeWindowUpdate, flagRST, id, 0)
return s.sendNoWait(stream.sendHdr)
}
} | [
"func",
"(",
"s",
"*",
"Session",
")",
"incomingStream",
"(",
"id",
"uint32",
")",
"error",
"{",
"// Reject immediately if we are doing a go away",
"if",
"atomic",
".",
"LoadInt32",
"(",
"&",
"s",
".",
"localGoAway",
")",
"==",
"1",
"{",
"hdr",
":=",
"header",
"(",
"make",
"(",
"[",
"]",
"byte",
",",
"headerSize",
")",
")",
"\n",
"hdr",
".",
"encode",
"(",
"typeWindowUpdate",
",",
"flagRST",
",",
"id",
",",
"0",
")",
"\n",
"return",
"s",
".",
"sendNoWait",
"(",
"hdr",
")",
"\n",
"}",
"\n\n",
"// Allocate a new stream",
"stream",
":=",
"newStream",
"(",
"s",
",",
"id",
",",
"streamSYNReceived",
")",
"\n\n",
"s",
".",
"streamLock",
".",
"Lock",
"(",
")",
"\n",
"defer",
"s",
".",
"streamLock",
".",
"Unlock",
"(",
")",
"\n\n",
"// Check if stream already exists",
"if",
"_",
",",
"ok",
":=",
"s",
".",
"streams",
"[",
"id",
"]",
";",
"ok",
"{",
"s",
".",
"logger",
".",
"Printf",
"(",
"\"",
"\"",
")",
"\n",
"if",
"sendErr",
":=",
"s",
".",
"sendNoWait",
"(",
"s",
".",
"goAway",
"(",
"goAwayProtoErr",
")",
")",
";",
"sendErr",
"!=",
"nil",
"{",
"s",
".",
"logger",
".",
"Printf",
"(",
"\"",
"\"",
",",
"sendErr",
")",
"\n",
"}",
"\n",
"return",
"ErrDuplicateStream",
"\n",
"}",
"\n\n",
"// Register the stream",
"s",
".",
"streams",
"[",
"id",
"]",
"=",
"stream",
"\n\n",
"// Check if we've exceeded the backlog",
"select",
"{",
"case",
"s",
".",
"acceptCh",
"<-",
"stream",
":",
"return",
"nil",
"\n",
"default",
":",
"// Backlog exceeded! RST the stream",
"s",
".",
"logger",
".",
"Printf",
"(",
"\"",
"\"",
")",
"\n",
"delete",
"(",
"s",
".",
"streams",
",",
"id",
")",
"\n",
"stream",
".",
"sendHdr",
".",
"encode",
"(",
"typeWindowUpdate",
",",
"flagRST",
",",
"id",
",",
"0",
")",
"\n",
"return",
"s",
".",
"sendNoWait",
"(",
"stream",
".",
"sendHdr",
")",
"\n",
"}",
"\n",
"}"
] | // incomingStream is used to create a new incoming stream | [
"incomingStream",
"is",
"used",
"to",
"create",
"a",
"new",
"incoming",
"stream"
] | 2f1d1f20f75d5404f53b9edf6b53ed5505508675 | https://github.com/hashicorp/yamux/blob/2f1d1f20f75d5404f53b9edf6b53ed5505508675/session.go#L583-L620 | train |
hashicorp/yamux | session.go | closeStream | func (s *Session) closeStream(id uint32) {
s.streamLock.Lock()
if _, ok := s.inflight[id]; ok {
select {
case <-s.synCh:
default:
s.logger.Printf("[ERR] yamux: SYN tracking out of sync")
}
}
delete(s.streams, id)
s.streamLock.Unlock()
} | go | func (s *Session) closeStream(id uint32) {
s.streamLock.Lock()
if _, ok := s.inflight[id]; ok {
select {
case <-s.synCh:
default:
s.logger.Printf("[ERR] yamux: SYN tracking out of sync")
}
}
delete(s.streams, id)
s.streamLock.Unlock()
} | [
"func",
"(",
"s",
"*",
"Session",
")",
"closeStream",
"(",
"id",
"uint32",
")",
"{",
"s",
".",
"streamLock",
".",
"Lock",
"(",
")",
"\n",
"if",
"_",
",",
"ok",
":=",
"s",
".",
"inflight",
"[",
"id",
"]",
";",
"ok",
"{",
"select",
"{",
"case",
"<-",
"s",
".",
"synCh",
":",
"default",
":",
"s",
".",
"logger",
".",
"Printf",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"}",
"\n",
"delete",
"(",
"s",
".",
"streams",
",",
"id",
")",
"\n",
"s",
".",
"streamLock",
".",
"Unlock",
"(",
")",
"\n",
"}"
] | // closeStream is used to close a stream once both sides have
// issued a close. If there was an in-flight SYN and the stream
// was not yet established, then this will give the credit back. | [
"closeStream",
"is",
"used",
"to",
"close",
"a",
"stream",
"once",
"both",
"sides",
"have",
"issued",
"a",
"close",
".",
"If",
"there",
"was",
"an",
"in",
"-",
"flight",
"SYN",
"and",
"the",
"stream",
"was",
"not",
"yet",
"established",
"then",
"this",
"will",
"give",
"the",
"credit",
"back",
"."
] | 2f1d1f20f75d5404f53b9edf6b53ed5505508675 | https://github.com/hashicorp/yamux/blob/2f1d1f20f75d5404f53b9edf6b53ed5505508675/session.go#L625-L636 | train |
afex/hystrix-go | plugins/graphite_aggregator.go | InitializeGraphiteCollector | func InitializeGraphiteCollector(config *GraphiteCollectorConfig) {
go metrics.Graphite(metrics.DefaultRegistry, config.TickInterval, config.Prefix, config.GraphiteAddr)
} | go | func InitializeGraphiteCollector(config *GraphiteCollectorConfig) {
go metrics.Graphite(metrics.DefaultRegistry, config.TickInterval, config.Prefix, config.GraphiteAddr)
} | [
"func",
"InitializeGraphiteCollector",
"(",
"config",
"*",
"GraphiteCollectorConfig",
")",
"{",
"go",
"metrics",
".",
"Graphite",
"(",
"metrics",
".",
"DefaultRegistry",
",",
"config",
".",
"TickInterval",
",",
"config",
".",
"Prefix",
",",
"config",
".",
"GraphiteAddr",
")",
"\n",
"}"
] | // InitializeGraphiteCollector creates the connection to the graphite server
// and should be called before any metrics are recorded. | [
"InitializeGraphiteCollector",
"creates",
"the",
"connection",
"to",
"the",
"graphite",
"server",
"and",
"should",
"be",
"called",
"before",
"any",
"metrics",
"are",
"recorded",
"."
] | fa1af6a1f4f56e0e50d427fe901cd604d8c6fb8a | https://github.com/afex/hystrix-go/blob/fa1af6a1f4f56e0e50d427fe901cd604d8c6fb8a/plugins/graphite_aggregator.go#L49-L51 | train |
afex/hystrix-go | hystrix/circuit.go | GetCircuit | func GetCircuit(name string) (*CircuitBreaker, bool, error) {
circuitBreakersMutex.RLock()
_, ok := circuitBreakers[name]
if !ok {
circuitBreakersMutex.RUnlock()
circuitBreakersMutex.Lock()
defer circuitBreakersMutex.Unlock()
// because we released the rlock before we obtained the exclusive lock,
// we need to double check that some other thread didn't beat us to
// creation.
if cb, ok := circuitBreakers[name]; ok {
return cb, false, nil
}
circuitBreakers[name] = newCircuitBreaker(name)
} else {
defer circuitBreakersMutex.RUnlock()
}
return circuitBreakers[name], !ok, nil
} | go | func GetCircuit(name string) (*CircuitBreaker, bool, error) {
circuitBreakersMutex.RLock()
_, ok := circuitBreakers[name]
if !ok {
circuitBreakersMutex.RUnlock()
circuitBreakersMutex.Lock()
defer circuitBreakersMutex.Unlock()
// because we released the rlock before we obtained the exclusive lock,
// we need to double check that some other thread didn't beat us to
// creation.
if cb, ok := circuitBreakers[name]; ok {
return cb, false, nil
}
circuitBreakers[name] = newCircuitBreaker(name)
} else {
defer circuitBreakersMutex.RUnlock()
}
return circuitBreakers[name], !ok, nil
} | [
"func",
"GetCircuit",
"(",
"name",
"string",
")",
"(",
"*",
"CircuitBreaker",
",",
"bool",
",",
"error",
")",
"{",
"circuitBreakersMutex",
".",
"RLock",
"(",
")",
"\n",
"_",
",",
"ok",
":=",
"circuitBreakers",
"[",
"name",
"]",
"\n",
"if",
"!",
"ok",
"{",
"circuitBreakersMutex",
".",
"RUnlock",
"(",
")",
"\n",
"circuitBreakersMutex",
".",
"Lock",
"(",
")",
"\n",
"defer",
"circuitBreakersMutex",
".",
"Unlock",
"(",
")",
"\n",
"// because we released the rlock before we obtained the exclusive lock,",
"// we need to double check that some other thread didn't beat us to",
"// creation.",
"if",
"cb",
",",
"ok",
":=",
"circuitBreakers",
"[",
"name",
"]",
";",
"ok",
"{",
"return",
"cb",
",",
"false",
",",
"nil",
"\n",
"}",
"\n",
"circuitBreakers",
"[",
"name",
"]",
"=",
"newCircuitBreaker",
"(",
"name",
")",
"\n",
"}",
"else",
"{",
"defer",
"circuitBreakersMutex",
".",
"RUnlock",
"(",
")",
"\n",
"}",
"\n\n",
"return",
"circuitBreakers",
"[",
"name",
"]",
",",
"!",
"ok",
",",
"nil",
"\n",
"}"
] | // GetCircuit returns the circuit for the given command and whether this call created it. | [
"GetCircuit",
"returns",
"the",
"circuit",
"for",
"the",
"given",
"command",
"and",
"whether",
"this",
"call",
"created",
"it",
"."
] | fa1af6a1f4f56e0e50d427fe901cd604d8c6fb8a | https://github.com/afex/hystrix-go/blob/fa1af6a1f4f56e0e50d427fe901cd604d8c6fb8a/hystrix/circuit.go#L34-L53 | train |
afex/hystrix-go | hystrix/circuit.go | Flush | func Flush() {
circuitBreakersMutex.Lock()
defer circuitBreakersMutex.Unlock()
for name, cb := range circuitBreakers {
cb.metrics.Reset()
cb.executorPool.Metrics.Reset()
delete(circuitBreakers, name)
}
} | go | func Flush() {
circuitBreakersMutex.Lock()
defer circuitBreakersMutex.Unlock()
for name, cb := range circuitBreakers {
cb.metrics.Reset()
cb.executorPool.Metrics.Reset()
delete(circuitBreakers, name)
}
} | [
"func",
"Flush",
"(",
")",
"{",
"circuitBreakersMutex",
".",
"Lock",
"(",
")",
"\n",
"defer",
"circuitBreakersMutex",
".",
"Unlock",
"(",
")",
"\n\n",
"for",
"name",
",",
"cb",
":=",
"range",
"circuitBreakers",
"{",
"cb",
".",
"metrics",
".",
"Reset",
"(",
")",
"\n",
"cb",
".",
"executorPool",
".",
"Metrics",
".",
"Reset",
"(",
")",
"\n",
"delete",
"(",
"circuitBreakers",
",",
"name",
")",
"\n",
"}",
"\n",
"}"
] | // Flush purges all circuit and metric information from memory. | [
"Flush",
"purges",
"all",
"circuit",
"and",
"metric",
"information",
"from",
"memory",
"."
] | fa1af6a1f4f56e0e50d427fe901cd604d8c6fb8a | https://github.com/afex/hystrix-go/blob/fa1af6a1f4f56e0e50d427fe901cd604d8c6fb8a/hystrix/circuit.go#L56-L65 | train |
afex/hystrix-go | hystrix/circuit.go | newCircuitBreaker | func newCircuitBreaker(name string) *CircuitBreaker {
c := &CircuitBreaker{}
c.Name = name
c.metrics = newMetricExchange(name)
c.executorPool = newExecutorPool(name)
c.mutex = &sync.RWMutex{}
return c
} | go | func newCircuitBreaker(name string) *CircuitBreaker {
c := &CircuitBreaker{}
c.Name = name
c.metrics = newMetricExchange(name)
c.executorPool = newExecutorPool(name)
c.mutex = &sync.RWMutex{}
return c
} | [
"func",
"newCircuitBreaker",
"(",
"name",
"string",
")",
"*",
"CircuitBreaker",
"{",
"c",
":=",
"&",
"CircuitBreaker",
"{",
"}",
"\n",
"c",
".",
"Name",
"=",
"name",
"\n",
"c",
".",
"metrics",
"=",
"newMetricExchange",
"(",
"name",
")",
"\n",
"c",
".",
"executorPool",
"=",
"newExecutorPool",
"(",
"name",
")",
"\n",
"c",
".",
"mutex",
"=",
"&",
"sync",
".",
"RWMutex",
"{",
"}",
"\n\n",
"return",
"c",
"\n",
"}"
] | // newCircuitBreaker creates a CircuitBreaker with associated Health | [
"newCircuitBreaker",
"creates",
"a",
"CircuitBreaker",
"with",
"associated",
"Health"
] | fa1af6a1f4f56e0e50d427fe901cd604d8c6fb8a | https://github.com/afex/hystrix-go/blob/fa1af6a1f4f56e0e50d427fe901cd604d8c6fb8a/hystrix/circuit.go#L68-L76 | train |
afex/hystrix-go | hystrix/circuit.go | toggleForceOpen | func (circuit *CircuitBreaker) toggleForceOpen(toggle bool) error {
circuit, _, err := GetCircuit(circuit.Name)
if err != nil {
return err
}
circuit.forceOpen = toggle
return nil
} | go | func (circuit *CircuitBreaker) toggleForceOpen(toggle bool) error {
circuit, _, err := GetCircuit(circuit.Name)
if err != nil {
return err
}
circuit.forceOpen = toggle
return nil
} | [
"func",
"(",
"circuit",
"*",
"CircuitBreaker",
")",
"toggleForceOpen",
"(",
"toggle",
"bool",
")",
"error",
"{",
"circuit",
",",
"_",
",",
"err",
":=",
"GetCircuit",
"(",
"circuit",
".",
"Name",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n\n",
"circuit",
".",
"forceOpen",
"=",
"toggle",
"\n",
"return",
"nil",
"\n",
"}"
] | // toggleForceOpen allows manually causing the fallback logic for all instances
// of a given command. | [
"toggleForceOpen",
"allows",
"manually",
"causing",
"the",
"fallback",
"logic",
"for",
"all",
"instances",
"of",
"a",
"given",
"command",
"."
] | fa1af6a1f4f56e0e50d427fe901cd604d8c6fb8a | https://github.com/afex/hystrix-go/blob/fa1af6a1f4f56e0e50d427fe901cd604d8c6fb8a/hystrix/circuit.go#L80-L88 | train |
afex/hystrix-go | hystrix/circuit.go | IsOpen | func (circuit *CircuitBreaker) IsOpen() bool {
circuit.mutex.RLock()
o := circuit.forceOpen || circuit.open
circuit.mutex.RUnlock()
if o {
return true
}
if uint64(circuit.metrics.Requests().Sum(time.Now())) < getSettings(circuit.Name).RequestVolumeThreshold {
return false
}
if !circuit.metrics.IsHealthy(time.Now()) {
// too many failures, open the circuit
circuit.setOpen()
return true
}
return false
} | go | func (circuit *CircuitBreaker) IsOpen() bool {
circuit.mutex.RLock()
o := circuit.forceOpen || circuit.open
circuit.mutex.RUnlock()
if o {
return true
}
if uint64(circuit.metrics.Requests().Sum(time.Now())) < getSettings(circuit.Name).RequestVolumeThreshold {
return false
}
if !circuit.metrics.IsHealthy(time.Now()) {
// too many failures, open the circuit
circuit.setOpen()
return true
}
return false
} | [
"func",
"(",
"circuit",
"*",
"CircuitBreaker",
")",
"IsOpen",
"(",
")",
"bool",
"{",
"circuit",
".",
"mutex",
".",
"RLock",
"(",
")",
"\n",
"o",
":=",
"circuit",
".",
"forceOpen",
"||",
"circuit",
".",
"open",
"\n",
"circuit",
".",
"mutex",
".",
"RUnlock",
"(",
")",
"\n\n",
"if",
"o",
"{",
"return",
"true",
"\n",
"}",
"\n\n",
"if",
"uint64",
"(",
"circuit",
".",
"metrics",
".",
"Requests",
"(",
")",
".",
"Sum",
"(",
"time",
".",
"Now",
"(",
")",
")",
")",
"<",
"getSettings",
"(",
"circuit",
".",
"Name",
")",
".",
"RequestVolumeThreshold",
"{",
"return",
"false",
"\n",
"}",
"\n\n",
"if",
"!",
"circuit",
".",
"metrics",
".",
"IsHealthy",
"(",
"time",
".",
"Now",
"(",
")",
")",
"{",
"// too many failures, open the circuit",
"circuit",
".",
"setOpen",
"(",
")",
"\n",
"return",
"true",
"\n",
"}",
"\n\n",
"return",
"false",
"\n",
"}"
] | // IsOpen is called before any Command execution to check whether or
// not it should be attempted. An "open" circuit means it is disabled. | [
"IsOpen",
"is",
"called",
"before",
"any",
"Command",
"execution",
"to",
"check",
"whether",
"or",
"not",
"it",
"should",
"be",
"attempted",
".",
"An",
"open",
"circuit",
"means",
"it",
"is",
"disabled",
"."
] | fa1af6a1f4f56e0e50d427fe901cd604d8c6fb8a | https://github.com/afex/hystrix-go/blob/fa1af6a1f4f56e0e50d427fe901cd604d8c6fb8a/hystrix/circuit.go#L92-L112 | train |
afex/hystrix-go | hystrix/circuit.go | ReportEvent | func (circuit *CircuitBreaker) ReportEvent(eventTypes []string, start time.Time, runDuration time.Duration) error {
if len(eventTypes) == 0 {
return fmt.Errorf("no event types sent for metrics")
}
circuit.mutex.RLock()
o := circuit.open
circuit.mutex.RUnlock()
if eventTypes[0] == "success" && o {
circuit.setClose()
}
var concurrencyInUse float64
if circuit.executorPool.Max > 0 {
concurrencyInUse = float64(circuit.executorPool.ActiveCount()) / float64(circuit.executorPool.Max)
}
select {
case circuit.metrics.Updates <- &commandExecution{
Types: eventTypes,
Start: start,
RunDuration: runDuration,
ConcurrencyInUse: concurrencyInUse,
}:
default:
return CircuitError{Message: fmt.Sprintf("metrics channel (%v) is at capacity", circuit.Name)}
}
return nil
} | go | func (circuit *CircuitBreaker) ReportEvent(eventTypes []string, start time.Time, runDuration time.Duration) error {
if len(eventTypes) == 0 {
return fmt.Errorf("no event types sent for metrics")
}
circuit.mutex.RLock()
o := circuit.open
circuit.mutex.RUnlock()
if eventTypes[0] == "success" && o {
circuit.setClose()
}
var concurrencyInUse float64
if circuit.executorPool.Max > 0 {
concurrencyInUse = float64(circuit.executorPool.ActiveCount()) / float64(circuit.executorPool.Max)
}
select {
case circuit.metrics.Updates <- &commandExecution{
Types: eventTypes,
Start: start,
RunDuration: runDuration,
ConcurrencyInUse: concurrencyInUse,
}:
default:
return CircuitError{Message: fmt.Sprintf("metrics channel (%v) is at capacity", circuit.Name)}
}
return nil
} | [
"func",
"(",
"circuit",
"*",
"CircuitBreaker",
")",
"ReportEvent",
"(",
"eventTypes",
"[",
"]",
"string",
",",
"start",
"time",
".",
"Time",
",",
"runDuration",
"time",
".",
"Duration",
")",
"error",
"{",
"if",
"len",
"(",
"eventTypes",
")",
"==",
"0",
"{",
"return",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n\n",
"circuit",
".",
"mutex",
".",
"RLock",
"(",
")",
"\n",
"o",
":=",
"circuit",
".",
"open",
"\n",
"circuit",
".",
"mutex",
".",
"RUnlock",
"(",
")",
"\n",
"if",
"eventTypes",
"[",
"0",
"]",
"==",
"\"",
"\"",
"&&",
"o",
"{",
"circuit",
".",
"setClose",
"(",
")",
"\n",
"}",
"\n\n",
"var",
"concurrencyInUse",
"float64",
"\n",
"if",
"circuit",
".",
"executorPool",
".",
"Max",
">",
"0",
"{",
"concurrencyInUse",
"=",
"float64",
"(",
"circuit",
".",
"executorPool",
".",
"ActiveCount",
"(",
")",
")",
"/",
"float64",
"(",
"circuit",
".",
"executorPool",
".",
"Max",
")",
"\n",
"}",
"\n\n",
"select",
"{",
"case",
"circuit",
".",
"metrics",
".",
"Updates",
"<-",
"&",
"commandExecution",
"{",
"Types",
":",
"eventTypes",
",",
"Start",
":",
"start",
",",
"RunDuration",
":",
"runDuration",
",",
"ConcurrencyInUse",
":",
"concurrencyInUse",
",",
"}",
":",
"default",
":",
"return",
"CircuitError",
"{",
"Message",
":",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"circuit",
".",
"Name",
")",
"}",
"\n",
"}",
"\n\n",
"return",
"nil",
"\n",
"}"
] | // ReportEvent records command metrics for tracking recent error rates and exposing data to the dashboard. | [
"ReportEvent",
"records",
"command",
"metrics",
"for",
"tracking",
"recent",
"error",
"rates",
"and",
"exposing",
"data",
"to",
"the",
"dashboard",
"."
] | fa1af6a1f4f56e0e50d427fe901cd604d8c6fb8a | https://github.com/afex/hystrix-go/blob/fa1af6a1f4f56e0e50d427fe901cd604d8c6fb8a/hystrix/circuit.go#L167-L196 | train |
afex/hystrix-go | hystrix/rolling/rolling.go | NewNumber | func NewNumber() *Number {
r := &Number{
Buckets: make(map[int64]*numberBucket),
Mutex: &sync.RWMutex{},
}
return r
} | go | func NewNumber() *Number {
r := &Number{
Buckets: make(map[int64]*numberBucket),
Mutex: &sync.RWMutex{},
}
return r
} | [
"func",
"NewNumber",
"(",
")",
"*",
"Number",
"{",
"r",
":=",
"&",
"Number",
"{",
"Buckets",
":",
"make",
"(",
"map",
"[",
"int64",
"]",
"*",
"numberBucket",
")",
",",
"Mutex",
":",
"&",
"sync",
".",
"RWMutex",
"{",
"}",
",",
"}",
"\n",
"return",
"r",
"\n",
"}"
] | // NewNumber initializes a RollingNumber struct. | [
"NewNumber",
"initializes",
"a",
"RollingNumber",
"struct",
"."
] | fa1af6a1f4f56e0e50d427fe901cd604d8c6fb8a | https://github.com/afex/hystrix-go/blob/fa1af6a1f4f56e0e50d427fe901cd604d8c6fb8a/hystrix/rolling/rolling.go#L20-L26 | train |
afex/hystrix-go | hystrix/rolling/rolling.go | Increment | func (r *Number) Increment(i float64) {
if i == 0 {
return
}
r.Mutex.Lock()
defer r.Mutex.Unlock()
b := r.getCurrentBucket()
b.Value += i
r.removeOldBuckets()
} | go | func (r *Number) Increment(i float64) {
if i == 0 {
return
}
r.Mutex.Lock()
defer r.Mutex.Unlock()
b := r.getCurrentBucket()
b.Value += i
r.removeOldBuckets()
} | [
"func",
"(",
"r",
"*",
"Number",
")",
"Increment",
"(",
"i",
"float64",
")",
"{",
"if",
"i",
"==",
"0",
"{",
"return",
"\n",
"}",
"\n\n",
"r",
".",
"Mutex",
".",
"Lock",
"(",
")",
"\n",
"defer",
"r",
".",
"Mutex",
".",
"Unlock",
"(",
")",
"\n\n",
"b",
":=",
"r",
".",
"getCurrentBucket",
"(",
")",
"\n",
"b",
".",
"Value",
"+=",
"i",
"\n",
"r",
".",
"removeOldBuckets",
"(",
")",
"\n",
"}"
] | // Increment increments the number in current timeBucket. | [
"Increment",
"increments",
"the",
"number",
"in",
"current",
"timeBucket",
"."
] | fa1af6a1f4f56e0e50d427fe901cd604d8c6fb8a | https://github.com/afex/hystrix-go/blob/fa1af6a1f4f56e0e50d427fe901cd604d8c6fb8a/hystrix/rolling/rolling.go#L53-L64 | train |
afex/hystrix-go | hystrix/rolling/rolling.go | UpdateMax | func (r *Number) UpdateMax(n float64) {
r.Mutex.Lock()
defer r.Mutex.Unlock()
b := r.getCurrentBucket()
if n > b.Value {
b.Value = n
}
r.removeOldBuckets()
} | go | func (r *Number) UpdateMax(n float64) {
r.Mutex.Lock()
defer r.Mutex.Unlock()
b := r.getCurrentBucket()
if n > b.Value {
b.Value = n
}
r.removeOldBuckets()
} | [
"func",
"(",
"r",
"*",
"Number",
")",
"UpdateMax",
"(",
"n",
"float64",
")",
"{",
"r",
".",
"Mutex",
".",
"Lock",
"(",
")",
"\n",
"defer",
"r",
".",
"Mutex",
".",
"Unlock",
"(",
")",
"\n\n",
"b",
":=",
"r",
".",
"getCurrentBucket",
"(",
")",
"\n",
"if",
"n",
">",
"b",
".",
"Value",
"{",
"b",
".",
"Value",
"=",
"n",
"\n",
"}",
"\n",
"r",
".",
"removeOldBuckets",
"(",
")",
"\n",
"}"
] | // UpdateMax updates the maximum value in the current bucket. | [
"UpdateMax",
"updates",
"the",
"maximum",
"value",
"in",
"the",
"current",
"bucket",
"."
] | fa1af6a1f4f56e0e50d427fe901cd604d8c6fb8a | https://github.com/afex/hystrix-go/blob/fa1af6a1f4f56e0e50d427fe901cd604d8c6fb8a/hystrix/rolling/rolling.go#L67-L76 | train |
afex/hystrix-go | hystrix/rolling/rolling.go | Sum | func (r *Number) Sum(now time.Time) float64 {
sum := float64(0)
r.Mutex.RLock()
defer r.Mutex.RUnlock()
for timestamp, bucket := range r.Buckets {
// TODO: configurable rolling window
if timestamp >= now.Unix()-10 {
sum += bucket.Value
}
}
return sum
} | go | func (r *Number) Sum(now time.Time) float64 {
sum := float64(0)
r.Mutex.RLock()
defer r.Mutex.RUnlock()
for timestamp, bucket := range r.Buckets {
// TODO: configurable rolling window
if timestamp >= now.Unix()-10 {
sum += bucket.Value
}
}
return sum
} | [
"func",
"(",
"r",
"*",
"Number",
")",
"Sum",
"(",
"now",
"time",
".",
"Time",
")",
"float64",
"{",
"sum",
":=",
"float64",
"(",
"0",
")",
"\n\n",
"r",
".",
"Mutex",
".",
"RLock",
"(",
")",
"\n",
"defer",
"r",
".",
"Mutex",
".",
"RUnlock",
"(",
")",
"\n\n",
"for",
"timestamp",
",",
"bucket",
":=",
"range",
"r",
".",
"Buckets",
"{",
"// TODO: configurable rolling window",
"if",
"timestamp",
">=",
"now",
".",
"Unix",
"(",
")",
"-",
"10",
"{",
"sum",
"+=",
"bucket",
".",
"Value",
"\n",
"}",
"\n",
"}",
"\n\n",
"return",
"sum",
"\n",
"}"
] | // Sum sums the values over the buckets in the last 10 seconds. | [
"Sum",
"sums",
"the",
"values",
"over",
"the",
"buckets",
"in",
"the",
"last",
"10",
"seconds",
"."
] | fa1af6a1f4f56e0e50d427fe901cd604d8c6fb8a | https://github.com/afex/hystrix-go/blob/fa1af6a1f4f56e0e50d427fe901cd604d8c6fb8a/hystrix/rolling/rolling.go#L79-L93 | train |
afex/hystrix-go | hystrix/rolling/rolling.go | Max | func (r *Number) Max(now time.Time) float64 {
var max float64
r.Mutex.RLock()
defer r.Mutex.RUnlock()
for timestamp, bucket := range r.Buckets {
// TODO: configurable rolling window
if timestamp >= now.Unix()-10 {
if bucket.Value > max {
max = bucket.Value
}
}
}
return max
} | go | func (r *Number) Max(now time.Time) float64 {
var max float64
r.Mutex.RLock()
defer r.Mutex.RUnlock()
for timestamp, bucket := range r.Buckets {
// TODO: configurable rolling window
if timestamp >= now.Unix()-10 {
if bucket.Value > max {
max = bucket.Value
}
}
}
return max
} | [
"func",
"(",
"r",
"*",
"Number",
")",
"Max",
"(",
"now",
"time",
".",
"Time",
")",
"float64",
"{",
"var",
"max",
"float64",
"\n\n",
"r",
".",
"Mutex",
".",
"RLock",
"(",
")",
"\n",
"defer",
"r",
".",
"Mutex",
".",
"RUnlock",
"(",
")",
"\n\n",
"for",
"timestamp",
",",
"bucket",
":=",
"range",
"r",
".",
"Buckets",
"{",
"// TODO: configurable rolling window",
"if",
"timestamp",
">=",
"now",
".",
"Unix",
"(",
")",
"-",
"10",
"{",
"if",
"bucket",
".",
"Value",
">",
"max",
"{",
"max",
"=",
"bucket",
".",
"Value",
"\n",
"}",
"\n",
"}",
"\n",
"}",
"\n\n",
"return",
"max",
"\n",
"}"
] | // Max returns the maximum value seen in the last 10 seconds. | [
"Max",
"returns",
"the",
"maximum",
"value",
"seen",
"in",
"the",
"last",
"10",
"seconds",
"."
] | fa1af6a1f4f56e0e50d427fe901cd604d8c6fb8a | https://github.com/afex/hystrix-go/blob/fa1af6a1f4f56e0e50d427fe901cd604d8c6fb8a/hystrix/rolling/rolling.go#L96-L112 | train |
afex/hystrix-go | hystrix/hystrix.go | Go | func Go(name string, run runFunc, fallback fallbackFunc) chan error {
runC := func(ctx context.Context) error {
return run()
}
var fallbackC fallbackFuncC
if fallback != nil {
fallbackC = func(ctx context.Context, err error) error {
return fallback(err)
}
}
return GoC(context.Background(), name, runC, fallbackC)
} | go | func Go(name string, run runFunc, fallback fallbackFunc) chan error {
runC := func(ctx context.Context) error {
return run()
}
var fallbackC fallbackFuncC
if fallback != nil {
fallbackC = func(ctx context.Context, err error) error {
return fallback(err)
}
}
return GoC(context.Background(), name, runC, fallbackC)
} | [
"func",
"Go",
"(",
"name",
"string",
",",
"run",
"runFunc",
",",
"fallback",
"fallbackFunc",
")",
"chan",
"error",
"{",
"runC",
":=",
"func",
"(",
"ctx",
"context",
".",
"Context",
")",
"error",
"{",
"return",
"run",
"(",
")",
"\n",
"}",
"\n",
"var",
"fallbackC",
"fallbackFuncC",
"\n",
"if",
"fallback",
"!=",
"nil",
"{",
"fallbackC",
"=",
"func",
"(",
"ctx",
"context",
".",
"Context",
",",
"err",
"error",
")",
"error",
"{",
"return",
"fallback",
"(",
"err",
")",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"GoC",
"(",
"context",
".",
"Background",
"(",
")",
",",
"name",
",",
"runC",
",",
"fallbackC",
")",
"\n",
"}"
] | // Go runs your function while tracking the health of previous calls to it.
// If your function begins slowing down or failing repeatedly, we will block
// new calls to it for you to give the dependent service time to repair.
//
// Define a fallback function if you want to define some code to execute during outages. | [
"Go",
"runs",
"your",
"function",
"while",
"tracking",
"the",
"health",
"of",
"previous",
"calls",
"to",
"it",
".",
"If",
"your",
"function",
"begins",
"slowing",
"down",
"or",
"failing",
"repeatedly",
"we",
"will",
"block",
"new",
"calls",
"to",
"it",
"for",
"you",
"to",
"give",
"the",
"dependent",
"service",
"time",
"to",
"repair",
".",
"Define",
"a",
"fallback",
"function",
"if",
"you",
"want",
"to",
"define",
"some",
"code",
"to",
"execute",
"during",
"outages",
"."
] | fa1af6a1f4f56e0e50d427fe901cd604d8c6fb8a | https://github.com/afex/hystrix-go/blob/fa1af6a1f4f56e0e50d427fe901cd604d8c6fb8a/hystrix/hystrix.go#L55-L66 | train |
afex/hystrix-go | hystrix/hystrix.go | DoC | func DoC(ctx context.Context, name string, run runFuncC, fallback fallbackFuncC) error {
done := make(chan struct{}, 1)
r := func(ctx context.Context) error {
err := run(ctx)
if err != nil {
return err
}
done <- struct{}{}
return nil
}
f := func(ctx context.Context, e error) error {
err := fallback(ctx, e)
if err != nil {
return err
}
done <- struct{}{}
return nil
}
var errChan chan error
if fallback == nil {
errChan = GoC(ctx, name, r, nil)
} else {
errChan = GoC(ctx, name, r, f)
}
select {
case <-done:
return nil
case err := <-errChan:
return err
}
} | go | func DoC(ctx context.Context, name string, run runFuncC, fallback fallbackFuncC) error {
done := make(chan struct{}, 1)
r := func(ctx context.Context) error {
err := run(ctx)
if err != nil {
return err
}
done <- struct{}{}
return nil
}
f := func(ctx context.Context, e error) error {
err := fallback(ctx, e)
if err != nil {
return err
}
done <- struct{}{}
return nil
}
var errChan chan error
if fallback == nil {
errChan = GoC(ctx, name, r, nil)
} else {
errChan = GoC(ctx, name, r, f)
}
select {
case <-done:
return nil
case err := <-errChan:
return err
}
} | [
"func",
"DoC",
"(",
"ctx",
"context",
".",
"Context",
",",
"name",
"string",
",",
"run",
"runFuncC",
",",
"fallback",
"fallbackFuncC",
")",
"error",
"{",
"done",
":=",
"make",
"(",
"chan",
"struct",
"{",
"}",
",",
"1",
")",
"\n\n",
"r",
":=",
"func",
"(",
"ctx",
"context",
".",
"Context",
")",
"error",
"{",
"err",
":=",
"run",
"(",
"ctx",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n\n",
"done",
"<-",
"struct",
"{",
"}",
"{",
"}",
"\n",
"return",
"nil",
"\n",
"}",
"\n\n",
"f",
":=",
"func",
"(",
"ctx",
"context",
".",
"Context",
",",
"e",
"error",
")",
"error",
"{",
"err",
":=",
"fallback",
"(",
"ctx",
",",
"e",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n\n",
"done",
"<-",
"struct",
"{",
"}",
"{",
"}",
"\n",
"return",
"nil",
"\n",
"}",
"\n\n",
"var",
"errChan",
"chan",
"error",
"\n",
"if",
"fallback",
"==",
"nil",
"{",
"errChan",
"=",
"GoC",
"(",
"ctx",
",",
"name",
",",
"r",
",",
"nil",
")",
"\n",
"}",
"else",
"{",
"errChan",
"=",
"GoC",
"(",
"ctx",
",",
"name",
",",
"r",
",",
"f",
")",
"\n",
"}",
"\n\n",
"select",
"{",
"case",
"<-",
"done",
":",
"return",
"nil",
"\n",
"case",
"err",
":=",
"<-",
"errChan",
":",
"return",
"err",
"\n",
"}",
"\n",
"}"
] | // DoC runs your function in a synchronous manner, blocking until either your function succeeds
// or an error is returned, including hystrix circuit errors | [
"DoC",
"runs",
"your",
"function",
"in",
"a",
"synchronous",
"manner",
"blocking",
"until",
"either",
"your",
"function",
"succeeds",
"or",
"an",
"error",
"is",
"returned",
"including",
"hystrix",
"circuit",
"errors"
] | fa1af6a1f4f56e0e50d427fe901cd604d8c6fb8a | https://github.com/afex/hystrix-go/blob/fa1af6a1f4f56e0e50d427fe901cd604d8c6fb8a/hystrix/hystrix.go#L217-L253 | train |
afex/hystrix-go | hystrix/hystrix.go | errorWithFallback | func (c *command) errorWithFallback(ctx context.Context, err error) {
eventType := "failure"
if err == ErrCircuitOpen {
eventType = "short-circuit"
} else if err == ErrMaxConcurrency {
eventType = "rejected"
} else if err == ErrTimeout {
eventType = "timeout"
} else if err == context.Canceled {
eventType = "context_canceled"
} else if err == context.DeadlineExceeded {
eventType = "context_deadline_exceeded"
}
c.reportEvent(eventType)
fallbackErr := c.tryFallback(ctx, err)
if fallbackErr != nil {
c.errChan <- fallbackErr
}
} | go | func (c *command) errorWithFallback(ctx context.Context, err error) {
eventType := "failure"
if err == ErrCircuitOpen {
eventType = "short-circuit"
} else if err == ErrMaxConcurrency {
eventType = "rejected"
} else if err == ErrTimeout {
eventType = "timeout"
} else if err == context.Canceled {
eventType = "context_canceled"
} else if err == context.DeadlineExceeded {
eventType = "context_deadline_exceeded"
}
c.reportEvent(eventType)
fallbackErr := c.tryFallback(ctx, err)
if fallbackErr != nil {
c.errChan <- fallbackErr
}
} | [
"func",
"(",
"c",
"*",
"command",
")",
"errorWithFallback",
"(",
"ctx",
"context",
".",
"Context",
",",
"err",
"error",
")",
"{",
"eventType",
":=",
"\"",
"\"",
"\n",
"if",
"err",
"==",
"ErrCircuitOpen",
"{",
"eventType",
"=",
"\"",
"\"",
"\n",
"}",
"else",
"if",
"err",
"==",
"ErrMaxConcurrency",
"{",
"eventType",
"=",
"\"",
"\"",
"\n",
"}",
"else",
"if",
"err",
"==",
"ErrTimeout",
"{",
"eventType",
"=",
"\"",
"\"",
"\n",
"}",
"else",
"if",
"err",
"==",
"context",
".",
"Canceled",
"{",
"eventType",
"=",
"\"",
"\"",
"\n",
"}",
"else",
"if",
"err",
"==",
"context",
".",
"DeadlineExceeded",
"{",
"eventType",
"=",
"\"",
"\"",
"\n",
"}",
"\n\n",
"c",
".",
"reportEvent",
"(",
"eventType",
")",
"\n",
"fallbackErr",
":=",
"c",
".",
"tryFallback",
"(",
"ctx",
",",
"err",
")",
"\n",
"if",
"fallbackErr",
"!=",
"nil",
"{",
"c",
".",
"errChan",
"<-",
"fallbackErr",
"\n",
"}",
"\n",
"}"
] | // errorWithFallback triggers the fallback while reporting the appropriate metric events. | [
"errorWithFallback",
"triggers",
"the",
"fallback",
"while",
"reporting",
"the",
"appropriate",
"metric",
"events",
"."
] | fa1af6a1f4f56e0e50d427fe901cd604d8c6fb8a | https://github.com/afex/hystrix-go/blob/fa1af6a1f4f56e0e50d427fe901cd604d8c6fb8a/hystrix/hystrix.go#L263-L282 | train |
afex/hystrix-go | hystrix/settings.go | Configure | func Configure(cmds map[string]CommandConfig) {
for k, v := range cmds {
ConfigureCommand(k, v)
}
} | go | func Configure(cmds map[string]CommandConfig) {
for k, v := range cmds {
ConfigureCommand(k, v)
}
} | [
"func",
"Configure",
"(",
"cmds",
"map",
"[",
"string",
"]",
"CommandConfig",
")",
"{",
"for",
"k",
",",
"v",
":=",
"range",
"cmds",
"{",
"ConfigureCommand",
"(",
"k",
",",
"v",
")",
"\n",
"}",
"\n",
"}"
] | // Configure applies settings for a set of circuits | [
"Configure",
"applies",
"settings",
"for",
"a",
"set",
"of",
"circuits"
] | fa1af6a1f4f56e0e50d427fe901cd604d8c6fb8a | https://github.com/afex/hystrix-go/blob/fa1af6a1f4f56e0e50d427fe901cd604d8c6fb8a/hystrix/settings.go#L51-L55 | train |
afex/hystrix-go | hystrix/settings.go | ConfigureCommand | func ConfigureCommand(name string, config CommandConfig) {
settingsMutex.Lock()
defer settingsMutex.Unlock()
timeout := DefaultTimeout
if config.Timeout != 0 {
timeout = config.Timeout
}
max := DefaultMaxConcurrent
if config.MaxConcurrentRequests != 0 {
max = config.MaxConcurrentRequests
}
volume := DefaultVolumeThreshold
if config.RequestVolumeThreshold != 0 {
volume = config.RequestVolumeThreshold
}
sleep := DefaultSleepWindow
if config.SleepWindow != 0 {
sleep = config.SleepWindow
}
errorPercent := DefaultErrorPercentThreshold
if config.ErrorPercentThreshold != 0 {
errorPercent = config.ErrorPercentThreshold
}
circuitSettings[name] = &Settings{
Timeout: time.Duration(timeout) * time.Millisecond,
MaxConcurrentRequests: max,
RequestVolumeThreshold: uint64(volume),
SleepWindow: time.Duration(sleep) * time.Millisecond,
ErrorPercentThreshold: errorPercent,
}
} | go | func ConfigureCommand(name string, config CommandConfig) {
settingsMutex.Lock()
defer settingsMutex.Unlock()
timeout := DefaultTimeout
if config.Timeout != 0 {
timeout = config.Timeout
}
max := DefaultMaxConcurrent
if config.MaxConcurrentRequests != 0 {
max = config.MaxConcurrentRequests
}
volume := DefaultVolumeThreshold
if config.RequestVolumeThreshold != 0 {
volume = config.RequestVolumeThreshold
}
sleep := DefaultSleepWindow
if config.SleepWindow != 0 {
sleep = config.SleepWindow
}
errorPercent := DefaultErrorPercentThreshold
if config.ErrorPercentThreshold != 0 {
errorPercent = config.ErrorPercentThreshold
}
circuitSettings[name] = &Settings{
Timeout: time.Duration(timeout) * time.Millisecond,
MaxConcurrentRequests: max,
RequestVolumeThreshold: uint64(volume),
SleepWindow: time.Duration(sleep) * time.Millisecond,
ErrorPercentThreshold: errorPercent,
}
} | [
"func",
"ConfigureCommand",
"(",
"name",
"string",
",",
"config",
"CommandConfig",
")",
"{",
"settingsMutex",
".",
"Lock",
"(",
")",
"\n",
"defer",
"settingsMutex",
".",
"Unlock",
"(",
")",
"\n\n",
"timeout",
":=",
"DefaultTimeout",
"\n",
"if",
"config",
".",
"Timeout",
"!=",
"0",
"{",
"timeout",
"=",
"config",
".",
"Timeout",
"\n",
"}",
"\n\n",
"max",
":=",
"DefaultMaxConcurrent",
"\n",
"if",
"config",
".",
"MaxConcurrentRequests",
"!=",
"0",
"{",
"max",
"=",
"config",
".",
"MaxConcurrentRequests",
"\n",
"}",
"\n\n",
"volume",
":=",
"DefaultVolumeThreshold",
"\n",
"if",
"config",
".",
"RequestVolumeThreshold",
"!=",
"0",
"{",
"volume",
"=",
"config",
".",
"RequestVolumeThreshold",
"\n",
"}",
"\n\n",
"sleep",
":=",
"DefaultSleepWindow",
"\n",
"if",
"config",
".",
"SleepWindow",
"!=",
"0",
"{",
"sleep",
"=",
"config",
".",
"SleepWindow",
"\n",
"}",
"\n\n",
"errorPercent",
":=",
"DefaultErrorPercentThreshold",
"\n",
"if",
"config",
".",
"ErrorPercentThreshold",
"!=",
"0",
"{",
"errorPercent",
"=",
"config",
".",
"ErrorPercentThreshold",
"\n",
"}",
"\n\n",
"circuitSettings",
"[",
"name",
"]",
"=",
"&",
"Settings",
"{",
"Timeout",
":",
"time",
".",
"Duration",
"(",
"timeout",
")",
"*",
"time",
".",
"Millisecond",
",",
"MaxConcurrentRequests",
":",
"max",
",",
"RequestVolumeThreshold",
":",
"uint64",
"(",
"volume",
")",
",",
"SleepWindow",
":",
"time",
".",
"Duration",
"(",
"sleep",
")",
"*",
"time",
".",
"Millisecond",
",",
"ErrorPercentThreshold",
":",
"errorPercent",
",",
"}",
"\n",
"}"
] | // ConfigureCommand applies settings for a circuit | [
"ConfigureCommand",
"applies",
"settings",
"for",
"a",
"circuit"
] | fa1af6a1f4f56e0e50d427fe901cd604d8c6fb8a | https://github.com/afex/hystrix-go/blob/fa1af6a1f4f56e0e50d427fe901cd604d8c6fb8a/hystrix/settings.go#L58-L94 | train |
afex/hystrix-go | hystrix/metric_collector/default_metric_collector.go | NumRequests | func (d *DefaultMetricCollector) NumRequests() *rolling.Number {
d.mutex.RLock()
defer d.mutex.RUnlock()
return d.numRequests
} | go | func (d *DefaultMetricCollector) NumRequests() *rolling.Number {
d.mutex.RLock()
defer d.mutex.RUnlock()
return d.numRequests
} | [
"func",
"(",
"d",
"*",
"DefaultMetricCollector",
")",
"NumRequests",
"(",
")",
"*",
"rolling",
".",
"Number",
"{",
"d",
".",
"mutex",
".",
"RLock",
"(",
")",
"\n",
"defer",
"d",
".",
"mutex",
".",
"RUnlock",
"(",
")",
"\n",
"return",
"d",
".",
"numRequests",
"\n",
"}"
] | // NumRequests returns the rolling number of requests | [
"NumRequests",
"returns",
"the",
"rolling",
"number",
"of",
"requests"
] | fa1af6a1f4f56e0e50d427fe901cd604d8c6fb8a | https://github.com/afex/hystrix-go/blob/fa1af6a1f4f56e0e50d427fe901cd604d8c6fb8a/hystrix/metric_collector/default_metric_collector.go#L43-L47 | train |
afex/hystrix-go | hystrix/metric_collector/default_metric_collector.go | Errors | func (d *DefaultMetricCollector) Errors() *rolling.Number {
d.mutex.RLock()
defer d.mutex.RUnlock()
return d.errors
} | go | func (d *DefaultMetricCollector) Errors() *rolling.Number {
d.mutex.RLock()
defer d.mutex.RUnlock()
return d.errors
} | [
"func",
"(",
"d",
"*",
"DefaultMetricCollector",
")",
"Errors",
"(",
")",
"*",
"rolling",
".",
"Number",
"{",
"d",
".",
"mutex",
".",
"RLock",
"(",
")",
"\n",
"defer",
"d",
".",
"mutex",
".",
"RUnlock",
"(",
")",
"\n",
"return",
"d",
".",
"errors",
"\n",
"}"
] | // Errors returns the rolling number of errors | [
"Errors",
"returns",
"the",
"rolling",
"number",
"of",
"errors"
] | fa1af6a1f4f56e0e50d427fe901cd604d8c6fb8a | https://github.com/afex/hystrix-go/blob/fa1af6a1f4f56e0e50d427fe901cd604d8c6fb8a/hystrix/metric_collector/default_metric_collector.go#L50-L54 | train |
afex/hystrix-go | hystrix/metric_collector/default_metric_collector.go | Successes | func (d *DefaultMetricCollector) Successes() *rolling.Number {
d.mutex.RLock()
defer d.mutex.RUnlock()
return d.successes
} | go | func (d *DefaultMetricCollector) Successes() *rolling.Number {
d.mutex.RLock()
defer d.mutex.RUnlock()
return d.successes
} | [
"func",
"(",
"d",
"*",
"DefaultMetricCollector",
")",
"Successes",
"(",
")",
"*",
"rolling",
".",
"Number",
"{",
"d",
".",
"mutex",
".",
"RLock",
"(",
")",
"\n",
"defer",
"d",
".",
"mutex",
".",
"RUnlock",
"(",
")",
"\n",
"return",
"d",
".",
"successes",
"\n",
"}"
] | // Successes returns the rolling number of successes | [
"Successes",
"returns",
"the",
"rolling",
"number",
"of",
"successes"
] | fa1af6a1f4f56e0e50d427fe901cd604d8c6fb8a | https://github.com/afex/hystrix-go/blob/fa1af6a1f4f56e0e50d427fe901cd604d8c6fb8a/hystrix/metric_collector/default_metric_collector.go#L57-L61 | train |
afex/hystrix-go | hystrix/metric_collector/default_metric_collector.go | Failures | func (d *DefaultMetricCollector) Failures() *rolling.Number {
d.mutex.RLock()
defer d.mutex.RUnlock()
return d.failures
} | go | func (d *DefaultMetricCollector) Failures() *rolling.Number {
d.mutex.RLock()
defer d.mutex.RUnlock()
return d.failures
} | [
"func",
"(",
"d",
"*",
"DefaultMetricCollector",
")",
"Failures",
"(",
")",
"*",
"rolling",
".",
"Number",
"{",
"d",
".",
"mutex",
".",
"RLock",
"(",
")",
"\n",
"defer",
"d",
".",
"mutex",
".",
"RUnlock",
"(",
")",
"\n",
"return",
"d",
".",
"failures",
"\n",
"}"
] | // Failures returns the rolling number of failures | [
"Failures",
"returns",
"the",
"rolling",
"number",
"of",
"failures"
] | fa1af6a1f4f56e0e50d427fe901cd604d8c6fb8a | https://github.com/afex/hystrix-go/blob/fa1af6a1f4f56e0e50d427fe901cd604d8c6fb8a/hystrix/metric_collector/default_metric_collector.go#L64-L68 | train |
afex/hystrix-go | hystrix/metric_collector/default_metric_collector.go | Rejects | func (d *DefaultMetricCollector) Rejects() *rolling.Number {
d.mutex.RLock()
defer d.mutex.RUnlock()
return d.rejects
} | go | func (d *DefaultMetricCollector) Rejects() *rolling.Number {
d.mutex.RLock()
defer d.mutex.RUnlock()
return d.rejects
} | [
"func",
"(",
"d",
"*",
"DefaultMetricCollector",
")",
"Rejects",
"(",
")",
"*",
"rolling",
".",
"Number",
"{",
"d",
".",
"mutex",
".",
"RLock",
"(",
")",
"\n",
"defer",
"d",
".",
"mutex",
".",
"RUnlock",
"(",
")",
"\n",
"return",
"d",
".",
"rejects",
"\n",
"}"
] | // Rejects returns the rolling number of rejects | [
"Rejects",
"returns",
"the",
"rolling",
"number",
"of",
"rejects"
] | fa1af6a1f4f56e0e50d427fe901cd604d8c6fb8a | https://github.com/afex/hystrix-go/blob/fa1af6a1f4f56e0e50d427fe901cd604d8c6fb8a/hystrix/metric_collector/default_metric_collector.go#L71-L75 | train |
afex/hystrix-go | hystrix/metric_collector/default_metric_collector.go | ShortCircuits | func (d *DefaultMetricCollector) ShortCircuits() *rolling.Number {
d.mutex.RLock()
defer d.mutex.RUnlock()
return d.shortCircuits
} | go | func (d *DefaultMetricCollector) ShortCircuits() *rolling.Number {
d.mutex.RLock()
defer d.mutex.RUnlock()
return d.shortCircuits
} | [
"func",
"(",
"d",
"*",
"DefaultMetricCollector",
")",
"ShortCircuits",
"(",
")",
"*",
"rolling",
".",
"Number",
"{",
"d",
".",
"mutex",
".",
"RLock",
"(",
")",
"\n",
"defer",
"d",
".",
"mutex",
".",
"RUnlock",
"(",
")",
"\n",
"return",
"d",
".",
"shortCircuits",
"\n",
"}"
] | // ShortCircuits returns the rolling number of short circuits | [
"ShortCircuits",
"returns",
"the",
"rolling",
"number",
"of",
"short",
"circuits"
] | fa1af6a1f4f56e0e50d427fe901cd604d8c6fb8a | https://github.com/afex/hystrix-go/blob/fa1af6a1f4f56e0e50d427fe901cd604d8c6fb8a/hystrix/metric_collector/default_metric_collector.go#L78-L82 | train |
afex/hystrix-go | hystrix/metric_collector/default_metric_collector.go | Timeouts | func (d *DefaultMetricCollector) Timeouts() *rolling.Number {
d.mutex.RLock()
defer d.mutex.RUnlock()
return d.timeouts
} | go | func (d *DefaultMetricCollector) Timeouts() *rolling.Number {
d.mutex.RLock()
defer d.mutex.RUnlock()
return d.timeouts
} | [
"func",
"(",
"d",
"*",
"DefaultMetricCollector",
")",
"Timeouts",
"(",
")",
"*",
"rolling",
".",
"Number",
"{",
"d",
".",
"mutex",
".",
"RLock",
"(",
")",
"\n",
"defer",
"d",
".",
"mutex",
".",
"RUnlock",
"(",
")",
"\n",
"return",
"d",
".",
"timeouts",
"\n",
"}"
] | // Timeouts returns the rolling number of timeouts | [
"Timeouts",
"returns",
"the",
"rolling",
"number",
"of",
"timeouts"
] | fa1af6a1f4f56e0e50d427fe901cd604d8c6fb8a | https://github.com/afex/hystrix-go/blob/fa1af6a1f4f56e0e50d427fe901cd604d8c6fb8a/hystrix/metric_collector/default_metric_collector.go#L85-L89 | train |
afex/hystrix-go | hystrix/metric_collector/default_metric_collector.go | FallbackSuccesses | func (d *DefaultMetricCollector) FallbackSuccesses() *rolling.Number {
d.mutex.RLock()
defer d.mutex.RUnlock()
return d.fallbackSuccesses
} | go | func (d *DefaultMetricCollector) FallbackSuccesses() *rolling.Number {
d.mutex.RLock()
defer d.mutex.RUnlock()
return d.fallbackSuccesses
} | [
"func",
"(",
"d",
"*",
"DefaultMetricCollector",
")",
"FallbackSuccesses",
"(",
")",
"*",
"rolling",
".",
"Number",
"{",
"d",
".",
"mutex",
".",
"RLock",
"(",
")",
"\n",
"defer",
"d",
".",
"mutex",
".",
"RUnlock",
"(",
")",
"\n",
"return",
"d",
".",
"fallbackSuccesses",
"\n",
"}"
] | // FallbackSuccesses returns the rolling number of fallback successes | [
"FallbackSuccesses",
"returns",
"the",
"rolling",
"number",
"of",
"fallback",
"successes"
] | fa1af6a1f4f56e0e50d427fe901cd604d8c6fb8a | https://github.com/afex/hystrix-go/blob/fa1af6a1f4f56e0e50d427fe901cd604d8c6fb8a/hystrix/metric_collector/default_metric_collector.go#L92-L96 | train |
afex/hystrix-go | hystrix/metric_collector/default_metric_collector.go | FallbackFailures | func (d *DefaultMetricCollector) FallbackFailures() *rolling.Number {
d.mutex.RLock()
defer d.mutex.RUnlock()
return d.fallbackFailures
} | go | func (d *DefaultMetricCollector) FallbackFailures() *rolling.Number {
d.mutex.RLock()
defer d.mutex.RUnlock()
return d.fallbackFailures
} | [
"func",
"(",
"d",
"*",
"DefaultMetricCollector",
")",
"FallbackFailures",
"(",
")",
"*",
"rolling",
".",
"Number",
"{",
"d",
".",
"mutex",
".",
"RLock",
"(",
")",
"\n",
"defer",
"d",
".",
"mutex",
".",
"RUnlock",
"(",
")",
"\n",
"return",
"d",
".",
"fallbackFailures",
"\n",
"}"
] | // FallbackFailures returns the rolling number of fallback failures | [
"FallbackFailures",
"returns",
"the",
"rolling",
"number",
"of",
"fallback",
"failures"
] | fa1af6a1f4f56e0e50d427fe901cd604d8c6fb8a | https://github.com/afex/hystrix-go/blob/fa1af6a1f4f56e0e50d427fe901cd604d8c6fb8a/hystrix/metric_collector/default_metric_collector.go#L111-L115 | train |
afex/hystrix-go | hystrix/metric_collector/default_metric_collector.go | TotalDuration | func (d *DefaultMetricCollector) TotalDuration() *rolling.Timing {
d.mutex.RLock()
defer d.mutex.RUnlock()
return d.totalDuration
} | go | func (d *DefaultMetricCollector) TotalDuration() *rolling.Timing {
d.mutex.RLock()
defer d.mutex.RUnlock()
return d.totalDuration
} | [
"func",
"(",
"d",
"*",
"DefaultMetricCollector",
")",
"TotalDuration",
"(",
")",
"*",
"rolling",
".",
"Timing",
"{",
"d",
".",
"mutex",
".",
"RLock",
"(",
")",
"\n",
"defer",
"d",
".",
"mutex",
".",
"RUnlock",
"(",
")",
"\n",
"return",
"d",
".",
"totalDuration",
"\n",
"}"
] | // TotalDuration returns the rolling total duration | [
"TotalDuration",
"returns",
"the",
"rolling",
"total",
"duration"
] | fa1af6a1f4f56e0e50d427fe901cd604d8c6fb8a | https://github.com/afex/hystrix-go/blob/fa1af6a1f4f56e0e50d427fe901cd604d8c6fb8a/hystrix/metric_collector/default_metric_collector.go#L118-L122 | train |
afex/hystrix-go | hystrix/metric_collector/default_metric_collector.go | RunDuration | func (d *DefaultMetricCollector) RunDuration() *rolling.Timing {
d.mutex.RLock()
defer d.mutex.RUnlock()
return d.runDuration
} | go | func (d *DefaultMetricCollector) RunDuration() *rolling.Timing {
d.mutex.RLock()
defer d.mutex.RUnlock()
return d.runDuration
} | [
"func",
"(",
"d",
"*",
"DefaultMetricCollector",
")",
"RunDuration",
"(",
")",
"*",
"rolling",
".",
"Timing",
"{",
"d",
".",
"mutex",
".",
"RLock",
"(",
")",
"\n",
"defer",
"d",
".",
"mutex",
".",
"RUnlock",
"(",
")",
"\n",
"return",
"d",
".",
"runDuration",
"\n",
"}"
] | // RunDuration returns the rolling run duration | [
"RunDuration",
"returns",
"the",
"rolling",
"run",
"duration"
] | fa1af6a1f4f56e0e50d427fe901cd604d8c6fb8a | https://github.com/afex/hystrix-go/blob/fa1af6a1f4f56e0e50d427fe901cd604d8c6fb8a/hystrix/metric_collector/default_metric_collector.go#L125-L129 | train |
afex/hystrix-go | hystrix/metric_collector/default_metric_collector.go | Reset | func (d *DefaultMetricCollector) Reset() {
d.mutex.Lock()
defer d.mutex.Unlock()
d.numRequests = rolling.NewNumber()
d.errors = rolling.NewNumber()
d.successes = rolling.NewNumber()
d.rejects = rolling.NewNumber()
d.shortCircuits = rolling.NewNumber()
d.failures = rolling.NewNumber()
d.timeouts = rolling.NewNumber()
d.fallbackSuccesses = rolling.NewNumber()
d.fallbackFailures = rolling.NewNumber()
d.contextCanceled = rolling.NewNumber()
d.contextDeadlineExceeded = rolling.NewNumber()
d.totalDuration = rolling.NewTiming()
d.runDuration = rolling.NewTiming()
} | go | func (d *DefaultMetricCollector) Reset() {
d.mutex.Lock()
defer d.mutex.Unlock()
d.numRequests = rolling.NewNumber()
d.errors = rolling.NewNumber()
d.successes = rolling.NewNumber()
d.rejects = rolling.NewNumber()
d.shortCircuits = rolling.NewNumber()
d.failures = rolling.NewNumber()
d.timeouts = rolling.NewNumber()
d.fallbackSuccesses = rolling.NewNumber()
d.fallbackFailures = rolling.NewNumber()
d.contextCanceled = rolling.NewNumber()
d.contextDeadlineExceeded = rolling.NewNumber()
d.totalDuration = rolling.NewTiming()
d.runDuration = rolling.NewTiming()
} | [
"func",
"(",
"d",
"*",
"DefaultMetricCollector",
")",
"Reset",
"(",
")",
"{",
"d",
".",
"mutex",
".",
"Lock",
"(",
")",
"\n",
"defer",
"d",
".",
"mutex",
".",
"Unlock",
"(",
")",
"\n\n",
"d",
".",
"numRequests",
"=",
"rolling",
".",
"NewNumber",
"(",
")",
"\n",
"d",
".",
"errors",
"=",
"rolling",
".",
"NewNumber",
"(",
")",
"\n",
"d",
".",
"successes",
"=",
"rolling",
".",
"NewNumber",
"(",
")",
"\n",
"d",
".",
"rejects",
"=",
"rolling",
".",
"NewNumber",
"(",
")",
"\n",
"d",
".",
"shortCircuits",
"=",
"rolling",
".",
"NewNumber",
"(",
")",
"\n",
"d",
".",
"failures",
"=",
"rolling",
".",
"NewNumber",
"(",
")",
"\n",
"d",
".",
"timeouts",
"=",
"rolling",
".",
"NewNumber",
"(",
")",
"\n",
"d",
".",
"fallbackSuccesses",
"=",
"rolling",
".",
"NewNumber",
"(",
")",
"\n",
"d",
".",
"fallbackFailures",
"=",
"rolling",
".",
"NewNumber",
"(",
")",
"\n",
"d",
".",
"contextCanceled",
"=",
"rolling",
".",
"NewNumber",
"(",
")",
"\n",
"d",
".",
"contextDeadlineExceeded",
"=",
"rolling",
".",
"NewNumber",
"(",
")",
"\n",
"d",
".",
"totalDuration",
"=",
"rolling",
".",
"NewTiming",
"(",
")",
"\n",
"d",
".",
"runDuration",
"=",
"rolling",
".",
"NewTiming",
"(",
")",
"\n",
"}"
] | // Reset resets all metrics in this collector to 0. | [
"Reset",
"resets",
"all",
"metrics",
"in",
"this",
"collector",
"to",
"0",
"."
] | fa1af6a1f4f56e0e50d427fe901cd604d8c6fb8a | https://github.com/afex/hystrix-go/blob/fa1af6a1f4f56e0e50d427fe901cd604d8c6fb8a/hystrix/metric_collector/default_metric_collector.go#L152-L169 | train |
afex/hystrix-go | hystrix/rolling/rolling_timing.go | NewTiming | func NewTiming() *Timing {
r := &Timing{
Buckets: make(map[int64]*timingBucket),
Mutex: &sync.RWMutex{},
}
return r
} | go | func NewTiming() *Timing {
r := &Timing{
Buckets: make(map[int64]*timingBucket),
Mutex: &sync.RWMutex{},
}
return r
} | [
"func",
"NewTiming",
"(",
")",
"*",
"Timing",
"{",
"r",
":=",
"&",
"Timing",
"{",
"Buckets",
":",
"make",
"(",
"map",
"[",
"int64",
"]",
"*",
"timingBucket",
")",
",",
"Mutex",
":",
"&",
"sync",
".",
"RWMutex",
"{",
"}",
",",
"}",
"\n",
"return",
"r",
"\n",
"}"
] | // NewTiming creates a RollingTiming struct. | [
"NewTiming",
"creates",
"a",
"RollingTiming",
"struct",
"."
] | fa1af6a1f4f56e0e50d427fe901cd604d8c6fb8a | https://github.com/afex/hystrix-go/blob/fa1af6a1f4f56e0e50d427fe901cd604d8c6fb8a/hystrix/rolling/rolling_timing.go#L26-L32 | train |
afex/hystrix-go | hystrix/rolling/rolling_timing.go | SortedDurations | func (r *Timing) SortedDurations() []time.Duration {
r.Mutex.RLock()
t := r.LastCachedTime
r.Mutex.RUnlock()
if t+time.Duration(1*time.Second).Nanoseconds() > time.Now().UnixNano() {
// don't recalculate if current cache is still fresh
return r.CachedSortedDurations
}
var durations byDuration
now := time.Now()
r.Mutex.Lock()
defer r.Mutex.Unlock()
for timestamp, b := range r.Buckets {
// TODO: configurable rolling window
if timestamp >= now.Unix()-60 {
for _, d := range b.Durations {
durations = append(durations, d)
}
}
}
sort.Sort(durations)
r.CachedSortedDurations = durations
r.LastCachedTime = time.Now().UnixNano()
return r.CachedSortedDurations
} | go | func (r *Timing) SortedDurations() []time.Duration {
r.Mutex.RLock()
t := r.LastCachedTime
r.Mutex.RUnlock()
if t+time.Duration(1*time.Second).Nanoseconds() > time.Now().UnixNano() {
// don't recalculate if current cache is still fresh
return r.CachedSortedDurations
}
var durations byDuration
now := time.Now()
r.Mutex.Lock()
defer r.Mutex.Unlock()
for timestamp, b := range r.Buckets {
// TODO: configurable rolling window
if timestamp >= now.Unix()-60 {
for _, d := range b.Durations {
durations = append(durations, d)
}
}
}
sort.Sort(durations)
r.CachedSortedDurations = durations
r.LastCachedTime = time.Now().UnixNano()
return r.CachedSortedDurations
} | [
"func",
"(",
"r",
"*",
"Timing",
")",
"SortedDurations",
"(",
")",
"[",
"]",
"time",
".",
"Duration",
"{",
"r",
".",
"Mutex",
".",
"RLock",
"(",
")",
"\n",
"t",
":=",
"r",
".",
"LastCachedTime",
"\n",
"r",
".",
"Mutex",
".",
"RUnlock",
"(",
")",
"\n\n",
"if",
"t",
"+",
"time",
".",
"Duration",
"(",
"1",
"*",
"time",
".",
"Second",
")",
".",
"Nanoseconds",
"(",
")",
">",
"time",
".",
"Now",
"(",
")",
".",
"UnixNano",
"(",
")",
"{",
"// don't recalculate if current cache is still fresh",
"return",
"r",
".",
"CachedSortedDurations",
"\n",
"}",
"\n\n",
"var",
"durations",
"byDuration",
"\n",
"now",
":=",
"time",
".",
"Now",
"(",
")",
"\n\n",
"r",
".",
"Mutex",
".",
"Lock",
"(",
")",
"\n",
"defer",
"r",
".",
"Mutex",
".",
"Unlock",
"(",
")",
"\n\n",
"for",
"timestamp",
",",
"b",
":=",
"range",
"r",
".",
"Buckets",
"{",
"// TODO: configurable rolling window",
"if",
"timestamp",
">=",
"now",
".",
"Unix",
"(",
")",
"-",
"60",
"{",
"for",
"_",
",",
"d",
":=",
"range",
"b",
".",
"Durations",
"{",
"durations",
"=",
"append",
"(",
"durations",
",",
"d",
")",
"\n",
"}",
"\n",
"}",
"\n",
"}",
"\n\n",
"sort",
".",
"Sort",
"(",
"durations",
")",
"\n\n",
"r",
".",
"CachedSortedDurations",
"=",
"durations",
"\n",
"r",
".",
"LastCachedTime",
"=",
"time",
".",
"Now",
"(",
")",
".",
"UnixNano",
"(",
")",
"\n\n",
"return",
"r",
".",
"CachedSortedDurations",
"\n",
"}"
] | // SortedDurations returns an array of time.Duration sorted from shortest
// to longest that have occurred in the last 60 seconds. | [
"SortedDurations",
"returns",
"an",
"array",
"of",
"time",
".",
"Duration",
"sorted",
"from",
"shortest",
"to",
"longest",
"that",
"have",
"occurred",
"in",
"the",
"last",
"60",
"seconds",
"."
] | fa1af6a1f4f56e0e50d427fe901cd604d8c6fb8a | https://github.com/afex/hystrix-go/blob/fa1af6a1f4f56e0e50d427fe901cd604d8c6fb8a/hystrix/rolling/rolling_timing.go#L42-L73 | train |
afex/hystrix-go | hystrix/rolling/rolling_timing.go | Add | func (r *Timing) Add(duration time.Duration) {
b := r.getCurrentBucket()
r.Mutex.Lock()
defer r.Mutex.Unlock()
b.Durations = append(b.Durations, duration)
r.removeOldBuckets()
} | go | func (r *Timing) Add(duration time.Duration) {
b := r.getCurrentBucket()
r.Mutex.Lock()
defer r.Mutex.Unlock()
b.Durations = append(b.Durations, duration)
r.removeOldBuckets()
} | [
"func",
"(",
"r",
"*",
"Timing",
")",
"Add",
"(",
"duration",
"time",
".",
"Duration",
")",
"{",
"b",
":=",
"r",
".",
"getCurrentBucket",
"(",
")",
"\n\n",
"r",
".",
"Mutex",
".",
"Lock",
"(",
")",
"\n",
"defer",
"r",
".",
"Mutex",
".",
"Unlock",
"(",
")",
"\n\n",
"b",
".",
"Durations",
"=",
"append",
"(",
"b",
".",
"Durations",
",",
"duration",
")",
"\n",
"r",
".",
"removeOldBuckets",
"(",
")",
"\n",
"}"
] | // Add appends the time.Duration given to the current time bucket. | [
"Add",
"appends",
"the",
"time",
".",
"Duration",
"given",
"to",
"the",
"current",
"time",
"bucket",
"."
] | fa1af6a1f4f56e0e50d427fe901cd604d8c6fb8a | https://github.com/afex/hystrix-go/blob/fa1af6a1f4f56e0e50d427fe901cd604d8c6fb8a/hystrix/rolling/rolling_timing.go#L104-L112 | train |
afex/hystrix-go | hystrix/rolling/rolling_timing.go | Percentile | func (r *Timing) Percentile(p float64) uint32 {
sortedDurations := r.SortedDurations()
length := len(sortedDurations)
if length <= 0 {
return 0
}
pos := r.ordinal(len(sortedDurations), p) - 1
return uint32(sortedDurations[pos].Nanoseconds() / 1000000)
} | go | func (r *Timing) Percentile(p float64) uint32 {
sortedDurations := r.SortedDurations()
length := len(sortedDurations)
if length <= 0 {
return 0
}
pos := r.ordinal(len(sortedDurations), p) - 1
return uint32(sortedDurations[pos].Nanoseconds() / 1000000)
} | [
"func",
"(",
"r",
"*",
"Timing",
")",
"Percentile",
"(",
"p",
"float64",
")",
"uint32",
"{",
"sortedDurations",
":=",
"r",
".",
"SortedDurations",
"(",
")",
"\n",
"length",
":=",
"len",
"(",
"sortedDurations",
")",
"\n",
"if",
"length",
"<=",
"0",
"{",
"return",
"0",
"\n",
"}",
"\n\n",
"pos",
":=",
"r",
".",
"ordinal",
"(",
"len",
"(",
"sortedDurations",
")",
",",
"p",
")",
"-",
"1",
"\n",
"return",
"uint32",
"(",
"sortedDurations",
"[",
"pos",
"]",
".",
"Nanoseconds",
"(",
")",
"/",
"1000000",
")",
"\n",
"}"
] | // Percentile computes the percentile given with a linear interpolation. | [
"Percentile",
"computes",
"the",
"percentile",
"given",
"with",
"a",
"linear",
"interpolation",
"."
] | fa1af6a1f4f56e0e50d427fe901cd604d8c6fb8a | https://github.com/afex/hystrix-go/blob/fa1af6a1f4f56e0e50d427fe901cd604d8c6fb8a/hystrix/rolling/rolling_timing.go#L115-L124 | train |
afex/hystrix-go | hystrix/rolling/rolling_timing.go | Mean | func (r *Timing) Mean() uint32 {
sortedDurations := r.SortedDurations()
var sum time.Duration
for _, d := range sortedDurations {
sum += d
}
length := int64(len(sortedDurations))
if length == 0 {
return 0
}
return uint32(sum.Nanoseconds()/length) / 1000000
} | go | func (r *Timing) Mean() uint32 {
sortedDurations := r.SortedDurations()
var sum time.Duration
for _, d := range sortedDurations {
sum += d
}
length := int64(len(sortedDurations))
if length == 0 {
return 0
}
return uint32(sum.Nanoseconds()/length) / 1000000
} | [
"func",
"(",
"r",
"*",
"Timing",
")",
"Mean",
"(",
")",
"uint32",
"{",
"sortedDurations",
":=",
"r",
".",
"SortedDurations",
"(",
")",
"\n",
"var",
"sum",
"time",
".",
"Duration",
"\n",
"for",
"_",
",",
"d",
":=",
"range",
"sortedDurations",
"{",
"sum",
"+=",
"d",
"\n",
"}",
"\n\n",
"length",
":=",
"int64",
"(",
"len",
"(",
"sortedDurations",
")",
")",
"\n",
"if",
"length",
"==",
"0",
"{",
"return",
"0",
"\n",
"}",
"\n\n",
"return",
"uint32",
"(",
"sum",
".",
"Nanoseconds",
"(",
")",
"/",
"length",
")",
"/",
"1000000",
"\n",
"}"
] | // Mean computes the average timing in the last 60 seconds. | [
"Mean",
"computes",
"the",
"average",
"timing",
"in",
"the",
"last",
"60",
"seconds",
"."
] | fa1af6a1f4f56e0e50d427fe901cd604d8c6fb8a | https://github.com/afex/hystrix-go/blob/fa1af6a1f4f56e0e50d427fe901cd604d8c6fb8a/hystrix/rolling/rolling_timing.go#L135-L148 | train |
afex/hystrix-go | hystrix/metrics.go | DefaultCollector | func (m *metricExchange) DefaultCollector() *metricCollector.DefaultMetricCollector {
if len(m.metricCollectors) < 1 {
panic("No Metric Collectors Registered.")
}
collection, ok := m.metricCollectors[0].(*metricCollector.DefaultMetricCollector)
if !ok {
panic("Default metric collector is not registered correctly. The default metric collector must be registered first.")
}
return collection
} | go | func (m *metricExchange) DefaultCollector() *metricCollector.DefaultMetricCollector {
if len(m.metricCollectors) < 1 {
panic("No Metric Collectors Registered.")
}
collection, ok := m.metricCollectors[0].(*metricCollector.DefaultMetricCollector)
if !ok {
panic("Default metric collector is not registered correctly. The default metric collector must be registered first.")
}
return collection
} | [
"func",
"(",
"m",
"*",
"metricExchange",
")",
"DefaultCollector",
"(",
")",
"*",
"metricCollector",
".",
"DefaultMetricCollector",
"{",
"if",
"len",
"(",
"m",
".",
"metricCollectors",
")",
"<",
"1",
"{",
"panic",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"collection",
",",
"ok",
":=",
"m",
".",
"metricCollectors",
"[",
"0",
"]",
".",
"(",
"*",
"metricCollector",
".",
"DefaultMetricCollector",
")",
"\n",
"if",
"!",
"ok",
"{",
"panic",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"return",
"collection",
"\n",
"}"
] | // The Default Collector function will panic if collectors are not setup to specification. | [
"The",
"Default",
"Collector",
"function",
"will",
"panic",
"if",
"collectors",
"are",
"not",
"setup",
"to",
"specification",
"."
] | fa1af6a1f4f56e0e50d427fe901cd604d8c6fb8a | https://github.com/afex/hystrix-go/blob/fa1af6a1f4f56e0e50d427fe901cd604d8c6fb8a/hystrix/metrics.go#L41-L50 | train |
afex/hystrix-go | hystrix/eventstream.go | Start | func (sh *StreamHandler) Start() {
sh.requests = make(map[*http.Request]chan []byte)
sh.done = make(chan struct{})
go sh.loop()
} | go | func (sh *StreamHandler) Start() {
sh.requests = make(map[*http.Request]chan []byte)
sh.done = make(chan struct{})
go sh.loop()
} | [
"func",
"(",
"sh",
"*",
"StreamHandler",
")",
"Start",
"(",
")",
"{",
"sh",
".",
"requests",
"=",
"make",
"(",
"map",
"[",
"*",
"http",
".",
"Request",
"]",
"chan",
"[",
"]",
"byte",
")",
"\n",
"sh",
".",
"done",
"=",
"make",
"(",
"chan",
"struct",
"{",
"}",
")",
"\n",
"go",
"sh",
".",
"loop",
"(",
")",
"\n",
"}"
] | // Start begins watching the in-memory circuit breakers for metrics | [
"Start",
"begins",
"watching",
"the",
"in",
"-",
"memory",
"circuit",
"breakers",
"for",
"metrics"
] | fa1af6a1f4f56e0e50d427fe901cd604d8c6fb8a | https://github.com/afex/hystrix-go/blob/fa1af6a1f4f56e0e50d427fe901cd604d8c6fb8a/hystrix/eventstream.go#L30-L34 | train |
afex/hystrix-go | hystrix/metric_collector/metric_collector.go | InitializeMetricCollectors | func (m *metricCollectorRegistry) InitializeMetricCollectors(name string) []MetricCollector {
m.lock.RLock()
defer m.lock.RUnlock()
metrics := make([]MetricCollector, len(m.registry))
for i, metricCollectorInitializer := range m.registry {
metrics[i] = metricCollectorInitializer(name)
}
return metrics
} | go | func (m *metricCollectorRegistry) InitializeMetricCollectors(name string) []MetricCollector {
m.lock.RLock()
defer m.lock.RUnlock()
metrics := make([]MetricCollector, len(m.registry))
for i, metricCollectorInitializer := range m.registry {
metrics[i] = metricCollectorInitializer(name)
}
return metrics
} | [
"func",
"(",
"m",
"*",
"metricCollectorRegistry",
")",
"InitializeMetricCollectors",
"(",
"name",
"string",
")",
"[",
"]",
"MetricCollector",
"{",
"m",
".",
"lock",
".",
"RLock",
"(",
")",
"\n",
"defer",
"m",
".",
"lock",
".",
"RUnlock",
"(",
")",
"\n\n",
"metrics",
":=",
"make",
"(",
"[",
"]",
"MetricCollector",
",",
"len",
"(",
"m",
".",
"registry",
")",
")",
"\n",
"for",
"i",
",",
"metricCollectorInitializer",
":=",
"range",
"m",
".",
"registry",
"{",
"metrics",
"[",
"i",
"]",
"=",
"metricCollectorInitializer",
"(",
"name",
")",
"\n",
"}",
"\n",
"return",
"metrics",
"\n",
"}"
] | // InitializeMetricCollectors runs the registried MetricCollector Initializers to create an array of MetricCollectors. | [
"InitializeMetricCollectors",
"runs",
"the",
"registried",
"MetricCollector",
"Initializers",
"to",
"create",
"an",
"array",
"of",
"MetricCollectors",
"."
] | fa1af6a1f4f56e0e50d427fe901cd604d8c6fb8a | https://github.com/afex/hystrix-go/blob/fa1af6a1f4f56e0e50d427fe901cd604d8c6fb8a/hystrix/metric_collector/metric_collector.go#L23-L32 | train |
afex/hystrix-go | hystrix/metric_collector/metric_collector.go | Register | func (m *metricCollectorRegistry) Register(initMetricCollector func(string) MetricCollector) {
m.lock.Lock()
defer m.lock.Unlock()
m.registry = append(m.registry, initMetricCollector)
} | go | func (m *metricCollectorRegistry) Register(initMetricCollector func(string) MetricCollector) {
m.lock.Lock()
defer m.lock.Unlock()
m.registry = append(m.registry, initMetricCollector)
} | [
"func",
"(",
"m",
"*",
"metricCollectorRegistry",
")",
"Register",
"(",
"initMetricCollector",
"func",
"(",
"string",
")",
"MetricCollector",
")",
"{",
"m",
".",
"lock",
".",
"Lock",
"(",
")",
"\n",
"defer",
"m",
".",
"lock",
".",
"Unlock",
"(",
")",
"\n\n",
"m",
".",
"registry",
"=",
"append",
"(",
"m",
".",
"registry",
",",
"initMetricCollector",
")",
"\n",
"}"
] | // Register places a MetricCollector Initializer in the registry maintained by this metricCollectorRegistry. | [
"Register",
"places",
"a",
"MetricCollector",
"Initializer",
"in",
"the",
"registry",
"maintained",
"by",
"this",
"metricCollectorRegistry",
"."
] | fa1af6a1f4f56e0e50d427fe901cd604d8c6fb8a | https://github.com/afex/hystrix-go/blob/fa1af6a1f4f56e0e50d427fe901cd604d8c6fb8a/hystrix/metric_collector/metric_collector.go#L35-L40 | train |
kardianos/service | version.go | versionAtMost | func versionAtMost(version, max []int) (bool, error) {
if comp, err := versionCompare(version, max); err != nil {
return false, err
} else if comp == 1 {
return false, nil
}
return true, nil
} | go | func versionAtMost(version, max []int) (bool, error) {
if comp, err := versionCompare(version, max); err != nil {
return false, err
} else if comp == 1 {
return false, nil
}
return true, nil
} | [
"func",
"versionAtMost",
"(",
"version",
",",
"max",
"[",
"]",
"int",
")",
"(",
"bool",
",",
"error",
")",
"{",
"if",
"comp",
",",
"err",
":=",
"versionCompare",
"(",
"version",
",",
"max",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"false",
",",
"err",
"\n",
"}",
"else",
"if",
"comp",
"==",
"1",
"{",
"return",
"false",
",",
"nil",
"\n",
"}",
"\n",
"return",
"true",
",",
"nil",
"\n",
"}"
] | // versionAtMost will return true if the provided version is less than or equal to max | [
"versionAtMost",
"will",
"return",
"true",
"if",
"the",
"provided",
"version",
"is",
"less",
"than",
"or",
"equal",
"to",
"max"
] | 0e5bec1b9eec14f9070a6f49ad7e0242f1545d66 | https://github.com/kardianos/service/blob/0e5bec1b9eec14f9070a6f49ad7e0242f1545d66/version.go#L10-L17 | train |
kardianos/service | version.go | versionCompare | func versionCompare(v1, v2 []int) (int, error) {
if len(v1) != len(v2) {
return 0, errors.New("version length mismatch")
}
for idx, v2S := range v2 {
v1S := v1[idx]
if v1S > v2S {
return 1, nil
}
if v1S < v2S {
return -1, nil
}
}
return 0, nil
} | go | func versionCompare(v1, v2 []int) (int, error) {
if len(v1) != len(v2) {
return 0, errors.New("version length mismatch")
}
for idx, v2S := range v2 {
v1S := v1[idx]
if v1S > v2S {
return 1, nil
}
if v1S < v2S {
return -1, nil
}
}
return 0, nil
} | [
"func",
"versionCompare",
"(",
"v1",
",",
"v2",
"[",
"]",
"int",
")",
"(",
"int",
",",
"error",
")",
"{",
"if",
"len",
"(",
"v1",
")",
"!=",
"len",
"(",
"v2",
")",
"{",
"return",
"0",
",",
"errors",
".",
"New",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n\n",
"for",
"idx",
",",
"v2S",
":=",
"range",
"v2",
"{",
"v1S",
":=",
"v1",
"[",
"idx",
"]",
"\n",
"if",
"v1S",
">",
"v2S",
"{",
"return",
"1",
",",
"nil",
"\n",
"}",
"\n\n",
"if",
"v1S",
"<",
"v2S",
"{",
"return",
"-",
"1",
",",
"nil",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"0",
",",
"nil",
"\n",
"}"
] | // versionCompare take to versions split into integer arrays and attempts to compare them
// An error will be returned if there is an array length mismatch.
// Return values are as follows
// -1 - v1 is less than v2
// 0 - v1 is equal to v2
// 1 - v1 is greater than v2 | [
"versionCompare",
"take",
"to",
"versions",
"split",
"into",
"integer",
"arrays",
"and",
"attempts",
"to",
"compare",
"them",
"An",
"error",
"will",
"be",
"returned",
"if",
"there",
"is",
"an",
"array",
"length",
"mismatch",
".",
"Return",
"values",
"are",
"as",
"follows",
"-",
"1",
"-",
"v1",
"is",
"less",
"than",
"v2",
"0",
"-",
"v1",
"is",
"equal",
"to",
"v2",
"1",
"-",
"v1",
"is",
"greater",
"than",
"v2"
] | 0e5bec1b9eec14f9070a6f49ad7e0242f1545d66 | https://github.com/kardianos/service/blob/0e5bec1b9eec14f9070a6f49ad7e0242f1545d66/version.go#L25-L41 | train |
kardianos/service | version.go | parseVersion | func parseVersion(v string) []int {
version := make([]int, 3)
for idx, vStr := range strings.Split(v, ".") {
vS, err := strconv.Atoi(vStr)
if err != nil {
return nil
}
version[idx] = vS
}
return version
} | go | func parseVersion(v string) []int {
version := make([]int, 3)
for idx, vStr := range strings.Split(v, ".") {
vS, err := strconv.Atoi(vStr)
if err != nil {
return nil
}
version[idx] = vS
}
return version
} | [
"func",
"parseVersion",
"(",
"v",
"string",
")",
"[",
"]",
"int",
"{",
"version",
":=",
"make",
"(",
"[",
"]",
"int",
",",
"3",
")",
"\n\n",
"for",
"idx",
",",
"vStr",
":=",
"range",
"strings",
".",
"Split",
"(",
"v",
",",
"\"",
"\"",
")",
"{",
"vS",
",",
"err",
":=",
"strconv",
".",
"Atoi",
"(",
"vStr",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
"\n",
"}",
"\n",
"version",
"[",
"idx",
"]",
"=",
"vS",
"\n",
"}",
"\n\n",
"return",
"version",
"\n",
"}"
] | // parseVersion will parse any integer type version seperated by periods.
// This does not fully support semver style versions. | [
"parseVersion",
"will",
"parse",
"any",
"integer",
"type",
"version",
"seperated",
"by",
"periods",
".",
"This",
"does",
"not",
"fully",
"support",
"semver",
"style",
"versions",
"."
] | 0e5bec1b9eec14f9070a6f49ad7e0242f1545d66 | https://github.com/kardianos/service/blob/0e5bec1b9eec14f9070a6f49ad7e0242f1545d66/version.go#L45-L57 | train |
kardianos/service | service.go | New | func New(i Interface, c *Config) (Service, error) {
if len(c.Name) == 0 {
return nil, ErrNameFieldRequired
}
if system == nil {
return nil, ErrNoServiceSystemDetected
}
return system.New(i, c)
} | go | func New(i Interface, c *Config) (Service, error) {
if len(c.Name) == 0 {
return nil, ErrNameFieldRequired
}
if system == nil {
return nil, ErrNoServiceSystemDetected
}
return system.New(i, c)
} | [
"func",
"New",
"(",
"i",
"Interface",
",",
"c",
"*",
"Config",
")",
"(",
"Service",
",",
"error",
")",
"{",
"if",
"len",
"(",
"c",
".",
"Name",
")",
"==",
"0",
"{",
"return",
"nil",
",",
"ErrNameFieldRequired",
"\n",
"}",
"\n",
"if",
"system",
"==",
"nil",
"{",
"return",
"nil",
",",
"ErrNoServiceSystemDetected",
"\n",
"}",
"\n",
"return",
"system",
".",
"New",
"(",
"i",
",",
"c",
")",
"\n",
"}"
] | // New creates a new service based on a service interface and configuration. | [
"New",
"creates",
"a",
"new",
"service",
"based",
"on",
"a",
"service",
"interface",
"and",
"configuration",
"."
] | 0e5bec1b9eec14f9070a6f49ad7e0242f1545d66 | https://github.com/kardianos/service/blob/0e5bec1b9eec14f9070a6f49ad7e0242f1545d66/service.go#L160-L168 | train |
kardianos/service | service.go | bool | func (kv KeyValue) bool(name string, defaultValue bool) bool {
if v, found := kv[name]; found {
if castValue, is := v.(bool); is {
return castValue
}
}
return defaultValue
} | go | func (kv KeyValue) bool(name string, defaultValue bool) bool {
if v, found := kv[name]; found {
if castValue, is := v.(bool); is {
return castValue
}
}
return defaultValue
} | [
"func",
"(",
"kv",
"KeyValue",
")",
"bool",
"(",
"name",
"string",
",",
"defaultValue",
"bool",
")",
"bool",
"{",
"if",
"v",
",",
"found",
":=",
"kv",
"[",
"name",
"]",
";",
"found",
"{",
"if",
"castValue",
",",
"is",
":=",
"v",
".",
"(",
"bool",
")",
";",
"is",
"{",
"return",
"castValue",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"defaultValue",
"\n",
"}"
] | // bool returns the value of the given name, assuming the value is a boolean.
// If the value isn't found or is not of the type, the defaultValue is returned. | [
"bool",
"returns",
"the",
"value",
"of",
"the",
"given",
"name",
"assuming",
"the",
"value",
"is",
"a",
"boolean",
".",
"If",
"the",
"value",
"isn",
"t",
"found",
"or",
"is",
"not",
"of",
"the",
"type",
"the",
"defaultValue",
"is",
"returned",
"."
] | 0e5bec1b9eec14f9070a6f49ad7e0242f1545d66 | https://github.com/kardianos/service/blob/0e5bec1b9eec14f9070a6f49ad7e0242f1545d66/service.go#L176-L183 | train |
kardianos/service | service.go | Control | func Control(s Service, action string) error {
var err error
switch action {
case ControlAction[0]:
err = s.Start()
case ControlAction[1]:
err = s.Stop()
case ControlAction[2]:
err = s.Restart()
case ControlAction[3]:
err = s.Install()
case ControlAction[4]:
err = s.Uninstall()
default:
err = fmt.Errorf("Unknown action %s", action)
}
if err != nil {
return fmt.Errorf("Failed to %s %v: %v", action, s, err)
}
return nil
} | go | func Control(s Service, action string) error {
var err error
switch action {
case ControlAction[0]:
err = s.Start()
case ControlAction[1]:
err = s.Stop()
case ControlAction[2]:
err = s.Restart()
case ControlAction[3]:
err = s.Install()
case ControlAction[4]:
err = s.Uninstall()
default:
err = fmt.Errorf("Unknown action %s", action)
}
if err != nil {
return fmt.Errorf("Failed to %s %v: %v", action, s, err)
}
return nil
} | [
"func",
"Control",
"(",
"s",
"Service",
",",
"action",
"string",
")",
"error",
"{",
"var",
"err",
"error",
"\n",
"switch",
"action",
"{",
"case",
"ControlAction",
"[",
"0",
"]",
":",
"err",
"=",
"s",
".",
"Start",
"(",
")",
"\n",
"case",
"ControlAction",
"[",
"1",
"]",
":",
"err",
"=",
"s",
".",
"Stop",
"(",
")",
"\n",
"case",
"ControlAction",
"[",
"2",
"]",
":",
"err",
"=",
"s",
".",
"Restart",
"(",
")",
"\n",
"case",
"ControlAction",
"[",
"3",
"]",
":",
"err",
"=",
"s",
".",
"Install",
"(",
")",
"\n",
"case",
"ControlAction",
"[",
"4",
"]",
":",
"err",
"=",
"s",
".",
"Uninstall",
"(",
")",
"\n",
"default",
":",
"err",
"=",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"action",
")",
"\n",
"}",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"action",
",",
"s",
",",
"err",
")",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}"
] | // Control issues control functions to the service from a given action string. | [
"Control",
"issues",
"control",
"functions",
"to",
"the",
"service",
"from",
"a",
"given",
"action",
"string",
"."
] | 0e5bec1b9eec14f9070a6f49ad7e0242f1545d66 | https://github.com/kardianos/service/blob/0e5bec1b9eec14f9070a6f49ad7e0242f1545d66/service.go#L368-L388 | train |
kardianos/service | service_windows.go | Errorf | func (l WindowsLogger) Errorf(format string, a ...interface{}) error {
return l.send(l.ev.Error(3, fmt.Sprintf(format, a...)))
} | go | func (l WindowsLogger) Errorf(format string, a ...interface{}) error {
return l.send(l.ev.Error(3, fmt.Sprintf(format, a...)))
} | [
"func",
"(",
"l",
"WindowsLogger",
")",
"Errorf",
"(",
"format",
"string",
",",
"a",
"...",
"interface",
"{",
"}",
")",
"error",
"{",
"return",
"l",
".",
"send",
"(",
"l",
".",
"ev",
".",
"Error",
"(",
"3",
",",
"fmt",
".",
"Sprintf",
"(",
"format",
",",
"a",
"...",
")",
")",
")",
"\n",
"}"
] | // Errorf logs an error message. | [
"Errorf",
"logs",
"an",
"error",
"message",
"."
] | 0e5bec1b9eec14f9070a6f49ad7e0242f1545d66 | https://github.com/kardianos/service/blob/0e5bec1b9eec14f9070a6f49ad7e0242f1545d66/service_windows.go#L87-L89 | train |
kardianos/service | service_windows.go | Warningf | func (l WindowsLogger) Warningf(format string, a ...interface{}) error {
return l.send(l.ev.Warning(2, fmt.Sprintf(format, a...)))
} | go | func (l WindowsLogger) Warningf(format string, a ...interface{}) error {
return l.send(l.ev.Warning(2, fmt.Sprintf(format, a...)))
} | [
"func",
"(",
"l",
"WindowsLogger",
")",
"Warningf",
"(",
"format",
"string",
",",
"a",
"...",
"interface",
"{",
"}",
")",
"error",
"{",
"return",
"l",
".",
"send",
"(",
"l",
".",
"ev",
".",
"Warning",
"(",
"2",
",",
"fmt",
".",
"Sprintf",
"(",
"format",
",",
"a",
"...",
")",
")",
")",
"\n",
"}"
] | // Warningf logs an warning message. | [
"Warningf",
"logs",
"an",
"warning",
"message",
"."
] | 0e5bec1b9eec14f9070a6f49ad7e0242f1545d66 | https://github.com/kardianos/service/blob/0e5bec1b9eec14f9070a6f49ad7e0242f1545d66/service_windows.go#L92-L94 | train |
kardianos/service | service_windows.go | Infof | func (l WindowsLogger) Infof(format string, a ...interface{}) error {
return l.send(l.ev.Info(1, fmt.Sprintf(format, a...)))
} | go | func (l WindowsLogger) Infof(format string, a ...interface{}) error {
return l.send(l.ev.Info(1, fmt.Sprintf(format, a...)))
} | [
"func",
"(",
"l",
"WindowsLogger",
")",
"Infof",
"(",
"format",
"string",
",",
"a",
"...",
"interface",
"{",
"}",
")",
"error",
"{",
"return",
"l",
".",
"send",
"(",
"l",
".",
"ev",
".",
"Info",
"(",
"1",
",",
"fmt",
".",
"Sprintf",
"(",
"format",
",",
"a",
"...",
")",
")",
")",
"\n",
"}"
] | // Infof logs an info message. | [
"Infof",
"logs",
"an",
"info",
"message",
"."
] | 0e5bec1b9eec14f9070a6f49ad7e0242f1545d66 | https://github.com/kardianos/service/blob/0e5bec1b9eec14f9070a6f49ad7e0242f1545d66/service_windows.go#L97-L99 | train |
kardianos/service | service_windows.go | NError | func (l WindowsLogger) NError(eventID uint32, v ...interface{}) error {
return l.send(l.ev.Error(eventID, fmt.Sprint(v...)))
} | go | func (l WindowsLogger) NError(eventID uint32, v ...interface{}) error {
return l.send(l.ev.Error(eventID, fmt.Sprint(v...)))
} | [
"func",
"(",
"l",
"WindowsLogger",
")",
"NError",
"(",
"eventID",
"uint32",
",",
"v",
"...",
"interface",
"{",
"}",
")",
"error",
"{",
"return",
"l",
".",
"send",
"(",
"l",
".",
"ev",
".",
"Error",
"(",
"eventID",
",",
"fmt",
".",
"Sprint",
"(",
"v",
"...",
")",
")",
")",
"\n",
"}"
] | // NError logs an error message and an event ID. | [
"NError",
"logs",
"an",
"error",
"message",
"and",
"an",
"event",
"ID",
"."
] | 0e5bec1b9eec14f9070a6f49ad7e0242f1545d66 | https://github.com/kardianos/service/blob/0e5bec1b9eec14f9070a6f49ad7e0242f1545d66/service_windows.go#L102-L104 | train |
kardianos/service | service_windows.go | NWarning | func (l WindowsLogger) NWarning(eventID uint32, v ...interface{}) error {
return l.send(l.ev.Warning(eventID, fmt.Sprint(v...)))
} | go | func (l WindowsLogger) NWarning(eventID uint32, v ...interface{}) error {
return l.send(l.ev.Warning(eventID, fmt.Sprint(v...)))
} | [
"func",
"(",
"l",
"WindowsLogger",
")",
"NWarning",
"(",
"eventID",
"uint32",
",",
"v",
"...",
"interface",
"{",
"}",
")",
"error",
"{",
"return",
"l",
".",
"send",
"(",
"l",
".",
"ev",
".",
"Warning",
"(",
"eventID",
",",
"fmt",
".",
"Sprint",
"(",
"v",
"...",
")",
")",
")",
"\n",
"}"
] | // NWarning logs an warning message and an event ID. | [
"NWarning",
"logs",
"an",
"warning",
"message",
"and",
"an",
"event",
"ID",
"."
] | 0e5bec1b9eec14f9070a6f49ad7e0242f1545d66 | https://github.com/kardianos/service/blob/0e5bec1b9eec14f9070a6f49ad7e0242f1545d66/service_windows.go#L107-L109 | train |
kardianos/service | service_windows.go | NInfo | func (l WindowsLogger) NInfo(eventID uint32, v ...interface{}) error {
return l.send(l.ev.Info(eventID, fmt.Sprint(v...)))
} | go | func (l WindowsLogger) NInfo(eventID uint32, v ...interface{}) error {
return l.send(l.ev.Info(eventID, fmt.Sprint(v...)))
} | [
"func",
"(",
"l",
"WindowsLogger",
")",
"NInfo",
"(",
"eventID",
"uint32",
",",
"v",
"...",
"interface",
"{",
"}",
")",
"error",
"{",
"return",
"l",
".",
"send",
"(",
"l",
".",
"ev",
".",
"Info",
"(",
"eventID",
",",
"fmt",
".",
"Sprint",
"(",
"v",
"...",
")",
")",
")",
"\n",
"}"
] | // NInfo logs an info message and an event ID. | [
"NInfo",
"logs",
"an",
"info",
"message",
"and",
"an",
"event",
"ID",
"."
] | 0e5bec1b9eec14f9070a6f49ad7e0242f1545d66 | https://github.com/kardianos/service/blob/0e5bec1b9eec14f9070a6f49ad7e0242f1545d66/service_windows.go#L112-L114 | train |
kardianos/service | service_windows.go | NErrorf | func (l WindowsLogger) NErrorf(eventID uint32, format string, a ...interface{}) error {
return l.send(l.ev.Error(eventID, fmt.Sprintf(format, a...)))
} | go | func (l WindowsLogger) NErrorf(eventID uint32, format string, a ...interface{}) error {
return l.send(l.ev.Error(eventID, fmt.Sprintf(format, a...)))
} | [
"func",
"(",
"l",
"WindowsLogger",
")",
"NErrorf",
"(",
"eventID",
"uint32",
",",
"format",
"string",
",",
"a",
"...",
"interface",
"{",
"}",
")",
"error",
"{",
"return",
"l",
".",
"send",
"(",
"l",
".",
"ev",
".",
"Error",
"(",
"eventID",
",",
"fmt",
".",
"Sprintf",
"(",
"format",
",",
"a",
"...",
")",
")",
")",
"\n",
"}"
] | // NErrorf logs an error message and an event ID. | [
"NErrorf",
"logs",
"an",
"error",
"message",
"and",
"an",
"event",
"ID",
"."
] | 0e5bec1b9eec14f9070a6f49ad7e0242f1545d66 | https://github.com/kardianos/service/blob/0e5bec1b9eec14f9070a6f49ad7e0242f1545d66/service_windows.go#L117-L119 | train |
kardianos/service | service_windows.go | NWarningf | func (l WindowsLogger) NWarningf(eventID uint32, format string, a ...interface{}) error {
return l.send(l.ev.Warning(eventID, fmt.Sprintf(format, a...)))
} | go | func (l WindowsLogger) NWarningf(eventID uint32, format string, a ...interface{}) error {
return l.send(l.ev.Warning(eventID, fmt.Sprintf(format, a...)))
} | [
"func",
"(",
"l",
"WindowsLogger",
")",
"NWarningf",
"(",
"eventID",
"uint32",
",",
"format",
"string",
",",
"a",
"...",
"interface",
"{",
"}",
")",
"error",
"{",
"return",
"l",
".",
"send",
"(",
"l",
".",
"ev",
".",
"Warning",
"(",
"eventID",
",",
"fmt",
".",
"Sprintf",
"(",
"format",
",",
"a",
"...",
")",
")",
")",
"\n",
"}"
] | // NWarningf logs an warning message and an event ID. | [
"NWarningf",
"logs",
"an",
"warning",
"message",
"and",
"an",
"event",
"ID",
"."
] | 0e5bec1b9eec14f9070a6f49ad7e0242f1545d66 | https://github.com/kardianos/service/blob/0e5bec1b9eec14f9070a6f49ad7e0242f1545d66/service_windows.go#L122-L124 | train |
kardianos/service | service_windows.go | NInfof | func (l WindowsLogger) NInfof(eventID uint32, format string, a ...interface{}) error {
return l.send(l.ev.Info(eventID, fmt.Sprintf(format, a...)))
} | go | func (l WindowsLogger) NInfof(eventID uint32, format string, a ...interface{}) error {
return l.send(l.ev.Info(eventID, fmt.Sprintf(format, a...)))
} | [
"func",
"(",
"l",
"WindowsLogger",
")",
"NInfof",
"(",
"eventID",
"uint32",
",",
"format",
"string",
",",
"a",
"...",
"interface",
"{",
"}",
")",
"error",
"{",
"return",
"l",
".",
"send",
"(",
"l",
".",
"ev",
".",
"Info",
"(",
"eventID",
",",
"fmt",
".",
"Sprintf",
"(",
"format",
",",
"a",
"...",
")",
")",
")",
"\n",
"}"
] | // NInfof logs an info message and an event ID. | [
"NInfof",
"logs",
"an",
"info",
"message",
"and",
"an",
"event",
"ID",
"."
] | 0e5bec1b9eec14f9070a6f49ad7e0242f1545d66 | https://github.com/kardianos/service/blob/0e5bec1b9eec14f9070a6f49ad7e0242f1545d66/service_windows.go#L127-L129 | train |
kardianos/service | service_windows.go | getStopTimeout | func getStopTimeout() time.Duration {
// For default and paths see https://support.microsoft.com/en-us/kb/146092
defaultTimeout := time.Millisecond * 20000
key, err := registry.OpenKey(registry.LOCAL_MACHINE, `SYSTEM\CurrentControlSet\Control`, registry.READ)
if err != nil {
return defaultTimeout
}
sv, _, err := key.GetStringValue("WaitToKillServiceTimeout")
if err != nil {
return defaultTimeout
}
v, err := strconv.Atoi(sv)
if err != nil {
return defaultTimeout
}
return time.Millisecond * time.Duration(v)
} | go | func getStopTimeout() time.Duration {
// For default and paths see https://support.microsoft.com/en-us/kb/146092
defaultTimeout := time.Millisecond * 20000
key, err := registry.OpenKey(registry.LOCAL_MACHINE, `SYSTEM\CurrentControlSet\Control`, registry.READ)
if err != nil {
return defaultTimeout
}
sv, _, err := key.GetStringValue("WaitToKillServiceTimeout")
if err != nil {
return defaultTimeout
}
v, err := strconv.Atoi(sv)
if err != nil {
return defaultTimeout
}
return time.Millisecond * time.Duration(v)
} | [
"func",
"getStopTimeout",
"(",
")",
"time",
".",
"Duration",
"{",
"// For default and paths see https://support.microsoft.com/en-us/kb/146092",
"defaultTimeout",
":=",
"time",
".",
"Millisecond",
"*",
"20000",
"\n",
"key",
",",
"err",
":=",
"registry",
".",
"OpenKey",
"(",
"registry",
".",
"LOCAL_MACHINE",
",",
"`SYSTEM\\CurrentControlSet\\Control`",
",",
"registry",
".",
"READ",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"defaultTimeout",
"\n",
"}",
"\n",
"sv",
",",
"_",
",",
"err",
":=",
"key",
".",
"GetStringValue",
"(",
"\"",
"\"",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"defaultTimeout",
"\n",
"}",
"\n",
"v",
",",
"err",
":=",
"strconv",
".",
"Atoi",
"(",
"sv",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"defaultTimeout",
"\n",
"}",
"\n",
"return",
"time",
".",
"Millisecond",
"*",
"time",
".",
"Duration",
"(",
"v",
")",
"\n",
"}"
] | // getStopTimeout fetches the time before windows will kill the service. | [
"getStopTimeout",
"fetches",
"the",
"time",
"before",
"windows",
"will",
"kill",
"the",
"service",
"."
] | 0e5bec1b9eec14f9070a6f49ad7e0242f1545d66 | https://github.com/kardianos/service/blob/0e5bec1b9eec14f9070a6f49ad7e0242f1545d66/service_windows.go#L406-L422 | train |
jroimartin/gocui | edit.go | simpleEditor | func simpleEditor(v *View, key Key, ch rune, mod Modifier) {
switch {
case ch != 0 && mod == 0:
v.EditWrite(ch)
case key == KeySpace:
v.EditWrite(' ')
case key == KeyBackspace || key == KeyBackspace2:
v.EditDelete(true)
case key == KeyDelete:
v.EditDelete(false)
case key == KeyInsert:
v.Overwrite = !v.Overwrite
case key == KeyEnter:
v.EditNewLine()
case key == KeyArrowDown:
v.MoveCursor(0, 1, false)
case key == KeyArrowUp:
v.MoveCursor(0, -1, false)
case key == KeyArrowLeft:
v.MoveCursor(-1, 0, false)
case key == KeyArrowRight:
v.MoveCursor(1, 0, false)
}
} | go | func simpleEditor(v *View, key Key, ch rune, mod Modifier) {
switch {
case ch != 0 && mod == 0:
v.EditWrite(ch)
case key == KeySpace:
v.EditWrite(' ')
case key == KeyBackspace || key == KeyBackspace2:
v.EditDelete(true)
case key == KeyDelete:
v.EditDelete(false)
case key == KeyInsert:
v.Overwrite = !v.Overwrite
case key == KeyEnter:
v.EditNewLine()
case key == KeyArrowDown:
v.MoveCursor(0, 1, false)
case key == KeyArrowUp:
v.MoveCursor(0, -1, false)
case key == KeyArrowLeft:
v.MoveCursor(-1, 0, false)
case key == KeyArrowRight:
v.MoveCursor(1, 0, false)
}
} | [
"func",
"simpleEditor",
"(",
"v",
"*",
"View",
",",
"key",
"Key",
",",
"ch",
"rune",
",",
"mod",
"Modifier",
")",
"{",
"switch",
"{",
"case",
"ch",
"!=",
"0",
"&&",
"mod",
"==",
"0",
":",
"v",
".",
"EditWrite",
"(",
"ch",
")",
"\n",
"case",
"key",
"==",
"KeySpace",
":",
"v",
".",
"EditWrite",
"(",
"' '",
")",
"\n",
"case",
"key",
"==",
"KeyBackspace",
"||",
"key",
"==",
"KeyBackspace2",
":",
"v",
".",
"EditDelete",
"(",
"true",
")",
"\n",
"case",
"key",
"==",
"KeyDelete",
":",
"v",
".",
"EditDelete",
"(",
"false",
")",
"\n",
"case",
"key",
"==",
"KeyInsert",
":",
"v",
".",
"Overwrite",
"=",
"!",
"v",
".",
"Overwrite",
"\n",
"case",
"key",
"==",
"KeyEnter",
":",
"v",
".",
"EditNewLine",
"(",
")",
"\n",
"case",
"key",
"==",
"KeyArrowDown",
":",
"v",
".",
"MoveCursor",
"(",
"0",
",",
"1",
",",
"false",
")",
"\n",
"case",
"key",
"==",
"KeyArrowUp",
":",
"v",
".",
"MoveCursor",
"(",
"0",
",",
"-",
"1",
",",
"false",
")",
"\n",
"case",
"key",
"==",
"KeyArrowLeft",
":",
"v",
".",
"MoveCursor",
"(",
"-",
"1",
",",
"0",
",",
"false",
")",
"\n",
"case",
"key",
"==",
"KeyArrowRight",
":",
"v",
".",
"MoveCursor",
"(",
"1",
",",
"0",
",",
"false",
")",
"\n",
"}",
"\n",
"}"
] | // simpleEditor is used as the default gocui editor. | [
"simpleEditor",
"is",
"used",
"as",
"the",
"default",
"gocui",
"editor",
"."
] | c055c87ae801372cd74a0839b972db4f7697ae5f | https://github.com/jroimartin/gocui/blob/c055c87ae801372cd74a0839b972db4f7697ae5f/edit.go#L30-L53 | train |
jroimartin/gocui | edit.go | EditWrite | func (v *View) EditWrite(ch rune) {
v.writeRune(v.cx, v.cy, ch)
v.MoveCursor(1, 0, true)
} | go | func (v *View) EditWrite(ch rune) {
v.writeRune(v.cx, v.cy, ch)
v.MoveCursor(1, 0, true)
} | [
"func",
"(",
"v",
"*",
"View",
")",
"EditWrite",
"(",
"ch",
"rune",
")",
"{",
"v",
".",
"writeRune",
"(",
"v",
".",
"cx",
",",
"v",
".",
"cy",
",",
"ch",
")",
"\n",
"v",
".",
"MoveCursor",
"(",
"1",
",",
"0",
",",
"true",
")",
"\n",
"}"
] | // EditWrite writes a rune at the cursor position. | [
"EditWrite",
"writes",
"a",
"rune",
"at",
"the",
"cursor",
"position",
"."
] | c055c87ae801372cd74a0839b972db4f7697ae5f | https://github.com/jroimartin/gocui/blob/c055c87ae801372cd74a0839b972db4f7697ae5f/edit.go#L56-L59 | train |
jroimartin/gocui | edit.go | EditDelete | func (v *View) EditDelete(back bool) {
x, y := v.ox+v.cx, v.oy+v.cy
if y < 0 {
return
} else if y >= len(v.viewLines) {
v.MoveCursor(-1, 0, true)
return
}
maxX, _ := v.Size()
if back {
if x == 0 { // start of the line
if y < 1 {
return
}
var maxPrevWidth int
if v.Wrap {
maxPrevWidth = maxX
} else {
maxPrevWidth = maxInt
}
if v.viewLines[y].linesX == 0 { // regular line
v.mergeLines(v.cy - 1)
if len(v.viewLines[y-1].line) < maxPrevWidth {
v.MoveCursor(-1, 0, true)
}
} else { // wrapped line
v.deleteRune(len(v.viewLines[y-1].line)-1, v.cy-1)
v.MoveCursor(-1, 0, true)
}
} else { // middle/end of the line
v.deleteRune(v.cx-1, v.cy)
v.MoveCursor(-1, 0, true)
}
} else {
if x == len(v.viewLines[y].line) { // end of the line
v.mergeLines(v.cy)
} else { // start/middle of the line
v.deleteRune(v.cx, v.cy)
}
}
} | go | func (v *View) EditDelete(back bool) {
x, y := v.ox+v.cx, v.oy+v.cy
if y < 0 {
return
} else if y >= len(v.viewLines) {
v.MoveCursor(-1, 0, true)
return
}
maxX, _ := v.Size()
if back {
if x == 0 { // start of the line
if y < 1 {
return
}
var maxPrevWidth int
if v.Wrap {
maxPrevWidth = maxX
} else {
maxPrevWidth = maxInt
}
if v.viewLines[y].linesX == 0 { // regular line
v.mergeLines(v.cy - 1)
if len(v.viewLines[y-1].line) < maxPrevWidth {
v.MoveCursor(-1, 0, true)
}
} else { // wrapped line
v.deleteRune(len(v.viewLines[y-1].line)-1, v.cy-1)
v.MoveCursor(-1, 0, true)
}
} else { // middle/end of the line
v.deleteRune(v.cx-1, v.cy)
v.MoveCursor(-1, 0, true)
}
} else {
if x == len(v.viewLines[y].line) { // end of the line
v.mergeLines(v.cy)
} else { // start/middle of the line
v.deleteRune(v.cx, v.cy)
}
}
} | [
"func",
"(",
"v",
"*",
"View",
")",
"EditDelete",
"(",
"back",
"bool",
")",
"{",
"x",
",",
"y",
":=",
"v",
".",
"ox",
"+",
"v",
".",
"cx",
",",
"v",
".",
"oy",
"+",
"v",
".",
"cy",
"\n",
"if",
"y",
"<",
"0",
"{",
"return",
"\n",
"}",
"else",
"if",
"y",
">=",
"len",
"(",
"v",
".",
"viewLines",
")",
"{",
"v",
".",
"MoveCursor",
"(",
"-",
"1",
",",
"0",
",",
"true",
")",
"\n",
"return",
"\n",
"}",
"\n\n",
"maxX",
",",
"_",
":=",
"v",
".",
"Size",
"(",
")",
"\n",
"if",
"back",
"{",
"if",
"x",
"==",
"0",
"{",
"// start of the line",
"if",
"y",
"<",
"1",
"{",
"return",
"\n",
"}",
"\n\n",
"var",
"maxPrevWidth",
"int",
"\n",
"if",
"v",
".",
"Wrap",
"{",
"maxPrevWidth",
"=",
"maxX",
"\n",
"}",
"else",
"{",
"maxPrevWidth",
"=",
"maxInt",
"\n",
"}",
"\n\n",
"if",
"v",
".",
"viewLines",
"[",
"y",
"]",
".",
"linesX",
"==",
"0",
"{",
"// regular line",
"v",
".",
"mergeLines",
"(",
"v",
".",
"cy",
"-",
"1",
")",
"\n",
"if",
"len",
"(",
"v",
".",
"viewLines",
"[",
"y",
"-",
"1",
"]",
".",
"line",
")",
"<",
"maxPrevWidth",
"{",
"v",
".",
"MoveCursor",
"(",
"-",
"1",
",",
"0",
",",
"true",
")",
"\n",
"}",
"\n",
"}",
"else",
"{",
"// wrapped line",
"v",
".",
"deleteRune",
"(",
"len",
"(",
"v",
".",
"viewLines",
"[",
"y",
"-",
"1",
"]",
".",
"line",
")",
"-",
"1",
",",
"v",
".",
"cy",
"-",
"1",
")",
"\n",
"v",
".",
"MoveCursor",
"(",
"-",
"1",
",",
"0",
",",
"true",
")",
"\n",
"}",
"\n",
"}",
"else",
"{",
"// middle/end of the line",
"v",
".",
"deleteRune",
"(",
"v",
".",
"cx",
"-",
"1",
",",
"v",
".",
"cy",
")",
"\n",
"v",
".",
"MoveCursor",
"(",
"-",
"1",
",",
"0",
",",
"true",
")",
"\n",
"}",
"\n",
"}",
"else",
"{",
"if",
"x",
"==",
"len",
"(",
"v",
".",
"viewLines",
"[",
"y",
"]",
".",
"line",
")",
"{",
"// end of the line",
"v",
".",
"mergeLines",
"(",
"v",
".",
"cy",
")",
"\n",
"}",
"else",
"{",
"// start/middle of the line",
"v",
".",
"deleteRune",
"(",
"v",
".",
"cx",
",",
"v",
".",
"cy",
")",
"\n",
"}",
"\n",
"}",
"\n",
"}"
] | // EditDelete deletes a rune at the cursor position. back determines the
// direction. | [
"EditDelete",
"deletes",
"a",
"rune",
"at",
"the",
"cursor",
"position",
".",
"back",
"determines",
"the",
"direction",
"."
] | c055c87ae801372cd74a0839b972db4f7697ae5f | https://github.com/jroimartin/gocui/blob/c055c87ae801372cd74a0839b972db4f7697ae5f/edit.go#L63-L106 | train |
jroimartin/gocui | edit.go | EditNewLine | func (v *View) EditNewLine() {
v.breakLine(v.cx, v.cy)
v.ox = 0
v.cx = 0
v.MoveCursor(0, 1, true)
} | go | func (v *View) EditNewLine() {
v.breakLine(v.cx, v.cy)
v.ox = 0
v.cx = 0
v.MoveCursor(0, 1, true)
} | [
"func",
"(",
"v",
"*",
"View",
")",
"EditNewLine",
"(",
")",
"{",
"v",
".",
"breakLine",
"(",
"v",
".",
"cx",
",",
"v",
".",
"cy",
")",
"\n",
"v",
".",
"ox",
"=",
"0",
"\n",
"v",
".",
"cx",
"=",
"0",
"\n",
"v",
".",
"MoveCursor",
"(",
"0",
",",
"1",
",",
"true",
")",
"\n",
"}"
] | // EditNewLine inserts a new line under the cursor. | [
"EditNewLine",
"inserts",
"a",
"new",
"line",
"under",
"the",
"cursor",
"."
] | c055c87ae801372cd74a0839b972db4f7697ae5f | https://github.com/jroimartin/gocui/blob/c055c87ae801372cd74a0839b972db4f7697ae5f/edit.go#L109-L114 | train |
jroimartin/gocui | edit.go | mergeLines | func (v *View) mergeLines(y int) error {
v.tainted = true
_, y, err := v.realPosition(0, y)
if err != nil {
return err
}
if y < 0 || y >= len(v.lines) {
return errors.New("invalid point")
}
if y < len(v.lines)-1 { // otherwise we don't need to merge anything
v.lines[y] = append(v.lines[y], v.lines[y+1]...)
v.lines = append(v.lines[:y+1], v.lines[y+2:]...)
}
return nil
} | go | func (v *View) mergeLines(y int) error {
v.tainted = true
_, y, err := v.realPosition(0, y)
if err != nil {
return err
}
if y < 0 || y >= len(v.lines) {
return errors.New("invalid point")
}
if y < len(v.lines)-1 { // otherwise we don't need to merge anything
v.lines[y] = append(v.lines[y], v.lines[y+1]...)
v.lines = append(v.lines[:y+1], v.lines[y+2:]...)
}
return nil
} | [
"func",
"(",
"v",
"*",
"View",
")",
"mergeLines",
"(",
"y",
"int",
")",
"error",
"{",
"v",
".",
"tainted",
"=",
"true",
"\n\n",
"_",
",",
"y",
",",
"err",
":=",
"v",
".",
"realPosition",
"(",
"0",
",",
"y",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n\n",
"if",
"y",
"<",
"0",
"||",
"y",
">=",
"len",
"(",
"v",
".",
"lines",
")",
"{",
"return",
"errors",
".",
"New",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n\n",
"if",
"y",
"<",
"len",
"(",
"v",
".",
"lines",
")",
"-",
"1",
"{",
"// otherwise we don't need to merge anything",
"v",
".",
"lines",
"[",
"y",
"]",
"=",
"append",
"(",
"v",
".",
"lines",
"[",
"y",
"]",
",",
"v",
".",
"lines",
"[",
"y",
"+",
"1",
"]",
"...",
")",
"\n",
"v",
".",
"lines",
"=",
"append",
"(",
"v",
".",
"lines",
"[",
":",
"y",
"+",
"1",
"]",
",",
"v",
".",
"lines",
"[",
"y",
"+",
"2",
":",
"]",
"...",
")",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}"
] | // mergeLines merges the lines "y" and "y+1" if possible. | [
"mergeLines",
"merges",
"the",
"lines",
"y",
"and",
"y",
"+",
"1",
"if",
"possible",
"."
] | c055c87ae801372cd74a0839b972db4f7697ae5f | https://github.com/jroimartin/gocui/blob/c055c87ae801372cd74a0839b972db4f7697ae5f/edit.go#L294-L311 | train |
jroimartin/gocui | keybinding.go | newKeybinding | func newKeybinding(viewname string, key Key, ch rune, mod Modifier, handler func(*Gui, *View) error) (kb *keybinding) {
kb = &keybinding{
viewName: viewname,
key: key,
ch: ch,
mod: mod,
handler: handler,
}
return kb
} | go | func newKeybinding(viewname string, key Key, ch rune, mod Modifier, handler func(*Gui, *View) error) (kb *keybinding) {
kb = &keybinding{
viewName: viewname,
key: key,
ch: ch,
mod: mod,
handler: handler,
}
return kb
} | [
"func",
"newKeybinding",
"(",
"viewname",
"string",
",",
"key",
"Key",
",",
"ch",
"rune",
",",
"mod",
"Modifier",
",",
"handler",
"func",
"(",
"*",
"Gui",
",",
"*",
"View",
")",
"error",
")",
"(",
"kb",
"*",
"keybinding",
")",
"{",
"kb",
"=",
"&",
"keybinding",
"{",
"viewName",
":",
"viewname",
",",
"key",
":",
"key",
",",
"ch",
":",
"ch",
",",
"mod",
":",
"mod",
",",
"handler",
":",
"handler",
",",
"}",
"\n",
"return",
"kb",
"\n",
"}"
] | // newKeybinding returns a new Keybinding object. | [
"newKeybinding",
"returns",
"a",
"new",
"Keybinding",
"object",
"."
] | c055c87ae801372cd74a0839b972db4f7697ae5f | https://github.com/jroimartin/gocui/blob/c055c87ae801372cd74a0839b972db4f7697ae5f/keybinding.go#L19-L28 | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.