id int32 0 167k | 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 list | docstring stringlengths 6 2.61k | docstring_tokens list | sha stringlengths 40 40 | url stringlengths 85 252 |
|---|---|---|---|---|---|---|---|---|---|---|---|
15,100 | blevesearch/segment | segment.go | Segment | func (s *Segmenter) Segment() bool {
// Loop until we have a token.
for {
// See if we can get a token with what we already have.
if s.end > s.start {
advance, token, typ, err := s.segment(s.buf[s.start:s.end], s.err != nil)
if err != nil {
s.setErr(err)
return false
}
s.typ = typ
if !s.advance(advance) {
return false
}
s.token = token
if token != nil {
return true
}
}
// We cannot generate a token with what we are holding.
// If we've already hit EOF or an I/O error, we are done.
if s.err != nil {
// Shut it down.
s.start = 0
s.end = 0
return false
}
// Must read more data.
// First, shift data to beginning of buffer if there's lots of empty space
// or space is needed.
if s.start > 0 && (s.end == len(s.buf) || s.start > len(s.buf)/2) {
copy(s.buf, s.buf[s.start:s.end])
s.end -= s.start
s.start = 0
}
// Is the buffer full? If so, resize.
if s.end == len(s.buf) {
if len(s.buf) >= s.maxTokenSize {
s.setErr(ErrTooLong)
return false
}
newSize := len(s.buf) * 2
if newSize > s.maxTokenSize {
newSize = s.maxTokenSize
}
newBuf := make([]byte, newSize)
copy(newBuf, s.buf[s.start:s.end])
s.buf = newBuf
s.end -= s.start
s.start = 0
continue
}
// Finally we can read some input. Make sure we don't get stuck with
// a misbehaving Reader. Officially we don't need to do this, but let's
// be extra careful: Segmenter is for safe, simple jobs.
for loop := 0; ; {
n, err := s.r.Read(s.buf[s.end:len(s.buf)])
s.end += n
if err != nil {
s.setErr(err)
break
}
if n > 0 {
break
}
loop++
if loop > maxConsecutiveEmptyReads {
s.setErr(io.ErrNoProgress)
break
}
}
}
} | go | func (s *Segmenter) Segment() bool {
// Loop until we have a token.
for {
// See if we can get a token with what we already have.
if s.end > s.start {
advance, token, typ, err := s.segment(s.buf[s.start:s.end], s.err != nil)
if err != nil {
s.setErr(err)
return false
}
s.typ = typ
if !s.advance(advance) {
return false
}
s.token = token
if token != nil {
return true
}
}
// We cannot generate a token with what we are holding.
// If we've already hit EOF or an I/O error, we are done.
if s.err != nil {
// Shut it down.
s.start = 0
s.end = 0
return false
}
// Must read more data.
// First, shift data to beginning of buffer if there's lots of empty space
// or space is needed.
if s.start > 0 && (s.end == len(s.buf) || s.start > len(s.buf)/2) {
copy(s.buf, s.buf[s.start:s.end])
s.end -= s.start
s.start = 0
}
// Is the buffer full? If so, resize.
if s.end == len(s.buf) {
if len(s.buf) >= s.maxTokenSize {
s.setErr(ErrTooLong)
return false
}
newSize := len(s.buf) * 2
if newSize > s.maxTokenSize {
newSize = s.maxTokenSize
}
newBuf := make([]byte, newSize)
copy(newBuf, s.buf[s.start:s.end])
s.buf = newBuf
s.end -= s.start
s.start = 0
continue
}
// Finally we can read some input. Make sure we don't get stuck with
// a misbehaving Reader. Officially we don't need to do this, but let's
// be extra careful: Segmenter is for safe, simple jobs.
for loop := 0; ; {
n, err := s.r.Read(s.buf[s.end:len(s.buf)])
s.end += n
if err != nil {
s.setErr(err)
break
}
if n > 0 {
break
}
loop++
if loop > maxConsecutiveEmptyReads {
s.setErr(io.ErrNoProgress)
break
}
}
}
} | [
"func",
"(",
"s",
"*",
"Segmenter",
")",
"Segment",
"(",
")",
"bool",
"{",
"// Loop until we have a token.",
"for",
"{",
"// See if we can get a token with what we already have.",
"if",
"s",
".",
"end",
">",
"s",
".",
"start",
"{",
"advance",
",",
"token",
",",
... | // Segment advances the Segmenter to the next token, which will then be
// available through the Bytes or Text method. It returns false when the
// scan stops, either by reaching the end of the input or an error.
// After Segment returns false, the Err method will return any error that
// occurred during scanning, except that if it was io.EOF, Err
// will return nil. | [
"Segment",
"advances",
"the",
"Segmenter",
"to",
"the",
"next",
"token",
"which",
"will",
"then",
"be",
"available",
"through",
"the",
"Bytes",
"or",
"Text",
"method",
".",
"It",
"returns",
"false",
"when",
"the",
"scan",
"stops",
"either",
"by",
"reaching",... | 762005e7a34fd909a84586299f1dd457371d36ee | https://github.com/blevesearch/segment/blob/762005e7a34fd909a84586299f1dd457371d36ee/segment.go#L185-L257 |
15,101 | mixer/redutil | queue/util.go | rlConcat | func rlConcat(cnx redis.Conn, src, dest string) error {
data, err := cnx.Do("RPOPLPUSH", src, dest)
if err != nil {
return err
}
if data == nil {
return redis.ErrNil
}
return nil
} | go | func rlConcat(cnx redis.Conn, src, dest string) error {
data, err := cnx.Do("RPOPLPUSH", src, dest)
if err != nil {
return err
}
if data == nil {
return redis.ErrNil
}
return nil
} | [
"func",
"rlConcat",
"(",
"cnx",
"redis",
".",
"Conn",
",",
"src",
",",
"dest",
"string",
")",
"error",
"{",
"data",
",",
"err",
":=",
"cnx",
".",
"Do",
"(",
"\"",
"\"",
",",
"src",
",",
"dest",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return"... | // Concat implementation using RPOPLPUSH, compatible
// with the behaviour of Processor.Queue. | [
"Concat",
"implementation",
"using",
"RPOPLPUSH",
"compatible",
"with",
"the",
"behaviour",
"of",
"Processor",
".",
"Queue",
"."
] | a5663a71d6be64b703bd3dccb819ba06f3f25a52 | https://github.com/mixer/redutil/blob/a5663a71d6be64b703bd3dccb819ba06f3f25a52/queue/util.go#L7-L17 |
15,102 | mixer/redutil | pubsub/client.go | New | func New(pool *redis.Pool, reconnectPolicy conn.ReconnectPolicy) *Client {
return &Client{
eventEmitter: newEventEmitter(),
state: blueprint.Machine(),
stateLock: new(sync.Mutex),
pool: pool,
subscribed: map[string][]*Listener{},
policy: reconnectPolicy,
tasks: make(chan task, 128),
}
} | go | func New(pool *redis.Pool, reconnectPolicy conn.ReconnectPolicy) *Client {
return &Client{
eventEmitter: newEventEmitter(),
state: blueprint.Machine(),
stateLock: new(sync.Mutex),
pool: pool,
subscribed: map[string][]*Listener{},
policy: reconnectPolicy,
tasks: make(chan task, 128),
}
} | [
"func",
"New",
"(",
"pool",
"*",
"redis",
".",
"Pool",
",",
"reconnectPolicy",
"conn",
".",
"ReconnectPolicy",
")",
"*",
"Client",
"{",
"return",
"&",
"Client",
"{",
"eventEmitter",
":",
"newEventEmitter",
"(",
")",
",",
"state",
":",
"blueprint",
".",
"... | // Creates and returns a new pubsub client client and subscribes to it. | [
"Creates",
"and",
"returns",
"a",
"new",
"pubsub",
"client",
"client",
"and",
"subscribes",
"to",
"it",
"."
] | a5663a71d6be64b703bd3dccb819ba06f3f25a52 | https://github.com/mixer/redutil/blob/a5663a71d6be64b703bd3dccb819ba06f3f25a52/pubsub/client.go#L92-L102 |
15,103 | mixer/redutil | pubsub/client.go | Listener | func (c *Client) Listener(kind ListenerType, event string) *Listener {
listener := &Listener{
Type: kind,
Event: event,
Messages: make(chan redis.Message),
PMessages: make(chan redis.PMessage),
Client: c,
}
c.Subscribe(listener)
return listener
} | go | func (c *Client) Listener(kind ListenerType, event string) *Listener {
listener := &Listener{
Type: kind,
Event: event,
Messages: make(chan redis.Message),
PMessages: make(chan redis.PMessage),
Client: c,
}
c.Subscribe(listener)
return listener
} | [
"func",
"(",
"c",
"*",
"Client",
")",
"Listener",
"(",
"kind",
"ListenerType",
",",
"event",
"string",
")",
"*",
"Listener",
"{",
"listener",
":=",
"&",
"Listener",
"{",
"Type",
":",
"kind",
",",
"Event",
":",
"event",
",",
"Messages",
":",
"make",
"... | // Convenience function to create a new listener for an event. | [
"Convenience",
"function",
"to",
"create",
"a",
"new",
"listener",
"for",
"an",
"event",
"."
] | a5663a71d6be64b703bd3dccb819ba06f3f25a52 | https://github.com/mixer/redutil/blob/a5663a71d6be64b703bd3dccb819ba06f3f25a52/pubsub/client.go#L105-L116 |
15,104 | mixer/redutil | pubsub/client.go | GetState | func (c *Client) GetState() uint8 {
c.stateLock.Lock()
defer c.stateLock.Unlock()
return c.state.State()
} | go | func (c *Client) GetState() uint8 {
c.stateLock.Lock()
defer c.stateLock.Unlock()
return c.state.State()
} | [
"func",
"(",
"c",
"*",
"Client",
")",
"GetState",
"(",
")",
"uint8",
"{",
"c",
".",
"stateLock",
".",
"Lock",
"(",
")",
"\n",
"defer",
"c",
".",
"stateLock",
".",
"Unlock",
"(",
")",
"\n\n",
"return",
"c",
".",
"state",
".",
"State",
"(",
")",
... | // GetState gets the current client state. | [
"GetState",
"gets",
"the",
"current",
"client",
"state",
"."
] | a5663a71d6be64b703bd3dccb819ba06f3f25a52 | https://github.com/mixer/redutil/blob/a5663a71d6be64b703bd3dccb819ba06f3f25a52/pubsub/client.go#L119-L124 |
15,105 | mixer/redutil | pubsub/client.go | setState | func (c *Client) setState(s uint8) error {
c.stateLock.Lock()
err := c.state.Goto(s)
c.stateLock.Unlock()
if err != nil {
return err
}
switch s {
case ConnectedState:
c.emit(ConnectedEvent, nil)
case DisconnectedState:
c.emit(DisconnectedEvent, nil)
case ClosingState:
c.emit(ClosingEvent, nil)
case ClosedState:
c.emit(ClosedEvent, nil)
}
return nil
} | go | func (c *Client) setState(s uint8) error {
c.stateLock.Lock()
err := c.state.Goto(s)
c.stateLock.Unlock()
if err != nil {
return err
}
switch s {
case ConnectedState:
c.emit(ConnectedEvent, nil)
case DisconnectedState:
c.emit(DisconnectedEvent, nil)
case ClosingState:
c.emit(ClosingEvent, nil)
case ClosedState:
c.emit(ClosedEvent, nil)
}
return nil
} | [
"func",
"(",
"c",
"*",
"Client",
")",
"setState",
"(",
"s",
"uint8",
")",
"error",
"{",
"c",
".",
"stateLock",
".",
"Lock",
"(",
")",
"\n",
"err",
":=",
"c",
".",
"state",
".",
"Goto",
"(",
"s",
")",
"\n",
"c",
".",
"stateLock",
".",
"Unlock",
... | // Sets the client state in a thread-safe manner. | [
"Sets",
"the",
"client",
"state",
"in",
"a",
"thread",
"-",
"safe",
"manner",
"."
] | a5663a71d6be64b703bd3dccb819ba06f3f25a52 | https://github.com/mixer/redutil/blob/a5663a71d6be64b703bd3dccb819ba06f3f25a52/pubsub/client.go#L127-L148 |
15,106 | mixer/redutil | pubsub/client.go | Connect | func (c *Client) Connect() {
for c.GetState() == DisconnectedState {
go c.resubscribe()
c.doConnection()
time.Sleep(c.policy.Next())
}
c.setState(ClosedState)
} | go | func (c *Client) Connect() {
for c.GetState() == DisconnectedState {
go c.resubscribe()
c.doConnection()
time.Sleep(c.policy.Next())
}
c.setState(ClosedState)
} | [
"func",
"(",
"c",
"*",
"Client",
")",
"Connect",
"(",
")",
"{",
"for",
"c",
".",
"GetState",
"(",
")",
"==",
"DisconnectedState",
"{",
"go",
"c",
".",
"resubscribe",
"(",
")",
"\n",
"c",
".",
"doConnection",
"(",
")",
"\n",
"time",
".",
"Sleep",
... | // Tries to reconnect to pubsub, looping until we're able to do so
// successfully. This must be called to activate the client. | [
"Tries",
"to",
"reconnect",
"to",
"pubsub",
"looping",
"until",
"we",
"re",
"able",
"to",
"do",
"so",
"successfully",
".",
"This",
"must",
"be",
"called",
"to",
"activate",
"the",
"client",
"."
] | a5663a71d6be64b703bd3dccb819ba06f3f25a52 | https://github.com/mixer/redutil/blob/a5663a71d6be64b703bd3dccb819ba06f3f25a52/pubsub/client.go#L152-L160 |
15,107 | mixer/redutil | pubsub/client.go | dispatchMessage | func (c *Client) dispatchMessage(message redis.Message) {
if listeners, exists := c.subscribed[message.Channel]; exists {
for _, l := range listeners {
l.Messages <- message
}
}
} | go | func (c *Client) dispatchMessage(message redis.Message) {
if listeners, exists := c.subscribed[message.Channel]; exists {
for _, l := range listeners {
l.Messages <- message
}
}
} | [
"func",
"(",
"c",
"*",
"Client",
")",
"dispatchMessage",
"(",
"message",
"redis",
".",
"Message",
")",
"{",
"if",
"listeners",
",",
"exists",
":=",
"c",
".",
"subscribed",
"[",
"message",
".",
"Channel",
"]",
";",
"exists",
"{",
"for",
"_",
",",
"l",... | // Takes in a Redis message and sends it out to any "listening" channels. | [
"Takes",
"in",
"a",
"Redis",
"message",
"and",
"sends",
"it",
"out",
"to",
"any",
"listening",
"channels",
"."
] | a5663a71d6be64b703bd3dccb819ba06f3f25a52 | https://github.com/mixer/redutil/blob/a5663a71d6be64b703bd3dccb819ba06f3f25a52/pubsub/client.go#L272-L278 |
15,108 | mixer/redutil | pubsub/client.go | dispatchPMessage | func (c *Client) dispatchPMessage(message redis.PMessage) {
if listeners, exists := c.subscribed[message.Pattern]; exists {
for _, l := range listeners {
l.PMessages <- message
}
}
} | go | func (c *Client) dispatchPMessage(message redis.PMessage) {
if listeners, exists := c.subscribed[message.Pattern]; exists {
for _, l := range listeners {
l.PMessages <- message
}
}
} | [
"func",
"(",
"c",
"*",
"Client",
")",
"dispatchPMessage",
"(",
"message",
"redis",
".",
"PMessage",
")",
"{",
"if",
"listeners",
",",
"exists",
":=",
"c",
".",
"subscribed",
"[",
"message",
".",
"Pattern",
"]",
";",
"exists",
"{",
"for",
"_",
",",
"l... | // Takes in a Redis pmessage and sends it out to any "listening" channels. | [
"Takes",
"in",
"a",
"Redis",
"pmessage",
"and",
"sends",
"it",
"out",
"to",
"any",
"listening",
"channels",
"."
] | a5663a71d6be64b703bd3dccb819ba06f3f25a52 | https://github.com/mixer/redutil/blob/a5663a71d6be64b703bd3dccb819ba06f3f25a52/pubsub/client.go#L281-L287 |
15,109 | mixer/redutil | pubsub/client.go | resubscribe | func (c *Client) resubscribe() {
// Swap so that if we reconnect before all tasks are done,
// we don't duplicate things.
subs := c.subscribed
c.subscribed = map[string][]*Listener{}
for _, events := range subs {
// We only need to subscribe on one event, so that the Redis
// connection gets registered. We don't care about the others.
c.tasks <- task{Listener: events[0], Action: subscribeAction, Force: true}
}
} | go | func (c *Client) resubscribe() {
// Swap so that if we reconnect before all tasks are done,
// we don't duplicate things.
subs := c.subscribed
c.subscribed = map[string][]*Listener{}
for _, events := range subs {
// We only need to subscribe on one event, so that the Redis
// connection gets registered. We don't care about the others.
c.tasks <- task{Listener: events[0], Action: subscribeAction, Force: true}
}
} | [
"func",
"(",
"c",
"*",
"Client",
")",
"resubscribe",
"(",
")",
"{",
"// Swap so that if we reconnect before all tasks are done,",
"// we don't duplicate things.",
"subs",
":=",
"c",
".",
"subscribed",
"\n",
"c",
".",
"subscribed",
"=",
"map",
"[",
"string",
"]",
"... | // Resubscribes to all Redis events. Good to do after a disconnection. | [
"Resubscribes",
"to",
"all",
"Redis",
"events",
".",
"Good",
"to",
"do",
"after",
"a",
"disconnection",
"."
] | a5663a71d6be64b703bd3dccb819ba06f3f25a52 | https://github.com/mixer/redutil/blob/a5663a71d6be64b703bd3dccb819ba06f3f25a52/pubsub/client.go#L290-L301 |
15,110 | mixer/redutil | pubsub/client.go | TearDown | func (c *Client) TearDown() {
if c.GetState() != ConnectedState {
return
}
c.setState(ClosingState)
c.tasks <- task{Action: disruptAction}
c.WaitFor(ClosedEvent)
} | go | func (c *Client) TearDown() {
if c.GetState() != ConnectedState {
return
}
c.setState(ClosingState)
c.tasks <- task{Action: disruptAction}
c.WaitFor(ClosedEvent)
} | [
"func",
"(",
"c",
"*",
"Client",
")",
"TearDown",
"(",
")",
"{",
"if",
"c",
".",
"GetState",
"(",
")",
"!=",
"ConnectedState",
"{",
"return",
"\n",
"}",
"\n",
"c",
".",
"setState",
"(",
"ClosingState",
")",
"\n",
"c",
".",
"tasks",
"<-",
"task",
... | // Tears down the client - closes the connection and stops
// listening for connections. | [
"Tears",
"down",
"the",
"client",
"-",
"closes",
"the",
"connection",
"and",
"stops",
"listening",
"for",
"connections",
"."
] | a5663a71d6be64b703bd3dccb819ba06f3f25a52 | https://github.com/mixer/redutil/blob/a5663a71d6be64b703bd3dccb819ba06f3f25a52/pubsub/client.go#L305-L313 |
15,111 | mixer/redutil | pubsub/client.go | Subscribe | func (c *Client) Subscribe(listener *Listener) {
listener.Active = true
c.tasks <- task{Listener: listener, Action: subscribeAction}
} | go | func (c *Client) Subscribe(listener *Listener) {
listener.Active = true
c.tasks <- task{Listener: listener, Action: subscribeAction}
} | [
"func",
"(",
"c",
"*",
"Client",
")",
"Subscribe",
"(",
"listener",
"*",
"Listener",
")",
"{",
"listener",
".",
"Active",
"=",
"true",
"\n",
"c",
".",
"tasks",
"<-",
"task",
"{",
"Listener",
":",
"listener",
",",
"Action",
":",
"subscribeAction",
"}",
... | // Subscribes to a Redis event. Strings are sent back down the listener
// channel when they come in, and | [
"Subscribes",
"to",
"a",
"Redis",
"event",
".",
"Strings",
"are",
"sent",
"back",
"down",
"the",
"listener",
"channel",
"when",
"they",
"come",
"in",
"and"
] | a5663a71d6be64b703bd3dccb819ba06f3f25a52 | https://github.com/mixer/redutil/blob/a5663a71d6be64b703bd3dccb819ba06f3f25a52/pubsub/client.go#L317-L320 |
15,112 | mixer/redutil | pubsub/client.go | Unsubscribe | func (c *Client) Unsubscribe(listener *Listener) {
listener.Active = false
c.tasks <- task{Listener: listener, Action: unsubscribeAction}
} | go | func (c *Client) Unsubscribe(listener *Listener) {
listener.Active = false
c.tasks <- task{Listener: listener, Action: unsubscribeAction}
} | [
"func",
"(",
"c",
"*",
"Client",
")",
"Unsubscribe",
"(",
"listener",
"*",
"Listener",
")",
"{",
"listener",
".",
"Active",
"=",
"false",
"\n",
"c",
".",
"tasks",
"<-",
"task",
"{",
"Listener",
":",
"listener",
",",
"Action",
":",
"unsubscribeAction",
... | // Unsubscribe removes the listener from the list of subscribers. If it's the last one
// listening to that Redis event, we unsubscribe entirely. | [
"Unsubscribe",
"removes",
"the",
"listener",
"from",
"the",
"list",
"of",
"subscribers",
".",
"If",
"it",
"s",
"the",
"last",
"one",
"listening",
"to",
"that",
"Redis",
"event",
"we",
"unsubscribe",
"entirely",
"."
] | a5663a71d6be64b703bd3dccb819ba06f3f25a52 | https://github.com/mixer/redutil/blob/a5663a71d6be64b703bd3dccb819ba06f3f25a52/pubsub/client.go#L324-L327 |
15,113 | mixer/redutil | pubsub2/redis.go | Emit | func (r *record) Emit(ev Event, b []byte) {
// This looks absolutely _horrible_. It'd be better in C. Anyway, the idea
// is that we have a list of unsafe pointers, which is stored in the list
// which is an atomic pointer itself. We can swap the pointer held at each
// address in the list, so _that_ address needs to be loaded atomically.
// This means we need to actually load the data from the address at
// offset X from the start of the array underlying the slice.
//
// The cost of the atomic loading makes 5-10% slower, but allows us to
// atomically insert and remove listeners in many cases.
list := r.getUnsafeList()
for i := 0; i < len(list); i++ {
addr := uintptr(unsafe.Pointer(&list[i]))
value := atomic.LoadPointer(*(**unsafe.Pointer)(unsafe.Pointer(&addr)))
if value != nil {
(*(*Listener)(value)).Handle(ev, b)
}
}
} | go | func (r *record) Emit(ev Event, b []byte) {
// This looks absolutely _horrible_. It'd be better in C. Anyway, the idea
// is that we have a list of unsafe pointers, which is stored in the list
// which is an atomic pointer itself. We can swap the pointer held at each
// address in the list, so _that_ address needs to be loaded atomically.
// This means we need to actually load the data from the address at
// offset X from the start of the array underlying the slice.
//
// The cost of the atomic loading makes 5-10% slower, but allows us to
// atomically insert and remove listeners in many cases.
list := r.getUnsafeList()
for i := 0; i < len(list); i++ {
addr := uintptr(unsafe.Pointer(&list[i]))
value := atomic.LoadPointer(*(**unsafe.Pointer)(unsafe.Pointer(&addr)))
if value != nil {
(*(*Listener)(value)).Handle(ev, b)
}
}
} | [
"func",
"(",
"r",
"*",
"record",
")",
"Emit",
"(",
"ev",
"Event",
",",
"b",
"[",
"]",
"byte",
")",
"{",
"// This looks absolutely _horrible_. It'd be better in C. Anyway, the idea",
"// is that we have a list of unsafe pointers, which is stored in the list",
"// which is an ato... | // Emit invokes all attached listeners with the provided event. | [
"Emit",
"invokes",
"all",
"attached",
"listeners",
"with",
"the",
"provided",
"event",
"."
] | a5663a71d6be64b703bd3dccb819ba06f3f25a52 | https://github.com/mixer/redutil/blob/a5663a71d6be64b703bd3dccb819ba06f3f25a52/pubsub2/redis.go#L23-L42 |
15,114 | mixer/redutil | pubsub2/redis.go | Find | func (r *RecordList) Find(ev string) (index int, rec *record) {
for i, rec := range r.getList() {
if rec.name == ev {
return i, rec
}
}
return -1, nil
} | go | func (r *RecordList) Find(ev string) (index int, rec *record) {
for i, rec := range r.getList() {
if rec.name == ev {
return i, rec
}
}
return -1, nil
} | [
"func",
"(",
"r",
"*",
"RecordList",
")",
"Find",
"(",
"ev",
"string",
")",
"(",
"index",
"int",
",",
"rec",
"*",
"record",
")",
"{",
"for",
"i",
",",
"rec",
":=",
"range",
"r",
".",
"getList",
"(",
")",
"{",
"if",
"rec",
".",
"name",
"==",
"... | // Find looks up the index for the record corresponding to the provided
// event name. It returns -1 if one was not found. Thread-safe. | [
"Find",
"looks",
"up",
"the",
"index",
"for",
"the",
"record",
"corresponding",
"to",
"the",
"provided",
"event",
"name",
".",
"It",
"returns",
"-",
"1",
"if",
"one",
"was",
"not",
"found",
".",
"Thread",
"-",
"safe",
"."
] | a5663a71d6be64b703bd3dccb819ba06f3f25a52 | https://github.com/mixer/redutil/blob/a5663a71d6be64b703bd3dccb819ba06f3f25a52/pubsub2/redis.go#L90-L98 |
15,115 | mixer/redutil | pubsub2/redis.go | Add | func (r *RecordList) Add(ev EventBuilder, fn Listener) int {
idx, rec := r.Find(ev.Name())
if idx == -1 {
rec := &record{ev: ev, name: ev.Name()}
rec.setList([]unsafe.Pointer{unsafe.Pointer(&fn)})
r.append(rec)
return 1
}
oldList := rec.getUnsafeList()
newCount := len(oldList) - rec.inactiveItems + 1
if rec.inactiveItems == 0 {
rec.inactiveItems = len(oldList)
newList := make([]unsafe.Pointer, len(oldList)*2+1)
// copy so that the new list items are at the end of the list,
// this lets the slot search later run and find free space faster.
copy(newList[len(oldList)+1:], oldList)
newList[len(oldList)] = unsafe.Pointer(&fn)
rec.setList(newList)
return newCount
}
for i, ptr := range oldList {
if ptr == nil {
rec.storeAtIndex(i, fn)
rec.inactiveItems--
return newCount
}
}
panic("unreachable")
} | go | func (r *RecordList) Add(ev EventBuilder, fn Listener) int {
idx, rec := r.Find(ev.Name())
if idx == -1 {
rec := &record{ev: ev, name: ev.Name()}
rec.setList([]unsafe.Pointer{unsafe.Pointer(&fn)})
r.append(rec)
return 1
}
oldList := rec.getUnsafeList()
newCount := len(oldList) - rec.inactiveItems + 1
if rec.inactiveItems == 0 {
rec.inactiveItems = len(oldList)
newList := make([]unsafe.Pointer, len(oldList)*2+1)
// copy so that the new list items are at the end of the list,
// this lets the slot search later run and find free space faster.
copy(newList[len(oldList)+1:], oldList)
newList[len(oldList)] = unsafe.Pointer(&fn)
rec.setList(newList)
return newCount
}
for i, ptr := range oldList {
if ptr == nil {
rec.storeAtIndex(i, fn)
rec.inactiveItems--
return newCount
}
}
panic("unreachable")
} | [
"func",
"(",
"r",
"*",
"RecordList",
")",
"Add",
"(",
"ev",
"EventBuilder",
",",
"fn",
"Listener",
")",
"int",
"{",
"idx",
",",
"rec",
":=",
"r",
".",
"Find",
"(",
"ev",
".",
"Name",
"(",
")",
")",
"\n",
"if",
"idx",
"==",
"-",
"1",
"{",
"rec... | // Add inserts a new listener for an event. Returns the incremented
// number of listeners. Not thread-safe with other write operations. | [
"Add",
"inserts",
"a",
"new",
"listener",
"for",
"an",
"event",
".",
"Returns",
"the",
"incremented",
"number",
"of",
"listeners",
".",
"Not",
"thread",
"-",
"safe",
"with",
"other",
"write",
"operations",
"."
] | a5663a71d6be64b703bd3dccb819ba06f3f25a52 | https://github.com/mixer/redutil/blob/a5663a71d6be64b703bd3dccb819ba06f3f25a52/pubsub2/redis.go#L102-L133 |
15,116 | mixer/redutil | pubsub2/redis.go | Remove | func (r *RecordList) Remove(ev EventBuilder, fn Listener) int {
idx, rec := r.Find(ev.Name())
if idx == -1 {
return 0
}
// 1. Find the index of the listener in the list
oldList := rec.getUnsafeList()
spliceIndex := -1
for i, l := range oldList {
if l != nil && (*(*Listener)(l)) == fn {
spliceIndex = i
break
}
}
if spliceIndex == -1 {
return len(oldList)
}
newCount := len(oldList) - rec.inactiveItems - 1
// 2. If that's the only listener, just remove that record entirely.
if newCount == 0 {
r.remove(idx)
return 0
}
// 3. Otherwise, wipe the pointer, or make a new list copied from the parts
// of the old if we wanted to compact it.
if float32(rec.inactiveItems+1)/float32(len(oldList)) < compactionThreshold {
rec.storeAtIndex(spliceIndex, nil)
rec.inactiveItems++
return newCount
}
newList := make([]unsafe.Pointer, 0, newCount)
for i, ptr := range oldList {
if ptr != nil && i != spliceIndex {
newList = append(newList, ptr)
}
}
rec.inactiveItems = 0
rec.setList(newList)
return newCount
} | go | func (r *RecordList) Remove(ev EventBuilder, fn Listener) int {
idx, rec := r.Find(ev.Name())
if idx == -1 {
return 0
}
// 1. Find the index of the listener in the list
oldList := rec.getUnsafeList()
spliceIndex := -1
for i, l := range oldList {
if l != nil && (*(*Listener)(l)) == fn {
spliceIndex = i
break
}
}
if spliceIndex == -1 {
return len(oldList)
}
newCount := len(oldList) - rec.inactiveItems - 1
// 2. If that's the only listener, just remove that record entirely.
if newCount == 0 {
r.remove(idx)
return 0
}
// 3. Otherwise, wipe the pointer, or make a new list copied from the parts
// of the old if we wanted to compact it.
if float32(rec.inactiveItems+1)/float32(len(oldList)) < compactionThreshold {
rec.storeAtIndex(spliceIndex, nil)
rec.inactiveItems++
return newCount
}
newList := make([]unsafe.Pointer, 0, newCount)
for i, ptr := range oldList {
if ptr != nil && i != spliceIndex {
newList = append(newList, ptr)
}
}
rec.inactiveItems = 0
rec.setList(newList)
return newCount
} | [
"func",
"(",
"r",
"*",
"RecordList",
")",
"Remove",
"(",
"ev",
"EventBuilder",
",",
"fn",
"Listener",
")",
"int",
"{",
"idx",
",",
"rec",
":=",
"r",
".",
"Find",
"(",
"ev",
".",
"Name",
"(",
")",
")",
"\n",
"if",
"idx",
"==",
"-",
"1",
"{",
"... | // Remove delete the listener from the event. Returns the event's remaining
// listeners. Not thread-safe with other write operations. | [
"Remove",
"delete",
"the",
"listener",
"from",
"the",
"event",
".",
"Returns",
"the",
"event",
"s",
"remaining",
"listeners",
".",
"Not",
"thread",
"-",
"safe",
"with",
"other",
"write",
"operations",
"."
] | a5663a71d6be64b703bd3dccb819ba06f3f25a52 | https://github.com/mixer/redutil/blob/a5663a71d6be64b703bd3dccb819ba06f3f25a52/pubsub2/redis.go#L137-L182 |
15,117 | mixer/redutil | pubsub2/redis.go | ListenersFor | func (r *RecordList) ListenersFor(ev EventBuilder) []Listener {
idx, rec := r.Find(ev.Name())
if idx == -1 {
return nil
}
return rec.getList()
} | go | func (r *RecordList) ListenersFor(ev EventBuilder) []Listener {
idx, rec := r.Find(ev.Name())
if idx == -1 {
return nil
}
return rec.getList()
} | [
"func",
"(",
"r",
"*",
"RecordList",
")",
"ListenersFor",
"(",
"ev",
"EventBuilder",
")",
"[",
"]",
"Listener",
"{",
"idx",
",",
"rec",
":=",
"r",
".",
"Find",
"(",
"ev",
".",
"Name",
"(",
")",
")",
"\n",
"if",
"idx",
"==",
"-",
"1",
"{",
"retu... | // ListenersFor returns the list of listeners attached to the given event. | [
"ListenersFor",
"returns",
"the",
"list",
"of",
"listeners",
"attached",
"to",
"the",
"given",
"event",
"."
] | a5663a71d6be64b703bd3dccb819ba06f3f25a52 | https://github.com/mixer/redutil/blob/a5663a71d6be64b703bd3dccb819ba06f3f25a52/pubsub2/redis.go#L185-L192 |
15,118 | mixer/redutil | pubsub2/redis.go | NewPubsub | func NewPubsub(pool *redis.Pool) *Pubsub {
ps := &Pubsub{
pool: pool,
errs: make(chan error),
closer: make(chan struct{}),
send: make(chan command),
subs: []*RecordList{
PlainEvent: NewRecordList(),
PatternEvent: NewRecordList(),
},
}
go ps.work()
return ps
} | go | func NewPubsub(pool *redis.Pool) *Pubsub {
ps := &Pubsub{
pool: pool,
errs: make(chan error),
closer: make(chan struct{}),
send: make(chan command),
subs: []*RecordList{
PlainEvent: NewRecordList(),
PatternEvent: NewRecordList(),
},
}
go ps.work()
return ps
} | [
"func",
"NewPubsub",
"(",
"pool",
"*",
"redis",
".",
"Pool",
")",
"*",
"Pubsub",
"{",
"ps",
":=",
"&",
"Pubsub",
"{",
"pool",
":",
"pool",
",",
"errs",
":",
"make",
"(",
"chan",
"error",
")",
",",
"closer",
":",
"make",
"(",
"chan",
"struct",
"{"... | // NewPubsub creates a new Emitter based on pubsub on the provided
// Redis pool. | [
"NewPubsub",
"creates",
"a",
"new",
"Emitter",
"based",
"on",
"pubsub",
"on",
"the",
"provided",
"Redis",
"pool",
"."
] | a5663a71d6be64b703bd3dccb819ba06f3f25a52 | https://github.com/mixer/redutil/blob/a5663a71d6be64b703bd3dccb819ba06f3f25a52/pubsub2/redis.go#L229-L244 |
15,119 | mixer/redutil | pubsub2/redis.go | resubscribe | func (p *Pubsub) resubscribe(write *writePump) {
timer := gaugeLatency(PromReconnectLatency)
PromReconnections.Inc()
p.subsMu.Lock()
defer p.subsMu.Unlock()
for kind, recs := range p.subs {
if recs == nil {
continue
}
for _, ev := range recs.getList() {
write.Data() <- command{
command: EventType(kind).SubCommand(),
channel: ev.name,
}
}
}
timer()
} | go | func (p *Pubsub) resubscribe(write *writePump) {
timer := gaugeLatency(PromReconnectLatency)
PromReconnections.Inc()
p.subsMu.Lock()
defer p.subsMu.Unlock()
for kind, recs := range p.subs {
if recs == nil {
continue
}
for _, ev := range recs.getList() {
write.Data() <- command{
command: EventType(kind).SubCommand(),
channel: ev.name,
}
}
}
timer()
} | [
"func",
"(",
"p",
"*",
"Pubsub",
")",
"resubscribe",
"(",
"write",
"*",
"writePump",
")",
"{",
"timer",
":=",
"gaugeLatency",
"(",
"PromReconnectLatency",
")",
"\n",
"PromReconnections",
".",
"Inc",
"(",
")",
"\n\n",
"p",
".",
"subsMu",
".",
"Lock",
"(",... | // resubscribe flushes the `send` queue and replaces it with commands
// to resubscribe to all previously-subscribed-to channels. This will
// NOT block until all subs are resubmitted, only until we get a lock. | [
"resubscribe",
"flushes",
"the",
"send",
"queue",
"and",
"replaces",
"it",
"with",
"commands",
"to",
"resubscribe",
"to",
"all",
"previously",
"-",
"subscribed",
"-",
"to",
"channels",
".",
"This",
"will",
"NOT",
"block",
"until",
"all",
"subs",
"are",
"resu... | a5663a71d6be64b703bd3dccb819ba06f3f25a52 | https://github.com/mixer/redutil/blob/a5663a71d6be64b703bd3dccb819ba06f3f25a52/pubsub2/redis.go#L297-L318 |
15,120 | mixer/redutil | pubsub2/redis.go | Subscribe | func (p *Pubsub) Subscribe(ev EventBuilder, l Listener) {
timer := gaugeLatency(PromSubLatency)
defer timer()
p.subsMu.Lock()
count := p.subs[ev.kind].Add(ev, l)
p.subsMu.Unlock()
if count == 1 {
PromSubscriptions.Inc()
written := make(chan struct{}, 1)
p.send <- command{
command: ev.kind.SubCommand(),
channel: ev.Name(),
written: written,
}
<-written
}
} | go | func (p *Pubsub) Subscribe(ev EventBuilder, l Listener) {
timer := gaugeLatency(PromSubLatency)
defer timer()
p.subsMu.Lock()
count := p.subs[ev.kind].Add(ev, l)
p.subsMu.Unlock()
if count == 1 {
PromSubscriptions.Inc()
written := make(chan struct{}, 1)
p.send <- command{
command: ev.kind.SubCommand(),
channel: ev.Name(),
written: written,
}
<-written
}
} | [
"func",
"(",
"p",
"*",
"Pubsub",
")",
"Subscribe",
"(",
"ev",
"EventBuilder",
",",
"l",
"Listener",
")",
"{",
"timer",
":=",
"gaugeLatency",
"(",
"PromSubLatency",
")",
"\n",
"defer",
"timer",
"(",
")",
"\n\n",
"p",
".",
"subsMu",
".",
"Lock",
"(",
"... | // Subscribe implements Emitter.Subscribe | [
"Subscribe",
"implements",
"Emitter",
".",
"Subscribe"
] | a5663a71d6be64b703bd3dccb819ba06f3f25a52 | https://github.com/mixer/redutil/blob/a5663a71d6be64b703bd3dccb819ba06f3f25a52/pubsub2/redis.go#L354-L373 |
15,121 | mixer/redutil | pubsub2/redis.go | Unsubscribe | func (p *Pubsub) Unsubscribe(ev EventBuilder, l Listener) {
timer := gaugeLatency(PromSubLatency)
defer timer()
p.subsMu.Lock()
count := p.subs[ev.kind].Remove(ev, l)
p.subsMu.Unlock()
if count == 0 {
PromSubscriptions.Dec()
written := make(chan struct{}, 1)
p.send <- command{
command: ev.kind.UnsubCommand(),
channel: ev.Name(),
written: written,
}
<-written
}
} | go | func (p *Pubsub) Unsubscribe(ev EventBuilder, l Listener) {
timer := gaugeLatency(PromSubLatency)
defer timer()
p.subsMu.Lock()
count := p.subs[ev.kind].Remove(ev, l)
p.subsMu.Unlock()
if count == 0 {
PromSubscriptions.Dec()
written := make(chan struct{}, 1)
p.send <- command{
command: ev.kind.UnsubCommand(),
channel: ev.Name(),
written: written,
}
<-written
}
} | [
"func",
"(",
"p",
"*",
"Pubsub",
")",
"Unsubscribe",
"(",
"ev",
"EventBuilder",
",",
"l",
"Listener",
")",
"{",
"timer",
":=",
"gaugeLatency",
"(",
"PromSubLatency",
")",
"\n",
"defer",
"timer",
"(",
")",
"\n\n",
"p",
".",
"subsMu",
".",
"Lock",
"(",
... | // Unsubscribe implements Emitter.Unsubscribe | [
"Unsubscribe",
"implements",
"Emitter",
".",
"Unsubscribe"
] | a5663a71d6be64b703bd3dccb819ba06f3f25a52 | https://github.com/mixer/redutil/blob/a5663a71d6be64b703bd3dccb819ba06f3f25a52/pubsub2/redis.go#L376-L395 |
15,122 | mixer/redutil | pubsub2/event.go | SubCommand | func (e EventType) SubCommand() string {
switch e {
case PlainEvent:
return "SUBSCRIBE"
case PatternEvent:
return "PSUBSCRIBE"
default:
panic(fmt.Sprintf("redutil/pubsub: unknown event type %d", e))
}
} | go | func (e EventType) SubCommand() string {
switch e {
case PlainEvent:
return "SUBSCRIBE"
case PatternEvent:
return "PSUBSCRIBE"
default:
panic(fmt.Sprintf("redutil/pubsub: unknown event type %d", e))
}
} | [
"func",
"(",
"e",
"EventType",
")",
"SubCommand",
"(",
")",
"string",
"{",
"switch",
"e",
"{",
"case",
"PlainEvent",
":",
"return",
"\"",
"\"",
"\n",
"case",
"PatternEvent",
":",
"return",
"\"",
"\"",
"\n",
"default",
":",
"panic",
"(",
"fmt",
".",
"... | // SubCommand returns the command issued to subscribe to the event in Redis. | [
"SubCommand",
"returns",
"the",
"command",
"issued",
"to",
"subscribe",
"to",
"the",
"event",
"in",
"Redis",
"."
] | a5663a71d6be64b703bd3dccb819ba06f3f25a52 | https://github.com/mixer/redutil/blob/a5663a71d6be64b703bd3dccb819ba06f3f25a52/pubsub2/event.go#L31-L40 |
15,123 | mixer/redutil | pubsub2/event.go | Int | func (f Field) Int() (int, error) {
x, err := strconv.ParseInt(f.value, 10, 32)
return int(x), err
} | go | func (f Field) Int() (int, error) {
x, err := strconv.ParseInt(f.value, 10, 32)
return int(x), err
} | [
"func",
"(",
"f",
"Field",
")",
"Int",
"(",
")",
"(",
"int",
",",
"error",
")",
"{",
"x",
",",
"err",
":=",
"strconv",
".",
"ParseInt",
"(",
"f",
".",
"value",
",",
"10",
",",
"32",
")",
"\n",
"return",
"int",
"(",
"x",
")",
",",
"err",
"\n... | // Int attempts to parse and return the field value as an integer. | [
"Int",
"attempts",
"to",
"parse",
"and",
"return",
"the",
"field",
"value",
"as",
"an",
"integer",
"."
] | a5663a71d6be64b703bd3dccb819ba06f3f25a52 | https://github.com/mixer/redutil/blob/a5663a71d6be64b703bd3dccb819ba06f3f25a52/pubsub2/event.go#L74-L77 |
15,124 | mixer/redutil | pubsub2/event.go | String | func (e EventBuilder) String(str string) EventBuilder {
e.fields = append(e.fields, Field{valid: true, value: str})
return e
} | go | func (e EventBuilder) String(str string) EventBuilder {
e.fields = append(e.fields, Field{valid: true, value: str})
return e
} | [
"func",
"(",
"e",
"EventBuilder",
")",
"String",
"(",
"str",
"string",
")",
"EventBuilder",
"{",
"e",
".",
"fields",
"=",
"append",
"(",
"e",
".",
"fields",
",",
"Field",
"{",
"valid",
":",
"true",
",",
"value",
":",
"str",
"}",
")",
"\n",
"return"... | // String creates a Field containing a string. | [
"String",
"creates",
"a",
"Field",
"containing",
"a",
"string",
"."
] | a5663a71d6be64b703bd3dccb819ba06f3f25a52 | https://github.com/mixer/redutil/blob/a5663a71d6be64b703bd3dccb819ba06f3f25a52/pubsub2/event.go#L100-L103 |
15,125 | mixer/redutil | pubsub2/event.go | Int | func (e EventBuilder) Int(x int) EventBuilder {
e.fields = append(e.fields, Field{valid: true, value: strconv.Itoa(x)})
return e
} | go | func (e EventBuilder) Int(x int) EventBuilder {
e.fields = append(e.fields, Field{valid: true, value: strconv.Itoa(x)})
return e
} | [
"func",
"(",
"e",
"EventBuilder",
")",
"Int",
"(",
"x",
"int",
")",
"EventBuilder",
"{",
"e",
".",
"fields",
"=",
"append",
"(",
"e",
".",
"fields",
",",
"Field",
"{",
"valid",
":",
"true",
",",
"value",
":",
"strconv",
".",
"Itoa",
"(",
"x",
")"... | // Int creates a Field containing an integer. | [
"Int",
"creates",
"a",
"Field",
"containing",
"an",
"integer",
"."
] | a5663a71d6be64b703bd3dccb819ba06f3f25a52 | https://github.com/mixer/redutil/blob/a5663a71d6be64b703bd3dccb819ba06f3f25a52/pubsub2/event.go#L106-L109 |
15,126 | mixer/redutil | pubsub2/event.go | Placeholder | func (e EventBuilder) Placeholder() EventBuilder {
e.assertPattern()
e.fields = append(e.fields, Field{valid: true, value: "?", pattern: patternPlaceholder})
return e
} | go | func (e EventBuilder) Placeholder() EventBuilder {
e.assertPattern()
e.fields = append(e.fields, Field{valid: true, value: "?", pattern: patternPlaceholder})
return e
} | [
"func",
"(",
"e",
"EventBuilder",
")",
"Placeholder",
"(",
")",
"EventBuilder",
"{",
"e",
".",
"assertPattern",
"(",
")",
"\n",
"e",
".",
"fields",
"=",
"append",
"(",
"e",
".",
"fields",
",",
"Field",
"{",
"valid",
":",
"true",
",",
"value",
":",
... | // Placeholder creates a field containing a `?` for a placeholder in Redis patterns,
// and chains it on to the event. | [
"Placeholder",
"creates",
"a",
"field",
"containing",
"a",
"?",
"for",
"a",
"placeholder",
"in",
"Redis",
"patterns",
"and",
"chains",
"it",
"on",
"to",
"the",
"event",
"."
] | a5663a71d6be64b703bd3dccb819ba06f3f25a52 | https://github.com/mixer/redutil/blob/a5663a71d6be64b703bd3dccb819ba06f3f25a52/pubsub2/event.go#L121-L125 |
15,127 | mixer/redutil | pubsub2/event.go | Alternatives | func (e EventBuilder) Alternatives(alts string) EventBuilder {
e.assertPattern()
e.fields = append(e.fields, Field{
valid: true,
value: "[" + alts + "]",
pattern: patternAlts,
})
return e
} | go | func (e EventBuilder) Alternatives(alts string) EventBuilder {
e.assertPattern()
e.fields = append(e.fields, Field{
valid: true,
value: "[" + alts + "]",
pattern: patternAlts,
})
return e
} | [
"func",
"(",
"e",
"EventBuilder",
")",
"Alternatives",
"(",
"alts",
"string",
")",
"EventBuilder",
"{",
"e",
".",
"assertPattern",
"(",
")",
"\n",
"e",
".",
"fields",
"=",
"append",
"(",
"e",
".",
"fields",
",",
"Field",
"{",
"valid",
":",
"true",
",... | // Alternatives creates a field with the alts wrapped in brackets, to match
// one of them in a Redis pattern, and chains it on to the event. | [
"Alternatives",
"creates",
"a",
"field",
"with",
"the",
"alts",
"wrapped",
"in",
"brackets",
"to",
"match",
"one",
"of",
"them",
"in",
"a",
"Redis",
"pattern",
"and",
"chains",
"it",
"on",
"to",
"the",
"event",
"."
] | a5663a71d6be64b703bd3dccb819ba06f3f25a52 | https://github.com/mixer/redutil/blob/a5663a71d6be64b703bd3dccb819ba06f3f25a52/pubsub2/event.go#L129-L137 |
15,128 | mixer/redutil | pubsub2/event.go | Name | func (e EventBuilder) Name() string {
strs := make([]string, len(e.fields))
for i, field := range e.fields {
strs[i] = field.value
}
return strings.Join(strs, "")
} | go | func (e EventBuilder) Name() string {
strs := make([]string, len(e.fields))
for i, field := range e.fields {
strs[i] = field.value
}
return strings.Join(strs, "")
} | [
"func",
"(",
"e",
"EventBuilder",
")",
"Name",
"(",
")",
"string",
"{",
"strs",
":=",
"make",
"(",
"[",
"]",
"string",
",",
"len",
"(",
"e",
".",
"fields",
")",
")",
"\n",
"for",
"i",
",",
"field",
":=",
"range",
"e",
".",
"fields",
"{",
"strs"... | // Name returns name of the event, formed by a concatenation of all the
// event fields. | [
"Name",
"returns",
"name",
"of",
"the",
"event",
"formed",
"by",
"a",
"concatenation",
"of",
"all",
"the",
"event",
"fields",
"."
] | a5663a71d6be64b703bd3dccb819ba06f3f25a52 | https://github.com/mixer/redutil/blob/a5663a71d6be64b703bd3dccb819ba06f3f25a52/pubsub2/event.go#L148-L155 |
15,129 | mixer/redutil | pubsub2/event.go | ToEvent | func (e EventBuilder) ToEvent(channel, pattern string) Event {
fields := make([]Field, len(e.fields))
copy(fields, e.fields)
return Event{
fields: fields,
kind: e.kind,
channel: channel,
pattern: pattern,
}
} | go | func (e EventBuilder) ToEvent(channel, pattern string) Event {
fields := make([]Field, len(e.fields))
copy(fields, e.fields)
return Event{
fields: fields,
kind: e.kind,
channel: channel,
pattern: pattern,
}
} | [
"func",
"(",
"e",
"EventBuilder",
")",
"ToEvent",
"(",
"channel",
",",
"pattern",
"string",
")",
"Event",
"{",
"fields",
":=",
"make",
"(",
"[",
"]",
"Field",
",",
"len",
"(",
"e",
".",
"fields",
")",
")",
"\n",
"copy",
"(",
"fields",
",",
"e",
"... | // ToEvent converts an EventBuilder into an immutable event which appears
// to have been send down the provided channel and pattern. This is primarily
// used internally but may also be useful for unit testing. | [
"ToEvent",
"converts",
"an",
"EventBuilder",
"into",
"an",
"immutable",
"event",
"which",
"appears",
"to",
"have",
"been",
"send",
"down",
"the",
"provided",
"channel",
"and",
"pattern",
".",
"This",
"is",
"primarily",
"used",
"internally",
"but",
"may",
"also... | a5663a71d6be64b703bd3dccb819ba06f3f25a52 | https://github.com/mixer/redutil/blob/a5663a71d6be64b703bd3dccb819ba06f3f25a52/pubsub2/event.go#L160-L170 |
15,130 | mixer/redutil | pubsub2/event.go | applyFields | func applyFields(event EventBuilder, values []interface{}) EventBuilder {
for _, v := range values {
switch t := v.(type) {
case string:
event = event.String(t)
case []byte:
event = event.String(string(t))
default:
panic(fmt.Sprintf("Expected string or field when creating an event, got %T", v))
}
}
return event
} | go | func applyFields(event EventBuilder, values []interface{}) EventBuilder {
for _, v := range values {
switch t := v.(type) {
case string:
event = event.String(t)
case []byte:
event = event.String(string(t))
default:
panic(fmt.Sprintf("Expected string or field when creating an event, got %T", v))
}
}
return event
} | [
"func",
"applyFields",
"(",
"event",
"EventBuilder",
",",
"values",
"[",
"]",
"interface",
"{",
"}",
")",
"EventBuilder",
"{",
"for",
"_",
",",
"v",
":=",
"range",
"values",
"{",
"switch",
"t",
":=",
"v",
".",
"(",
"type",
")",
"{",
"case",
"string",... | // applyFields attempts to convert the values from a string or byte slice into
// a Field. It panics if a value is none of the above. | [
"applyFields",
"attempts",
"to",
"convert",
"the",
"values",
"from",
"a",
"string",
"or",
"byte",
"slice",
"into",
"a",
"Field",
".",
"It",
"panics",
"if",
"a",
"value",
"is",
"none",
"of",
"the",
"above",
"."
] | a5663a71d6be64b703bd3dccb819ba06f3f25a52 | https://github.com/mixer/redutil/blob/a5663a71d6be64b703bd3dccb819ba06f3f25a52/pubsub2/event.go#L184-L197 |
15,131 | mixer/redutil | pubsub2/event.go | Get | func (e Event) Get(i int) Field {
if len(e.fields) <= i {
return Field{valid: false}
}
return e.fields[i]
} | go | func (e Event) Get(i int) Field {
if len(e.fields) <= i {
return Field{valid: false}
}
return e.fields[i]
} | [
"func",
"(",
"e",
"Event",
")",
"Get",
"(",
"i",
"int",
")",
"Field",
"{",
"if",
"len",
"(",
"e",
".",
"fields",
")",
"<=",
"i",
"{",
"return",
"Field",
"{",
"valid",
":",
"false",
"}",
"\n",
"}",
"\n\n",
"return",
"e",
".",
"fields",
"[",
"i... | // Get returns the value of a field at index `i` within the event. If the
// field does not exist, an empty struct will be returned. | [
"Get",
"returns",
"the",
"value",
"of",
"a",
"field",
"at",
"index",
"i",
"within",
"the",
"event",
".",
"If",
"the",
"field",
"does",
"not",
"exist",
"an",
"empty",
"struct",
"will",
"be",
"returned",
"."
] | a5663a71d6be64b703bd3dccb819ba06f3f25a52 | https://github.com/mixer/redutil/blob/a5663a71d6be64b703bd3dccb819ba06f3f25a52/pubsub2/event.go#L235-L241 |
15,132 | mixer/redutil | pubsub2/event.go | Find | func (e Event) Find(alias string) Field {
for _, field := range e.fields {
if field.alias == alias {
return field
}
}
return Field{valid: false}
} | go | func (e Event) Find(alias string) Field {
for _, field := range e.fields {
if field.alias == alias {
return field
}
}
return Field{valid: false}
} | [
"func",
"(",
"e",
"Event",
")",
"Find",
"(",
"alias",
"string",
")",
"Field",
"{",
"for",
"_",
",",
"field",
":=",
"range",
"e",
".",
"fields",
"{",
"if",
"field",
".",
"alias",
"==",
"alias",
"{",
"return",
"field",
"\n",
"}",
"\n",
"}",
"\n\n",... | // Find looks up a field value by its alias. This is most useful in pattern
// subscriptions where might use Find to look up a parameterized property.
// If the alias does not exist, an empty struct will be returned. | [
"Find",
"looks",
"up",
"a",
"field",
"value",
"by",
"its",
"alias",
".",
"This",
"is",
"most",
"useful",
"in",
"pattern",
"subscriptions",
"where",
"might",
"use",
"Find",
"to",
"look",
"up",
"a",
"parameterized",
"property",
".",
"If",
"the",
"alias",
"... | a5663a71d6be64b703bd3dccb819ba06f3f25a52 | https://github.com/mixer/redutil/blob/a5663a71d6be64b703bd3dccb819ba06f3f25a52/pubsub2/event.go#L246-L254 |
15,133 | mixer/redutil | pubsub/events.go | Once | func (e *eventEmitter) Once(ev EventType, h EventHandler) {
e.addHandlerToMap(ev, h, e.once)
} | go | func (e *eventEmitter) Once(ev EventType, h EventHandler) {
e.addHandlerToMap(ev, h, e.once)
} | [
"func",
"(",
"e",
"*",
"eventEmitter",
")",
"Once",
"(",
"ev",
"EventType",
",",
"h",
"EventHandler",
")",
"{",
"e",
".",
"addHandlerToMap",
"(",
"ev",
",",
"h",
",",
"e",
".",
"once",
")",
"\n",
"}"
] | // Once adds a handler that's executed once when an event is emitted. | [
"Once",
"adds",
"a",
"handler",
"that",
"s",
"executed",
"once",
"when",
"an",
"event",
"is",
"emitted",
"."
] | a5663a71d6be64b703bd3dccb819ba06f3f25a52 | https://github.com/mixer/redutil/blob/a5663a71d6be64b703bd3dccb819ba06f3f25a52/pubsub/events.go#L58-L60 |
15,134 | mixer/redutil | pubsub/events.go | On | func (e *eventEmitter) On(ev EventType, h EventHandler) {
e.addHandlerToMap(ev, h, e.listeners)
} | go | func (e *eventEmitter) On(ev EventType, h EventHandler) {
e.addHandlerToMap(ev, h, e.listeners)
} | [
"func",
"(",
"e",
"*",
"eventEmitter",
")",
"On",
"(",
"ev",
"EventType",
",",
"h",
"EventHandler",
")",
"{",
"e",
".",
"addHandlerToMap",
"(",
"ev",
",",
"h",
",",
"e",
".",
"listeners",
")",
"\n",
"}"
] | // On adds a handler that's executed when an event happens. | [
"On",
"adds",
"a",
"handler",
"that",
"s",
"executed",
"when",
"an",
"event",
"happens",
"."
] | a5663a71d6be64b703bd3dccb819ba06f3f25a52 | https://github.com/mixer/redutil/blob/a5663a71d6be64b703bd3dccb819ba06f3f25a52/pubsub/events.go#L63-L65 |
15,135 | mixer/redutil | pubsub/events.go | OnChannel | func (e *eventEmitter) OnChannel(ev EventType) chan Event {
ch := make(chan Event, 1)
e.On(ev, func(e Event) {
ch <- e
})
return ch
} | go | func (e *eventEmitter) OnChannel(ev EventType) chan Event {
ch := make(chan Event, 1)
e.On(ev, func(e Event) {
ch <- e
})
return ch
} | [
"func",
"(",
"e",
"*",
"eventEmitter",
")",
"OnChannel",
"(",
"ev",
"EventType",
")",
"chan",
"Event",
"{",
"ch",
":=",
"make",
"(",
"chan",
"Event",
",",
"1",
")",
"\n",
"e",
".",
"On",
"(",
"ev",
",",
"func",
"(",
"e",
"Event",
")",
"{",
"ch"... | // Creates a channel that gets written to when a new event comes in. | [
"Creates",
"a",
"channel",
"that",
"gets",
"written",
"to",
"when",
"a",
"new",
"event",
"comes",
"in",
"."
] | a5663a71d6be64b703bd3dccb819ba06f3f25a52 | https://github.com/mixer/redutil/blob/a5663a71d6be64b703bd3dccb819ba06f3f25a52/pubsub/events.go#L68-L75 |
15,136 | mixer/redutil | pubsub/events.go | emit | func (e *eventEmitter) emit(typ EventType, data interface{}) {
ev := Event{Type: typ, Packet: data}
e.lock.Lock()
lists := [][]EventHandler{}
if handlers, ok := e.listeners[ev.Type]; ok {
lists = append(lists, handlers)
}
if handlers, ok := e.once[ev.Type]; ok {
lists = append(lists, handlers)
delete(e.once, ev.Type)
}
e.lock.Unlock()
for _, list := range lists {
for _, handler := range list {
go handler(ev)
}
}
} | go | func (e *eventEmitter) emit(typ EventType, data interface{}) {
ev := Event{Type: typ, Packet: data}
e.lock.Lock()
lists := [][]EventHandler{}
if handlers, ok := e.listeners[ev.Type]; ok {
lists = append(lists, handlers)
}
if handlers, ok := e.once[ev.Type]; ok {
lists = append(lists, handlers)
delete(e.once, ev.Type)
}
e.lock.Unlock()
for _, list := range lists {
for _, handler := range list {
go handler(ev)
}
}
} | [
"func",
"(",
"e",
"*",
"eventEmitter",
")",
"emit",
"(",
"typ",
"EventType",
",",
"data",
"interface",
"{",
"}",
")",
"{",
"ev",
":=",
"Event",
"{",
"Type",
":",
"typ",
",",
"Packet",
":",
"data",
"}",
"\n\n",
"e",
".",
"lock",
".",
"Lock",
"(",
... | // Triggers an event to be sent out to listeners. | [
"Triggers",
"an",
"event",
"to",
"be",
"sent",
"out",
"to",
"listeners",
"."
] | a5663a71d6be64b703bd3dccb819ba06f3f25a52 | https://github.com/mixer/redutil/blob/a5663a71d6be64b703bd3dccb819ba06f3f25a52/pubsub/events.go#L78-L97 |
15,137 | mixer/redutil | pubsub/events.go | WaitFor | func (e *eventEmitter) WaitFor(ev EventType) {
done := make(chan bool)
go func() {
e.Once(ev, func(e Event) {
done <- true
})
}()
<-done
} | go | func (e *eventEmitter) WaitFor(ev EventType) {
done := make(chan bool)
go func() {
e.Once(ev, func(e Event) {
done <- true
})
}()
<-done
} | [
"func",
"(",
"e",
"*",
"eventEmitter",
")",
"WaitFor",
"(",
"ev",
"EventType",
")",
"{",
"done",
":=",
"make",
"(",
"chan",
"bool",
")",
"\n\n",
"go",
"func",
"(",
")",
"{",
"e",
".",
"Once",
"(",
"ev",
",",
"func",
"(",
"e",
"Event",
")",
"{",... | // Blocks until an event is received. Mainly for backwards-compatibility. | [
"Blocks",
"until",
"an",
"event",
"is",
"received",
".",
"Mainly",
"for",
"backwards",
"-",
"compatibility",
"."
] | a5663a71d6be64b703bd3dccb819ba06f3f25a52 | https://github.com/mixer/redutil/blob/a5663a71d6be64b703bd3dccb819ba06f3f25a52/pubsub/events.go#L100-L110 |
15,138 | mixer/redutil | queue/durable_queue.go | NewDurableQueue | func NewDurableQueue(pool *redis.Pool, source, dest string) *DurableQueue {
return &DurableQueue{
dest: dest,
BaseQueue: BaseQueue{source: source, pool: pool},
}
} | go | func NewDurableQueue(pool *redis.Pool, source, dest string) *DurableQueue {
return &DurableQueue{
dest: dest,
BaseQueue: BaseQueue{source: source, pool: pool},
}
} | [
"func",
"NewDurableQueue",
"(",
"pool",
"*",
"redis",
".",
"Pool",
",",
"source",
",",
"dest",
"string",
")",
"*",
"DurableQueue",
"{",
"return",
"&",
"DurableQueue",
"{",
"dest",
":",
"dest",
",",
"BaseQueue",
":",
"BaseQueue",
"{",
"source",
":",
"sour... | // NewDurableQueue initializes and returns a new pointer to an instance of a
// DurableQueue. It is initialized with the given Redis pool, and the source and
// destination queues. By default the FIFO tactic is used, but a call to
// SetProcessor can change this in a safe fashion.
//
// DurableQueues own no goroutines, so this method does not spwawn any
// goroutines or channels. | [
"NewDurableQueue",
"initializes",
"and",
"returns",
"a",
"new",
"pointer",
"to",
"an",
"instance",
"of",
"a",
"DurableQueue",
".",
"It",
"is",
"initialized",
"with",
"the",
"given",
"Redis",
"pool",
"and",
"the",
"source",
"and",
"destination",
"queues",
".",
... | a5663a71d6be64b703bd3dccb819ba06f3f25a52 | https://github.com/mixer/redutil/blob/a5663a71d6be64b703bd3dccb819ba06f3f25a52/queue/durable_queue.go#L33-L38 |
15,139 | mixer/redutil | queue/durable_queue.go | Pull | func (q *DurableQueue) Pull(timeout time.Duration) (payload []byte, err error) {
cnx := q.pool.Get()
defer cnx.Close()
return q.Processor().PullTo(cnx, q.Source(), q.Dest(), timeout)
} | go | func (q *DurableQueue) Pull(timeout time.Duration) (payload []byte, err error) {
cnx := q.pool.Get()
defer cnx.Close()
return q.Processor().PullTo(cnx, q.Source(), q.Dest(), timeout)
} | [
"func",
"(",
"q",
"*",
"DurableQueue",
")",
"Pull",
"(",
"timeout",
"time",
".",
"Duration",
")",
"(",
"payload",
"[",
"]",
"byte",
",",
"err",
"error",
")",
"{",
"cnx",
":=",
"q",
".",
"pool",
".",
"Get",
"(",
")",
"\n",
"defer",
"cnx",
".",
"... | // Pull implements the Pull function on the Queue interface. Unlike common
// implementations of the Queue type, it mutates the Redis keyspace twice, by
// removing an item from one LIST and popping it onto another. It does so by
// delegating into the processor, thus blocking until the processor returns. | [
"Pull",
"implements",
"the",
"Pull",
"function",
"on",
"the",
"Queue",
"interface",
".",
"Unlike",
"common",
"implementations",
"of",
"the",
"Queue",
"type",
"it",
"mutates",
"the",
"Redis",
"keyspace",
"twice",
"by",
"removing",
"an",
"item",
"from",
"one",
... | a5663a71d6be64b703bd3dccb819ba06f3f25a52 | https://github.com/mixer/redutil/blob/a5663a71d6be64b703bd3dccb819ba06f3f25a52/queue/durable_queue.go#L44-L49 |
15,140 | mixer/redutil | queue/durable_queue.go | Dest | func (q *DurableQueue) Dest() string {
q.dmu.RLock()
defer q.dmu.RUnlock()
return q.dest
} | go | func (q *DurableQueue) Dest() string {
q.dmu.RLock()
defer q.dmu.RUnlock()
return q.dest
} | [
"func",
"(",
"q",
"*",
"DurableQueue",
")",
"Dest",
"(",
")",
"string",
"{",
"q",
".",
"dmu",
".",
"RLock",
"(",
")",
"\n",
"defer",
"q",
".",
"dmu",
".",
"RUnlock",
"(",
")",
"\n\n",
"return",
"q",
".",
"dest",
"\n",
"}"
] | // Dest returns the destination keyspace in Redis where pulled items end up. It
// first obtains a read-level lock on the member `dest` variable before
// returning. | [
"Dest",
"returns",
"the",
"destination",
"keyspace",
"in",
"Redis",
"where",
"pulled",
"items",
"end",
"up",
".",
"It",
"first",
"obtains",
"a",
"read",
"-",
"level",
"lock",
"on",
"the",
"member",
"dest",
"variable",
"before",
"returning",
"."
] | a5663a71d6be64b703bd3dccb819ba06f3f25a52 | https://github.com/mixer/redutil/blob/a5663a71d6be64b703bd3dccb819ba06f3f25a52/queue/durable_queue.go#L54-L59 |
15,141 | mixer/redutil | queue/durable_queue.go | SetDest | func (q *DurableQueue) SetDest(dest string) string {
q.dmu.Lock()
defer q.dmu.Unlock()
q.dest = dest
return q.dest
} | go | func (q *DurableQueue) SetDest(dest string) string {
q.dmu.Lock()
defer q.dmu.Unlock()
q.dest = dest
return q.dest
} | [
"func",
"(",
"q",
"*",
"DurableQueue",
")",
"SetDest",
"(",
"dest",
"string",
")",
"string",
"{",
"q",
".",
"dmu",
".",
"Lock",
"(",
")",
"\n",
"defer",
"q",
".",
"dmu",
".",
"Unlock",
"(",
")",
"\n\n",
"q",
".",
"dest",
"=",
"dest",
"\n\n",
"r... | // SetDest updates the destination where items are "pulled" to in a safe,
// blocking manner. It does this by first obtaining a write-level lock on the
// internal member variable wherein the destination is stored, updating, and
// then relinquishing the lock.
//
// It returns the new destination that was just set. | [
"SetDest",
"updates",
"the",
"destination",
"where",
"items",
"are",
"pulled",
"to",
"in",
"a",
"safe",
"blocking",
"manner",
".",
"It",
"does",
"this",
"by",
"first",
"obtaining",
"a",
"write",
"-",
"level",
"lock",
"on",
"the",
"internal",
"member",
"var... | a5663a71d6be64b703bd3dccb819ba06f3f25a52 | https://github.com/mixer/redutil/blob/a5663a71d6be64b703bd3dccb819ba06f3f25a52/queue/durable_queue.go#L67-L74 |
15,142 | mixer/redutil | queue/base_queue.go | Pull | func (q *BaseQueue) Pull(timeout time.Duration) (payload []byte, err error) {
cnx := q.pool.Get()
defer cnx.Close()
return q.Processor().Pull(cnx, q.Source(), timeout)
} | go | func (q *BaseQueue) Pull(timeout time.Duration) (payload []byte, err error) {
cnx := q.pool.Get()
defer cnx.Close()
return q.Processor().Pull(cnx, q.Source(), timeout)
} | [
"func",
"(",
"q",
"*",
"BaseQueue",
")",
"Pull",
"(",
"timeout",
"time",
".",
"Duration",
")",
"(",
"payload",
"[",
"]",
"byte",
",",
"err",
"error",
")",
"{",
"cnx",
":=",
"q",
".",
"pool",
".",
"Get",
"(",
")",
"\n",
"defer",
"cnx",
".",
"Clo... | // Source implements the Source method on the Queue interface. | [
"Source",
"implements",
"the",
"Source",
"method",
"on",
"the",
"Queue",
"interface",
"."
] | a5663a71d6be64b703bd3dccb819ba06f3f25a52 | https://github.com/mixer/redutil/blob/a5663a71d6be64b703bd3dccb819ba06f3f25a52/queue/base_queue.go#L50-L55 |
15,143 | mixer/redutil | queue/base_queue.go | Processor | func (q *BaseQueue) Processor() Processor {
q.pmu.RLock()
defer q.pmu.RUnlock()
if q.processor == nil {
return FIFO
}
return q.processor
} | go | func (q *BaseQueue) Processor() Processor {
q.pmu.RLock()
defer q.pmu.RUnlock()
if q.processor == nil {
return FIFO
}
return q.processor
} | [
"func",
"(",
"q",
"*",
"BaseQueue",
")",
"Processor",
"(",
")",
"Processor",
"{",
"q",
".",
"pmu",
".",
"RLock",
"(",
")",
"\n",
"defer",
"q",
".",
"pmu",
".",
"RUnlock",
"(",
")",
"\n\n",
"if",
"q",
".",
"processor",
"==",
"nil",
"{",
"return",
... | // Source implements the Source method on the Queue interface. It functions by
// requesting a read-level lock from the guarding mutex and returning that value
// once obtained. If no processor is set, the the default FIFO implementation is
// returned. | [
"Source",
"implements",
"the",
"Source",
"method",
"on",
"the",
"Queue",
"interface",
".",
"It",
"functions",
"by",
"requesting",
"a",
"read",
"-",
"level",
"lock",
"from",
"the",
"guarding",
"mutex",
"and",
"returning",
"that",
"value",
"once",
"obtained",
... | a5663a71d6be64b703bd3dccb819ba06f3f25a52 | https://github.com/mixer/redutil/blob/a5663a71d6be64b703bd3dccb819ba06f3f25a52/queue/base_queue.go#L61-L70 |
15,144 | mixer/redutil | queue/base_queue.go | SetProcessor | func (q *BaseQueue) SetProcessor(processor Processor) {
q.pmu.Lock()
defer q.pmu.Unlock()
q.processor = processor
} | go | func (q *BaseQueue) SetProcessor(processor Processor) {
q.pmu.Lock()
defer q.pmu.Unlock()
q.processor = processor
} | [
"func",
"(",
"q",
"*",
"BaseQueue",
")",
"SetProcessor",
"(",
"processor",
"Processor",
")",
"{",
"q",
".",
"pmu",
".",
"Lock",
"(",
")",
"\n",
"defer",
"q",
".",
"pmu",
".",
"Unlock",
"(",
")",
"\n\n",
"q",
".",
"processor",
"=",
"processor",
"\n"... | // SetProcessor implements the SetProcessor method on the Queue interface. It
// functions by requesting write-level access from the guarding mutex and
// preforms the update atomically. | [
"SetProcessor",
"implements",
"the",
"SetProcessor",
"method",
"on",
"the",
"Queue",
"interface",
".",
"It",
"functions",
"by",
"requesting",
"write",
"-",
"level",
"access",
"from",
"the",
"guarding",
"mutex",
"and",
"preforms",
"the",
"update",
"atomically",
"... | a5663a71d6be64b703bd3dccb819ba06f3f25a52 | https://github.com/mixer/redutil/blob/a5663a71d6be64b703bd3dccb819ba06f3f25a52/queue/base_queue.go#L75-L80 |
15,145 | mixer/redutil | queue/base_queue.go | Concat | func (q *BaseQueue) Concat(src string) (moved int, err error) {
cnx := q.pool.Get()
defer cnx.Close()
errCount := 0
for {
err = q.Processor().Concat(cnx, src, q.Source())
if err == nil {
errCount = 0
moved++
continue
}
// ErrNil is returned when there are no more items to concat
if err == redis.ErrNil {
return
}
// Command error are bad; something is wrong in db and we should
// return the problem to the caller.
if _, cmdErr := err.(redis.Error); cmdErr {
return
}
// Otherwise this is probably some temporary network error. Close
// the old connection and try getting a new one.
errCount++
if errCount >= concatRetries {
return
}
cnx.Close()
cnx = q.pool.Get()
}
} | go | func (q *BaseQueue) Concat(src string) (moved int, err error) {
cnx := q.pool.Get()
defer cnx.Close()
errCount := 0
for {
err = q.Processor().Concat(cnx, src, q.Source())
if err == nil {
errCount = 0
moved++
continue
}
// ErrNil is returned when there are no more items to concat
if err == redis.ErrNil {
return
}
// Command error are bad; something is wrong in db and we should
// return the problem to the caller.
if _, cmdErr := err.(redis.Error); cmdErr {
return
}
// Otherwise this is probably some temporary network error. Close
// the old connection and try getting a new one.
errCount++
if errCount >= concatRetries {
return
}
cnx.Close()
cnx = q.pool.Get()
}
} | [
"func",
"(",
"q",
"*",
"BaseQueue",
")",
"Concat",
"(",
"src",
"string",
")",
"(",
"moved",
"int",
",",
"err",
"error",
")",
"{",
"cnx",
":=",
"q",
".",
"pool",
".",
"Get",
"(",
")",
"\n",
"defer",
"cnx",
".",
"Close",
"(",
")",
"\n\n",
"errCou... | // Concat takes all elements from the source queue and adds them to this one. This
// can be a long-running operation. If a persistent error is returned while
// moving things, then it will be returned and the concat will stop, though
// the concat operation can be safely resumed at any time. | [
"Concat",
"takes",
"all",
"elements",
"from",
"the",
"source",
"queue",
"and",
"adds",
"them",
"to",
"this",
"one",
".",
"This",
"can",
"be",
"a",
"long",
"-",
"running",
"operation",
".",
"If",
"a",
"persistent",
"error",
"is",
"returned",
"while",
"mov... | a5663a71d6be64b703bd3dccb819ba06f3f25a52 | https://github.com/mixer/redutil/blob/a5663a71d6be64b703bd3dccb819ba06f3f25a52/queue/base_queue.go#L86-L120 |
15,146 | mixer/redutil | heartbeat/heartbeater.go | New | func New(id, location string, interval time.Duration, pool *redis.Pool) *Heartbeater {
h := &Heartbeater{
ID: id,
Location: location,
interval: interval,
pool: pool,
}
h.Strategy = HashExpireyStrategy{h.MaxAge()}
return h
} | go | func New(id, location string, interval time.Duration, pool *redis.Pool) *Heartbeater {
h := &Heartbeater{
ID: id,
Location: location,
interval: interval,
pool: pool,
}
h.Strategy = HashExpireyStrategy{h.MaxAge()}
return h
} | [
"func",
"New",
"(",
"id",
",",
"location",
"string",
",",
"interval",
"time",
".",
"Duration",
",",
"pool",
"*",
"redis",
".",
"Pool",
")",
"*",
"Heartbeater",
"{",
"h",
":=",
"&",
"Heartbeater",
"{",
"ID",
":",
"id",
",",
"Location",
":",
"location"... | // New allocates and returns a pointer to a new instance of a Heartbeater. It
// takes in the id, location, interval and pool with which to use to create
// Hearts and Detectors. | [
"New",
"allocates",
"and",
"returns",
"a",
"pointer",
"to",
"a",
"new",
"instance",
"of",
"a",
"Heartbeater",
".",
"It",
"takes",
"in",
"the",
"id",
"location",
"interval",
"and",
"pool",
"with",
"which",
"to",
"use",
"to",
"create",
"Hearts",
"and",
"De... | a5663a71d6be64b703bd3dccb819ba06f3f25a52 | https://github.com/mixer/redutil/blob/a5663a71d6be64b703bd3dccb819ba06f3f25a52/heartbeat/heartbeater.go#L36-L46 |
15,147 | mixer/redutil | heartbeat/heartbeater.go | Heart | func (h *Heartbeater) Heart() Heart {
// TODO: missing strategy field here
return NewSimpleHeart(h.ID, h.Location, h.interval, h.pool, h.Strategy)
} | go | func (h *Heartbeater) Heart() Heart {
// TODO: missing strategy field here
return NewSimpleHeart(h.ID, h.Location, h.interval, h.pool, h.Strategy)
} | [
"func",
"(",
"h",
"*",
"Heartbeater",
")",
"Heart",
"(",
")",
"Heart",
"{",
"// TODO: missing strategy field here",
"return",
"NewSimpleHeart",
"(",
"h",
".",
"ID",
",",
"h",
".",
"Location",
",",
"h",
".",
"interval",
",",
"h",
".",
"pool",
",",
"h",
... | // Heart creates and returns a new instance of the Heart type with the
// parameters used by the Heartbeater for consistency. | [
"Heart",
"creates",
"and",
"returns",
"a",
"new",
"instance",
"of",
"the",
"Heart",
"type",
"with",
"the",
"parameters",
"used",
"by",
"the",
"Heartbeater",
"for",
"consistency",
"."
] | a5663a71d6be64b703bd3dccb819ba06f3f25a52 | https://github.com/mixer/redutil/blob/a5663a71d6be64b703bd3dccb819ba06f3f25a52/heartbeat/heartbeater.go#L55-L58 |
15,148 | mixer/redutil | heartbeat/heartbeater.go | Detector | func (h *Heartbeater) Detector() Detector {
return NewDetector(h.Location, h.pool, h.Strategy)
} | go | func (h *Heartbeater) Detector() Detector {
return NewDetector(h.Location, h.pool, h.Strategy)
} | [
"func",
"(",
"h",
"*",
"Heartbeater",
")",
"Detector",
"(",
")",
"Detector",
"{",
"return",
"NewDetector",
"(",
"h",
".",
"Location",
",",
"h",
".",
"pool",
",",
"h",
".",
"Strategy",
")",
"\n",
"}"
] | // Detectors creates and returns a new instance of the Detector type with the
// parameters used by the Heartbeater for consistency. | [
"Detectors",
"creates",
"and",
"returns",
"a",
"new",
"instance",
"of",
"the",
"Detector",
"type",
"with",
"the",
"parameters",
"used",
"by",
"the",
"Heartbeater",
"for",
"consistency",
"."
] | a5663a71d6be64b703bd3dccb819ba06f3f25a52 | https://github.com/mixer/redutil/blob/a5663a71d6be64b703bd3dccb819ba06f3f25a52/heartbeat/heartbeater.go#L62-L64 |
15,149 | mixer/redutil | heartbeat/heartbeater.go | SetStrategy | func (h *Heartbeater) SetStrategy(strategy Strategy) *Heartbeater {
h.Strategy = strategy
return h
} | go | func (h *Heartbeater) SetStrategy(strategy Strategy) *Heartbeater {
h.Strategy = strategy
return h
} | [
"func",
"(",
"h",
"*",
"Heartbeater",
")",
"SetStrategy",
"(",
"strategy",
"Strategy",
")",
"*",
"Heartbeater",
"{",
"h",
".",
"Strategy",
"=",
"strategy",
"\n\n",
"return",
"h",
"\n",
"}"
] | // SetStrategy changes the strategy used by all future Heart and Detector
// instantiations. | [
"SetStrategy",
"changes",
"the",
"strategy",
"used",
"by",
"all",
"future",
"Heart",
"and",
"Detector",
"instantiations",
"."
] | a5663a71d6be64b703bd3dccb819ba06f3f25a52 | https://github.com/mixer/redutil/blob/a5663a71d6be64b703bd3dccb819ba06f3f25a52/heartbeat/heartbeater.go#L80-L84 |
15,150 | mixer/redutil | queue/fifo_processor.go | Push | func (f *fifoProcessor) Push(cnx redis.Conn, src string, payload []byte) (err error) {
_, err = cnx.Do("LPUSH", src, payload)
return
} | go | func (f *fifoProcessor) Push(cnx redis.Conn, src string, payload []byte) (err error) {
_, err = cnx.Do("LPUSH", src, payload)
return
} | [
"func",
"(",
"f",
"*",
"fifoProcessor",
")",
"Push",
"(",
"cnx",
"redis",
".",
"Conn",
",",
"src",
"string",
",",
"payload",
"[",
"]",
"byte",
")",
"(",
"err",
"error",
")",
"{",
"_",
",",
"err",
"=",
"cnx",
".",
"Do",
"(",
"\"",
"\"",
",",
"... | // Push implements the `func Push` from `Processor`. It pushes to the left-side
// of the Redis structure using RPUSH, and returns any errors encountered while
// runnning that command. | [
"Push",
"implements",
"the",
"func",
"Push",
"from",
"Processor",
".",
"It",
"pushes",
"to",
"the",
"left",
"-",
"side",
"of",
"the",
"Redis",
"structure",
"using",
"RPUSH",
"and",
"returns",
"any",
"errors",
"encountered",
"while",
"runnning",
"that",
"comm... | a5663a71d6be64b703bd3dccb819ba06f3f25a52 | https://github.com/mixer/redutil/blob/a5663a71d6be64b703bd3dccb819ba06f3f25a52/queue/fifo_processor.go#L17-L20 |
15,151 | mixer/redutil | worker/util.go | concatErrs | func concatErrs(errs ...<-chan error) <-chan error {
cases := make([]reflect.SelectCase, len(errs))
for i, ch := range errs {
cases[i] = reflect.SelectCase{
Dir: reflect.SelectRecv,
Chan: reflect.ValueOf(ch),
}
}
out := make(chan error)
go func() {
for len(cases) > 0 {
chosen, value, ok := reflect.Select(cases)
if !ok {
cases = append(cases[:chosen], cases[chosen+1:]...)
} else {
out <- value.Interface().(error)
}
}
close(out)
}()
return out
} | go | func concatErrs(errs ...<-chan error) <-chan error {
cases := make([]reflect.SelectCase, len(errs))
for i, ch := range errs {
cases[i] = reflect.SelectCase{
Dir: reflect.SelectRecv,
Chan: reflect.ValueOf(ch),
}
}
out := make(chan error)
go func() {
for len(cases) > 0 {
chosen, value, ok := reflect.Select(cases)
if !ok {
cases = append(cases[:chosen], cases[chosen+1:]...)
} else {
out <- value.Interface().(error)
}
}
close(out)
}()
return out
} | [
"func",
"concatErrs",
"(",
"errs",
"...",
"<-",
"chan",
"error",
")",
"<-",
"chan",
"error",
"{",
"cases",
":=",
"make",
"(",
"[",
"]",
"reflect",
".",
"SelectCase",
",",
"len",
"(",
"errs",
")",
")",
"\n",
"for",
"i",
",",
"ch",
":=",
"range",
"... | // Concatenates the output from several error channels into a single one.
// Stops and closes the resulting channel when all its inputs are closed. | [
"Concatenates",
"the",
"output",
"from",
"several",
"error",
"channels",
"into",
"a",
"single",
"one",
".",
"Stops",
"and",
"closes",
"the",
"resulting",
"channel",
"when",
"all",
"its",
"inputs",
"are",
"closed",
"."
] | a5663a71d6be64b703bd3dccb819ba06f3f25a52 | https://github.com/mixer/redutil/blob/a5663a71d6be64b703bd3dccb819ba06f3f25a52/worker/util.go#L7-L31 |
15,152 | mixer/redutil | worker/default_lifecycle.go | Abandon | func (l *DefaultLifecycle) Abandon(task *Task) error {
if err := l.availableTasks.Push(task.Bytes()); err != nil {
return err
}
return l.removeTask(task)
} | go | func (l *DefaultLifecycle) Abandon(task *Task) error {
if err := l.availableTasks.Push(task.Bytes()); err != nil {
return err
}
return l.removeTask(task)
} | [
"func",
"(",
"l",
"*",
"DefaultLifecycle",
")",
"Abandon",
"(",
"task",
"*",
"Task",
")",
"error",
"{",
"if",
"err",
":=",
"l",
".",
"availableTasks",
".",
"Push",
"(",
"task",
".",
"Bytes",
"(",
")",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
... | // Abandon marks a task as having failed, pushing it back onto the primary
// task queue and removing it from our worker queue. | [
"Abandon",
"marks",
"a",
"task",
"as",
"having",
"failed",
"pushing",
"it",
"back",
"onto",
"the",
"primary",
"task",
"queue",
"and",
"removing",
"it",
"from",
"our",
"worker",
"queue",
"."
] | a5663a71d6be64b703bd3dccb819ba06f3f25a52 | https://github.com/mixer/redutil/blob/a5663a71d6be64b703bd3dccb819ba06f3f25a52/worker/default_lifecycle.go#L122-L128 |
15,153 | mixer/redutil | worker/default_lifecycle.go | addTask | func (l *DefaultLifecycle) addTask(t *Task) {
l.rmu.Lock()
defer l.rmu.Unlock()
l.registry = append([]*Task{t}, l.registry...)
l.wg.Add(1)
} | go | func (l *DefaultLifecycle) addTask(t *Task) {
l.rmu.Lock()
defer l.rmu.Unlock()
l.registry = append([]*Task{t}, l.registry...)
l.wg.Add(1)
} | [
"func",
"(",
"l",
"*",
"DefaultLifecycle",
")",
"addTask",
"(",
"t",
"*",
"Task",
")",
"{",
"l",
".",
"rmu",
".",
"Lock",
"(",
")",
"\n",
"defer",
"l",
".",
"rmu",
".",
"Unlock",
"(",
")",
"\n\n",
"l",
".",
"registry",
"=",
"append",
"(",
"[",
... | // addTask inserts a newly created task into the internal tasks registry. | [
"addTask",
"inserts",
"a",
"newly",
"created",
"task",
"into",
"the",
"internal",
"tasks",
"registry",
"."
] | a5663a71d6be64b703bd3dccb819ba06f3f25a52 | https://github.com/mixer/redutil/blob/a5663a71d6be64b703bd3dccb819ba06f3f25a52/worker/default_lifecycle.go#L177-L183 |
15,154 | mixer/redutil | worker/default_lifecycle.go | removeTask | func (l *DefaultLifecycle) removeTask(task *Task) (err error) {
l.rmu.Lock()
defer l.rmu.Unlock()
cnx := l.pool.Get()
defer cnx.Close()
i := l.findTaskIndex(task)
if i == -1 {
return ErrNotFound
}
count := len(l.registry)
l.registry = append(l.registry[:i], l.registry[i+1:]...)
// We set the item relative to the end position of the list. Since the
// queue is running BRPOPLPUSH, the index relative to the start of the
// list (left side) might change in the meantime.
_, err = cnx.Do("LSET", l.workingTasks.Dest(), i-count, deleteToken)
if err != nil {
return
}
// Ignore errors from trimming. If this fails, it's unfortunate, but the
// task was still removed successfully. The next LTRIM will remove the
// item or, if not, we'll just ignore it if we read it from the queue.
cnx.Do("LREM", l.workingTasks.Dest(), 0, deleteToken)
l.wg.Done()
return nil
} | go | func (l *DefaultLifecycle) removeTask(task *Task) (err error) {
l.rmu.Lock()
defer l.rmu.Unlock()
cnx := l.pool.Get()
defer cnx.Close()
i := l.findTaskIndex(task)
if i == -1 {
return ErrNotFound
}
count := len(l.registry)
l.registry = append(l.registry[:i], l.registry[i+1:]...)
// We set the item relative to the end position of the list. Since the
// queue is running BRPOPLPUSH, the index relative to the start of the
// list (left side) might change in the meantime.
_, err = cnx.Do("LSET", l.workingTasks.Dest(), i-count, deleteToken)
if err != nil {
return
}
// Ignore errors from trimming. If this fails, it's unfortunate, but the
// task was still removed successfully. The next LTRIM will remove the
// item or, if not, we'll just ignore it if we read it from the queue.
cnx.Do("LREM", l.workingTasks.Dest(), 0, deleteToken)
l.wg.Done()
return nil
} | [
"func",
"(",
"l",
"*",
"DefaultLifecycle",
")",
"removeTask",
"(",
"task",
"*",
"Task",
")",
"(",
"err",
"error",
")",
"{",
"l",
".",
"rmu",
".",
"Lock",
"(",
")",
"\n",
"defer",
"l",
".",
"rmu",
".",
"Unlock",
"(",
")",
"\n",
"cnx",
":=",
"l",... | // Removes a task from the worker's task queue. | [
"Removes",
"a",
"task",
"from",
"the",
"worker",
"s",
"task",
"queue",
"."
] | a5663a71d6be64b703bd3dccb819ba06f3f25a52 | https://github.com/mixer/redutil/blob/a5663a71d6be64b703bd3dccb819ba06f3f25a52/worker/default_lifecycle.go#L186-L215 |
15,155 | mixer/redutil | worker/default_lifecycle.go | findTaskIndex | func (l *DefaultLifecycle) findTaskIndex(task *Task) int {
for i, t := range l.registry {
if t == task {
return i
}
}
return -1
} | go | func (l *DefaultLifecycle) findTaskIndex(task *Task) int {
for i, t := range l.registry {
if t == task {
return i
}
}
return -1
} | [
"func",
"(",
"l",
"*",
"DefaultLifecycle",
")",
"findTaskIndex",
"(",
"task",
"*",
"Task",
")",
"int",
"{",
"for",
"i",
",",
"t",
":=",
"range",
"l",
".",
"registry",
"{",
"if",
"t",
"==",
"task",
"{",
"return",
"i",
"\n",
"}",
"\n",
"}",
"\n\n",... | // Returns the index of the task in the tasks list. Returns -1 if the task
// was not in the list. | [
"Returns",
"the",
"index",
"of",
"the",
"task",
"in",
"the",
"tasks",
"list",
".",
"Returns",
"-",
"1",
"if",
"the",
"task",
"was",
"not",
"in",
"the",
"list",
"."
] | a5663a71d6be64b703bd3dccb819ba06f3f25a52 | https://github.com/mixer/redutil/blob/a5663a71d6be64b703bd3dccb819ba06f3f25a52/worker/default_lifecycle.go#L219-L227 |
15,156 | mixer/redutil | worker/task.go | Succeed | func (t *Task) Succeed() error {
return t.guardResolution(func() error {
return t.lifecycle.Complete(t)
})
} | go | func (t *Task) Succeed() error {
return t.guardResolution(func() error {
return t.lifecycle.Complete(t)
})
} | [
"func",
"(",
"t",
"*",
"Task",
")",
"Succeed",
"(",
")",
"error",
"{",
"return",
"t",
".",
"guardResolution",
"(",
"func",
"(",
")",
"error",
"{",
"return",
"t",
".",
"lifecycle",
".",
"Complete",
"(",
"t",
")",
"\n",
"}",
")",
"\n",
"}"
] | // Succeed signals the lifecycle that work on this task has been completed,
// and removes the task from the worker queue. | [
"Succeed",
"signals",
"the",
"lifecycle",
"that",
"work",
"on",
"this",
"task",
"has",
"been",
"completed",
"and",
"removes",
"the",
"task",
"from",
"the",
"worker",
"queue",
"."
] | a5663a71d6be64b703bd3dccb819ba06f3f25a52 | https://github.com/mixer/redutil/blob/a5663a71d6be64b703bd3dccb819ba06f3f25a52/worker/task.go#L45-L49 |
15,157 | mixer/redutil | worker/task.go | Fail | func (t *Task) Fail() error {
return t.guardResolution(func() error {
return t.lifecycle.Abandon(t)
})
} | go | func (t *Task) Fail() error {
return t.guardResolution(func() error {
return t.lifecycle.Abandon(t)
})
} | [
"func",
"(",
"t",
"*",
"Task",
")",
"Fail",
"(",
")",
"error",
"{",
"return",
"t",
".",
"guardResolution",
"(",
"func",
"(",
")",
"error",
"{",
"return",
"t",
".",
"lifecycle",
".",
"Abandon",
"(",
"t",
")",
"\n",
"}",
")",
"\n",
"}"
] | // Fail signals the lifecycle that work on this task has failed, causing
// it to return the task to the main processing queue to be retried. | [
"Fail",
"signals",
"the",
"lifecycle",
"that",
"work",
"on",
"this",
"task",
"has",
"failed",
"causing",
"it",
"to",
"return",
"the",
"task",
"to",
"the",
"main",
"processing",
"queue",
"to",
"be",
"retried",
"."
] | a5663a71d6be64b703bd3dccb819ba06f3f25a52 | https://github.com/mixer/redutil/blob/a5663a71d6be64b703bd3dccb819ba06f3f25a52/worker/task.go#L53-L57 |
15,158 | mixer/redutil | worker/task.go | IsResolved | func (t *Task) IsResolved() bool {
t.resolvedMu.Lock()
defer t.resolvedMu.Unlock()
return t.resolved
} | go | func (t *Task) IsResolved() bool {
t.resolvedMu.Lock()
defer t.resolvedMu.Unlock()
return t.resolved
} | [
"func",
"(",
"t",
"*",
"Task",
")",
"IsResolved",
"(",
")",
"bool",
"{",
"t",
".",
"resolvedMu",
".",
"Lock",
"(",
")",
"\n",
"defer",
"t",
".",
"resolvedMu",
".",
"Unlock",
"(",
")",
"\n\n",
"return",
"t",
".",
"resolved",
"\n",
"}"
] | // IsResolved returns true if the task has already been marked as having
// succeeded or failed. | [
"IsResolved",
"returns",
"true",
"if",
"the",
"task",
"has",
"already",
"been",
"marked",
"as",
"having",
"succeeded",
"or",
"failed",
"."
] | a5663a71d6be64b703bd3dccb819ba06f3f25a52 | https://github.com/mixer/redutil/blob/a5663a71d6be64b703bd3dccb819ba06f3f25a52/worker/task.go#L61-L66 |
15,159 | mixer/redutil | worker/task.go | guardResolution | func (t *Task) guardResolution(fn func() error) error {
t.resolvedMu.Lock()
defer t.resolvedMu.Unlock()
if t.resolved {
return ErrAlreadyResolved
}
err := fn()
if err == nil {
t.resolved = true
}
return err
} | go | func (t *Task) guardResolution(fn func() error) error {
t.resolvedMu.Lock()
defer t.resolvedMu.Unlock()
if t.resolved {
return ErrAlreadyResolved
}
err := fn()
if err == nil {
t.resolved = true
}
return err
} | [
"func",
"(",
"t",
"*",
"Task",
")",
"guardResolution",
"(",
"fn",
"func",
"(",
")",
"error",
")",
"error",
"{",
"t",
".",
"resolvedMu",
".",
"Lock",
"(",
")",
"\n",
"defer",
"t",
".",
"resolvedMu",
".",
"Unlock",
"(",
")",
"\n",
"if",
"t",
".",
... | // guardResolution runs the inner fn only if the task is not already resolved,
// returning ErrAlreadyResolved if that's not the case. If the inner function
// returns no error, the task will subsequently be marked as resolved. | [
"guardResolution",
"runs",
"the",
"inner",
"fn",
"only",
"if",
"the",
"task",
"is",
"not",
"already",
"resolved",
"returning",
"ErrAlreadyResolved",
"if",
"that",
"s",
"not",
"the",
"case",
".",
"If",
"the",
"inner",
"function",
"returns",
"no",
"error",
"th... | a5663a71d6be64b703bd3dccb819ba06f3f25a52 | https://github.com/mixer/redutil/blob/a5663a71d6be64b703bd3dccb819ba06f3f25a52/worker/task.go#L82-L95 |
15,160 | mixer/redutil | heartbeat/hash_expiry_strategy.go | Touch | func (s HashExpireyStrategy) Touch(location, ID string, pool *redis.Pool) error {
now := time.Now().UTC().Format(DefaultTimeFormat)
cnx := pool.Get()
defer cnx.Close()
if _, err := cnx.Do("HSET", location, ID, now); err != nil {
return err
}
return nil
} | go | func (s HashExpireyStrategy) Touch(location, ID string, pool *redis.Pool) error {
now := time.Now().UTC().Format(DefaultTimeFormat)
cnx := pool.Get()
defer cnx.Close()
if _, err := cnx.Do("HSET", location, ID, now); err != nil {
return err
}
return nil
} | [
"func",
"(",
"s",
"HashExpireyStrategy",
")",
"Touch",
"(",
"location",
",",
"ID",
"string",
",",
"pool",
"*",
"redis",
".",
"Pool",
")",
"error",
"{",
"now",
":=",
"time",
".",
"Now",
"(",
")",
".",
"UTC",
"(",
")",
".",
"Format",
"(",
"DefaultTim... | // Touch implements the `func Touch` defined in the Strategy interface. It
// assumes a HASH type is used in Redis to map the IDs of various Hearts to the
// last time that they were updated.
//
// It uses the Heart's `Location` and `ID` fields respectively to determine
// where to both place, and name the hash as well as the items within it.
//
// Times are marshalled using the `const DefaultTimeFormat` which stores times
// in the ISO8601 format. | [
"Touch",
"implements",
"the",
"func",
"Touch",
"defined",
"in",
"the",
"Strategy",
"interface",
".",
"It",
"assumes",
"a",
"HASH",
"type",
"is",
"used",
"in",
"Redis",
"to",
"map",
"the",
"IDs",
"of",
"various",
"Hearts",
"to",
"the",
"last",
"time",
"th... | a5663a71d6be64b703bd3dccb819ba06f3f25a52 | https://github.com/mixer/redutil/blob/a5663a71d6be64b703bd3dccb819ba06f3f25a52/heartbeat/hash_expiry_strategy.go#L35-L46 |
15,161 | mixer/redutil | heartbeat/hash_expiry_strategy.go | Purge | func (s HashExpireyStrategy) Purge(location, ID string, pool *redis.Pool) error {
cnx := pool.Get()
defer cnx.Close()
if _, err := cnx.Do("HDEL", location, ID); err != nil {
return err
}
return nil
} | go | func (s HashExpireyStrategy) Purge(location, ID string, pool *redis.Pool) error {
cnx := pool.Get()
defer cnx.Close()
if _, err := cnx.Do("HDEL", location, ID); err != nil {
return err
}
return nil
} | [
"func",
"(",
"s",
"HashExpireyStrategy",
")",
"Purge",
"(",
"location",
",",
"ID",
"string",
",",
"pool",
"*",
"redis",
".",
"Pool",
")",
"error",
"{",
"cnx",
":=",
"pool",
".",
"Get",
"(",
")",
"\n",
"defer",
"cnx",
".",
"Close",
"(",
")",
"\n\n",... | // Purge implements the `func Purge` defined in the Strategy interface. It
// assumes a HASH type is used in Redis to map the IDs of various Hearts,
// and removes the record for the specified ID from the hash. | [
"Purge",
"implements",
"the",
"func",
"Purge",
"defined",
"in",
"the",
"Strategy",
"interface",
".",
"It",
"assumes",
"a",
"HASH",
"type",
"is",
"used",
"in",
"Redis",
"to",
"map",
"the",
"IDs",
"of",
"various",
"Hearts",
"and",
"removes",
"the",
"record",... | a5663a71d6be64b703bd3dccb819ba06f3f25a52 | https://github.com/mixer/redutil/blob/a5663a71d6be64b703bd3dccb819ba06f3f25a52/heartbeat/hash_expiry_strategy.go#L51-L60 |
15,162 | mixer/redutil | heartbeat/hash_expiry_strategy.go | Expired | func (s HashExpireyStrategy) Expired(location string,
pool *redis.Pool) (expired []string, err error) {
now := time.Now().UTC()
cnx := pool.Get()
defer cnx.Close()
reply, err := redis.StringMap(cnx.Do("HGETALL", location))
if err != nil {
return
}
for id, tick := range reply {
lastUpdate, err := time.Parse(DefaultTimeFormat, tick)
if err != nil {
continue
} else if lastUpdate.Add(s.MaxAge).Before(now) {
expired = append(expired, id)
}
}
return
} | go | func (s HashExpireyStrategy) Expired(location string,
pool *redis.Pool) (expired []string, err error) {
now := time.Now().UTC()
cnx := pool.Get()
defer cnx.Close()
reply, err := redis.StringMap(cnx.Do("HGETALL", location))
if err != nil {
return
}
for id, tick := range reply {
lastUpdate, err := time.Parse(DefaultTimeFormat, tick)
if err != nil {
continue
} else if lastUpdate.Add(s.MaxAge).Before(now) {
expired = append(expired, id)
}
}
return
} | [
"func",
"(",
"s",
"HashExpireyStrategy",
")",
"Expired",
"(",
"location",
"string",
",",
"pool",
"*",
"redis",
".",
"Pool",
")",
"(",
"expired",
"[",
"]",
"string",
",",
"err",
"error",
")",
"{",
"now",
":=",
"time",
".",
"Now",
"(",
")",
".",
"UTC... | // Expired implements the `func Expired` defined on the Strategy interface. It
// scans iteratively over the Heart's `location` field to look for items that
// have expired. An item is marked as expired iff the last update time happened
// before the instant of the maxAge subtracted from the current time. | [
"Expired",
"implements",
"the",
"func",
"Expired",
"defined",
"on",
"the",
"Strategy",
"interface",
".",
"It",
"scans",
"iteratively",
"over",
"the",
"Heart",
"s",
"location",
"field",
"to",
"look",
"for",
"items",
"that",
"have",
"expired",
".",
"An",
"item... | a5663a71d6be64b703bd3dccb819ba06f3f25a52 | https://github.com/mixer/redutil/blob/a5663a71d6be64b703bd3dccb819ba06f3f25a52/heartbeat/hash_expiry_strategy.go#L66-L90 |
15,163 | mixer/redutil | pubsub2/pumps.go | newReadPump | func newReadPump(cnx redis.Conn) *readPump {
return &readPump{
cnx: cnx,
data: make(chan interface{}),
errs: make(chan error),
closer: make(chan struct{}),
}
} | go | func newReadPump(cnx redis.Conn) *readPump {
return &readPump{
cnx: cnx,
data: make(chan interface{}),
errs: make(chan error),
closer: make(chan struct{}),
}
} | [
"func",
"newReadPump",
"(",
"cnx",
"redis",
".",
"Conn",
")",
"*",
"readPump",
"{",
"return",
"&",
"readPump",
"{",
"cnx",
":",
"cnx",
",",
"data",
":",
"make",
"(",
"chan",
"interface",
"{",
"}",
")",
",",
"errs",
":",
"make",
"(",
"chan",
"error"... | // newReadPump creates a new pump that operates on the single Redis connection. | [
"newReadPump",
"creates",
"a",
"new",
"pump",
"that",
"operates",
"on",
"the",
"single",
"Redis",
"connection",
"."
] | a5663a71d6be64b703bd3dccb819ba06f3f25a52 | https://github.com/mixer/redutil/blob/a5663a71d6be64b703bd3dccb819ba06f3f25a52/pubsub2/pumps.go#L21-L28 |
15,164 | mixer/redutil | pubsub2/pumps.go | Work | func (r *readPump) Work() {
cnx := redis.PubSubConn{Conn: r.cnx}
defer close(r.closer)
for {
msg := cnx.Receive()
if err, isErr := msg.(error); isErr && shouldNotifyUser(err) {
select {
case r.errs <- err:
case <-r.closer:
return
}
} else if !isErr {
select {
case r.data <- msg:
case <-r.closer:
return
}
}
}
} | go | func (r *readPump) Work() {
cnx := redis.PubSubConn{Conn: r.cnx}
defer close(r.closer)
for {
msg := cnx.Receive()
if err, isErr := msg.(error); isErr && shouldNotifyUser(err) {
select {
case r.errs <- err:
case <-r.closer:
return
}
} else if !isErr {
select {
case r.data <- msg:
case <-r.closer:
return
}
}
}
} | [
"func",
"(",
"r",
"*",
"readPump",
")",
"Work",
"(",
")",
"{",
"cnx",
":=",
"redis",
".",
"PubSubConn",
"{",
"Conn",
":",
"r",
".",
"cnx",
"}",
"\n",
"defer",
"close",
"(",
"r",
".",
"closer",
")",
"\n\n",
"for",
"{",
"msg",
":=",
"cnx",
".",
... | // Work starts reading from the connection and blocks until it is closed. | [
"Work",
"starts",
"reading",
"from",
"the",
"connection",
"and",
"blocks",
"until",
"it",
"is",
"closed",
"."
] | a5663a71d6be64b703bd3dccb819ba06f3f25a52 | https://github.com/mixer/redutil/blob/a5663a71d6be64b703bd3dccb819ba06f3f25a52/pubsub2/pumps.go#L31-L52 |
15,165 | mixer/redutil | pubsub2/pumps.go | newWritePump | func newWritePump(cnx redis.Conn) *writePump {
return &writePump{
cnx: cnx,
data: make(chan command),
errs: make(chan error),
closer: make(chan struct{}),
}
} | go | func newWritePump(cnx redis.Conn) *writePump {
return &writePump{
cnx: cnx,
data: make(chan command),
errs: make(chan error),
closer: make(chan struct{}),
}
} | [
"func",
"newWritePump",
"(",
"cnx",
"redis",
".",
"Conn",
")",
"*",
"writePump",
"{",
"return",
"&",
"writePump",
"{",
"cnx",
":",
"cnx",
",",
"data",
":",
"make",
"(",
"chan",
"command",
")",
",",
"errs",
":",
"make",
"(",
"chan",
"error",
")",
",... | // newWritePump creates a new pump that operates on the single Redis connection. | [
"newWritePump",
"creates",
"a",
"new",
"pump",
"that",
"operates",
"on",
"the",
"single",
"Redis",
"connection",
"."
] | a5663a71d6be64b703bd3dccb819ba06f3f25a52 | https://github.com/mixer/redutil/blob/a5663a71d6be64b703bd3dccb819ba06f3f25a52/pubsub2/pumps.go#L79-L86 |
15,166 | mixer/redutil | pubsub2/pumps.go | Work | func (r *writePump) Work() {
defer close(r.closer)
for {
select {
case data := <-r.data:
r.cnx.Send(data.command, data.channel)
if err := r.cnx.Flush(); err != nil {
select {
case r.errs <- err:
case <-r.closer:
return
}
}
case <-r.closer:
return
}
}
} | go | func (r *writePump) Work() {
defer close(r.closer)
for {
select {
case data := <-r.data:
r.cnx.Send(data.command, data.channel)
if err := r.cnx.Flush(); err != nil {
select {
case r.errs <- err:
case <-r.closer:
return
}
}
case <-r.closer:
return
}
}
} | [
"func",
"(",
"r",
"*",
"writePump",
")",
"Work",
"(",
")",
"{",
"defer",
"close",
"(",
"r",
".",
"closer",
")",
"\n\n",
"for",
"{",
"select",
"{",
"case",
"data",
":=",
"<-",
"r",
".",
"data",
":",
"r",
".",
"cnx",
".",
"Send",
"(",
"data",
"... | // Work starts writing to the connection and blocks until it is closed. | [
"Work",
"starts",
"writing",
"to",
"the",
"connection",
"and",
"blocks",
"until",
"it",
"is",
"closed",
"."
] | a5663a71d6be64b703bd3dccb819ba06f3f25a52 | https://github.com/mixer/redutil/blob/a5663a71d6be64b703bd3dccb819ba06f3f25a52/pubsub2/pumps.go#L89-L107 |
15,167 | mixer/redutil | pubsub2/pumps.go | shouldNotifyUser | func shouldNotifyUser(err error) bool {
if nerr, ok := err.(net.Error); ok && (nerr.Timeout() || nerr.Temporary()) {
return false
}
return true
} | go | func shouldNotifyUser(err error) bool {
if nerr, ok := err.(net.Error); ok && (nerr.Timeout() || nerr.Temporary()) {
return false
}
return true
} | [
"func",
"shouldNotifyUser",
"(",
"err",
"error",
")",
"bool",
"{",
"if",
"nerr",
",",
"ok",
":=",
"err",
".",
"(",
"net",
".",
"Error",
")",
";",
"ok",
"&&",
"(",
"nerr",
".",
"Timeout",
"(",
")",
"||",
"nerr",
".",
"Temporary",
"(",
")",
")",
... | // shouldNotifyUser return true if the user should be notified of the
// given error; if it's not a temporary network error or a timeout. | [
"shouldNotifyUser",
"return",
"true",
"if",
"the",
"user",
"should",
"be",
"notified",
"of",
"the",
"given",
"error",
";",
"if",
"it",
"s",
"not",
"a",
"temporary",
"network",
"error",
"or",
"a",
"timeout",
"."
] | a5663a71d6be64b703bd3dccb819ba06f3f25a52 | https://github.com/mixer/redutil/blob/a5663a71d6be64b703bd3dccb819ba06f3f25a52/pubsub2/pumps.go#L120-L126 |
15,168 | mixer/redutil | conn/conn.go | NewWithActiveLimit | func NewWithActiveLimit(param ConnectionParam, maxIdle int, maxActive int) (*redis.Pool, ReconnectPolicy) {
if param.Policy == nil {
param.Policy = &LogReconnectPolicy{Base: 10, Factor: time.Millisecond}
}
return &redis.Pool{Dial: connect(param), MaxIdle: maxIdle, MaxActive: maxActive}, param.Policy
} | go | func NewWithActiveLimit(param ConnectionParam, maxIdle int, maxActive int) (*redis.Pool, ReconnectPolicy) {
if param.Policy == nil {
param.Policy = &LogReconnectPolicy{Base: 10, Factor: time.Millisecond}
}
return &redis.Pool{Dial: connect(param), MaxIdle: maxIdle, MaxActive: maxActive}, param.Policy
} | [
"func",
"NewWithActiveLimit",
"(",
"param",
"ConnectionParam",
",",
"maxIdle",
"int",
",",
"maxActive",
"int",
")",
"(",
"*",
"redis",
".",
"Pool",
",",
"ReconnectPolicy",
")",
"{",
"if",
"param",
".",
"Policy",
"==",
"nil",
"{",
"param",
".",
"Policy",
... | // NewWithActiveLimit makes and returns a pointer to a new Connector instance. It sets some
// defaults on the ConnectionParam object, such as the policy, which defaults to
// a LogReconnectPolicy with a base of 10ms. A call to this function does not
// produce a connection. | [
"NewWithActiveLimit",
"makes",
"and",
"returns",
"a",
"pointer",
"to",
"a",
"new",
"Connector",
"instance",
".",
"It",
"sets",
"some",
"defaults",
"on",
"the",
"ConnectionParam",
"object",
"such",
"as",
"the",
"policy",
"which",
"defaults",
"to",
"a",
"LogReco... | a5663a71d6be64b703bd3dccb819ba06f3f25a52 | https://github.com/mixer/redutil/blob/a5663a71d6be64b703bd3dccb819ba06f3f25a52/conn/conn.go#L28-L34 |
15,169 | mixer/redutil | worker/janitor.go | runCleaning | func (j *janitorRunner) runCleaning() {
dead, err := j.detector.Detect()
if err != nil {
j.errs <- err
return
}
var wg sync.WaitGroup
wg.Add(len(dead))
for _, worker := range dead {
go func(worker string) {
defer wg.Done()
err := j.handleDeath(worker)
if err != nil && err != redsync.ErrFailed {
j.errs <- err
}
}(worker)
}
wg.Wait()
} | go | func (j *janitorRunner) runCleaning() {
dead, err := j.detector.Detect()
if err != nil {
j.errs <- err
return
}
var wg sync.WaitGroup
wg.Add(len(dead))
for _, worker := range dead {
go func(worker string) {
defer wg.Done()
err := j.handleDeath(worker)
if err != nil && err != redsync.ErrFailed {
j.errs <- err
}
}(worker)
}
wg.Wait()
} | [
"func",
"(",
"j",
"*",
"janitorRunner",
")",
"runCleaning",
"(",
")",
"{",
"dead",
",",
"err",
":=",
"j",
".",
"detector",
".",
"Detect",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"j",
".",
"errs",
"<-",
"err",
"\n",
"return",
"\n",
"}",
"... | // Detects expired records and starts tasks to move any of their abandoned
// tasks back to the main queue. | [
"Detects",
"expired",
"records",
"and",
"starts",
"tasks",
"to",
"move",
"any",
"of",
"their",
"abandoned",
"tasks",
"back",
"to",
"the",
"main",
"queue",
"."
] | a5663a71d6be64b703bd3dccb819ba06f3f25a52 | https://github.com/mixer/redutil/blob/a5663a71d6be64b703bd3dccb819ba06f3f25a52/worker/janitor.go#L110-L132 |
15,170 | mixer/redutil | worker/janitor.go | getLock | func (j *janitorRunner) getLock(worker string) (*redsync.Mutex, error) {
mu, err := redsync.NewMutexWithPool("redutil:lock:"+worker, []*redis.Pool{j.pool})
if err != nil {
return nil, err
}
return mu, mu.Lock()
} | go | func (j *janitorRunner) getLock(worker string) (*redsync.Mutex, error) {
mu, err := redsync.NewMutexWithPool("redutil:lock:"+worker, []*redis.Pool{j.pool})
if err != nil {
return nil, err
}
return mu, mu.Lock()
} | [
"func",
"(",
"j",
"*",
"janitorRunner",
")",
"getLock",
"(",
"worker",
"string",
")",
"(",
"*",
"redsync",
".",
"Mutex",
",",
"error",
")",
"{",
"mu",
",",
"err",
":=",
"redsync",
".",
"NewMutexWithPool",
"(",
"\"",
"\"",
"+",
"worker",
",",
"[",
"... | // Creates a mutex and attempts to acquire a redlock to dispose of the worker. | [
"Creates",
"a",
"mutex",
"and",
"attempts",
"to",
"acquire",
"a",
"redlock",
"to",
"dispose",
"of",
"the",
"worker",
"."
] | a5663a71d6be64b703bd3dccb819ba06f3f25a52 | https://github.com/mixer/redutil/blob/a5663a71d6be64b703bd3dccb819ba06f3f25a52/worker/janitor.go#L135-L142 |
15,171 | mixer/redutil | worker/janitor.go | handleDeath | func (j *janitorRunner) handleDeath(worker string) error {
mu, err := j.getLock(worker)
if err != nil {
return err
}
defer mu.Unlock()
cnx := j.pool.Get()
defer cnx.Close()
if err := j.janitor.OnPreConcat(cnx, worker); err != nil {
return err
}
_, err = j.availableTasks.Concat(
getWorkingQueueName(j.availableTasks.Source(), worker))
if err != nil && err != redis.ErrNil {
return err
}
j.detector.Purge(worker)
return j.janitor.OnPostConcat(cnx, worker)
} | go | func (j *janitorRunner) handleDeath(worker string) error {
mu, err := j.getLock(worker)
if err != nil {
return err
}
defer mu.Unlock()
cnx := j.pool.Get()
defer cnx.Close()
if err := j.janitor.OnPreConcat(cnx, worker); err != nil {
return err
}
_, err = j.availableTasks.Concat(
getWorkingQueueName(j.availableTasks.Source(), worker))
if err != nil && err != redis.ErrNil {
return err
}
j.detector.Purge(worker)
return j.janitor.OnPostConcat(cnx, worker)
} | [
"func",
"(",
"j",
"*",
"janitorRunner",
")",
"handleDeath",
"(",
"worker",
"string",
")",
"error",
"{",
"mu",
",",
"err",
":=",
"j",
".",
"getLock",
"(",
"worker",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"defer",... | // Processes a dead worker, moving its queue back to the main queue and
// calling the disposer function if we get a lock on it. | [
"Processes",
"a",
"dead",
"worker",
"moving",
"its",
"queue",
"back",
"to",
"the",
"main",
"queue",
"and",
"calling",
"the",
"disposer",
"function",
"if",
"we",
"get",
"a",
"lock",
"on",
"it",
"."
] | a5663a71d6be64b703bd3dccb819ba06f3f25a52 | https://github.com/mixer/redutil/blob/a5663a71d6be64b703bd3dccb819ba06f3f25a52/worker/janitor.go#L146-L168 |
15,172 | mixer/redutil | worker/default_worker.go | SetJanitor | func (w *DefaultWorker) SetJanitor(janitor Janitor) {
w.ensureUnstarted()
w.janitor = janitor
} | go | func (w *DefaultWorker) SetJanitor(janitor Janitor) {
w.ensureUnstarted()
w.janitor = janitor
} | [
"func",
"(",
"w",
"*",
"DefaultWorker",
")",
"SetJanitor",
"(",
"janitor",
"Janitor",
")",
"{",
"w",
".",
"ensureUnstarted",
"(",
")",
"\n",
"w",
".",
"janitor",
"=",
"janitor",
"\n",
"}"
] | // Sets the Janitor interface used to dispose of old workers. This is optional;
// if you do not need to hook in extra functionality, you don't need to
// provide a janitor. | [
"Sets",
"the",
"Janitor",
"interface",
"used",
"to",
"dispose",
"of",
"old",
"workers",
".",
"This",
"is",
"optional",
";",
"if",
"you",
"do",
"not",
"need",
"to",
"hook",
"in",
"extra",
"functionality",
"you",
"don",
"t",
"need",
"to",
"provide",
"a",
... | a5663a71d6be64b703bd3dccb819ba06f3f25a52 | https://github.com/mixer/redutil/blob/a5663a71d6be64b703bd3dccb819ba06f3f25a52/worker/default_worker.go#L109-L112 |
15,173 | mixer/redutil | worker/default_worker.go | Start | func (w *DefaultWorker) Start() (<-chan *Task, <-chan error) {
w.smu.Lock()
defer w.smu.Unlock()
w.state = open
w.lifecycle.SetQueues(w.availableTasks, w.workingTasks)
w.janitorRunner = newJanitorRunner(w.pool, w.detector, w.janitor, w.availableTasks)
errs1 := w.janitorRunner.Start()
tasks, errs2 := w.lifecycle.Listen()
return tasks, concatErrs(errs1, errs2)
} | go | func (w *DefaultWorker) Start() (<-chan *Task, <-chan error) {
w.smu.Lock()
defer w.smu.Unlock()
w.state = open
w.lifecycle.SetQueues(w.availableTasks, w.workingTasks)
w.janitorRunner = newJanitorRunner(w.pool, w.detector, w.janitor, w.availableTasks)
errs1 := w.janitorRunner.Start()
tasks, errs2 := w.lifecycle.Listen()
return tasks, concatErrs(errs1, errs2)
} | [
"func",
"(",
"w",
"*",
"DefaultWorker",
")",
"Start",
"(",
")",
"(",
"<-",
"chan",
"*",
"Task",
",",
"<-",
"chan",
"error",
")",
"{",
"w",
".",
"smu",
".",
"Lock",
"(",
")",
"\n",
"defer",
"w",
".",
"smu",
".",
"Unlock",
"(",
")",
"\n\n",
"w"... | // Start signals the worker to begin receiving tasks from the main queue. | [
"Start",
"signals",
"the",
"worker",
"to",
"begin",
"receiving",
"tasks",
"from",
"the",
"main",
"queue",
"."
] | a5663a71d6be64b703bd3dccb819ba06f3f25a52 | https://github.com/mixer/redutil/blob/a5663a71d6be64b703bd3dccb819ba06f3f25a52/worker/default_worker.go#L124-L136 |
15,174 | mixer/redutil | worker/default_worker.go | Halt | func (w *DefaultWorker) Halt() {
w.startClosing(func() {
w.state = halting
w.lifecycle.AbandonAll()
})
} | go | func (w *DefaultWorker) Halt() {
w.startClosing(func() {
w.state = halting
w.lifecycle.AbandonAll()
})
} | [
"func",
"(",
"w",
"*",
"DefaultWorker",
")",
"Halt",
"(",
")",
"{",
"w",
".",
"startClosing",
"(",
"func",
"(",
")",
"{",
"w",
".",
"state",
"=",
"halting",
"\n",
"w",
".",
"lifecycle",
".",
"AbandonAll",
"(",
")",
"\n",
"}",
")",
"\n",
"}"
] | // Halt stops the heartbeat and queue polling goroutines immediately and cancels
// all tasks, marking them as FAILED before returning. | [
"Halt",
"stops",
"the",
"heartbeat",
"and",
"queue",
"polling",
"goroutines",
"immediately",
"and",
"cancels",
"all",
"tasks",
"marking",
"them",
"as",
"FAILED",
"before",
"returning",
"."
] | a5663a71d6be64b703bd3dccb819ba06f3f25a52 | https://github.com/mixer/redutil/blob/a5663a71d6be64b703bd3dccb819ba06f3f25a52/worker/default_worker.go#L148-L153 |
15,175 | mixer/redutil | worker/default_worker.go | startClosing | func (w *DefaultWorker) startClosing(fn func()) {
w.smu.Lock()
defer w.smu.Unlock()
if w.state != open {
return
}
w.lifecycle.StopListening()
w.heart.Close()
w.janitorRunner.Close()
fn()
w.lifecycle.Await()
w.state = closed
} | go | func (w *DefaultWorker) startClosing(fn func()) {
w.smu.Lock()
defer w.smu.Unlock()
if w.state != open {
return
}
w.lifecycle.StopListening()
w.heart.Close()
w.janitorRunner.Close()
fn()
w.lifecycle.Await()
w.state = closed
} | [
"func",
"(",
"w",
"*",
"DefaultWorker",
")",
"startClosing",
"(",
"fn",
"func",
"(",
")",
")",
"{",
"w",
".",
"smu",
".",
"Lock",
"(",
")",
"\n",
"defer",
"w",
".",
"smu",
".",
"Unlock",
"(",
")",
"\n",
"if",
"w",
".",
"state",
"!=",
"open",
... | // Starts closing the worker if it was not already closed. Invokes the passed
// function to help in the teardown, and blocks until all tasks are done. | [
"Starts",
"closing",
"the",
"worker",
"if",
"it",
"was",
"not",
"already",
"closed",
".",
"Invokes",
"the",
"passed",
"function",
"to",
"help",
"in",
"the",
"teardown",
"and",
"blocks",
"until",
"all",
"tasks",
"are",
"done",
"."
] | a5663a71d6be64b703bd3dccb819ba06f3f25a52 | https://github.com/mixer/redutil/blob/a5663a71d6be64b703bd3dccb819ba06f3f25a52/worker/default_worker.go#L157-L173 |
15,176 | mixer/redutil | heartbeat/simple_detector.go | NewDetector | func NewDetector(location string, pool *redis.Pool, strategy Strategy) Detector {
return SimpleDetector{
location: location,
pool: pool,
strategy: strategy,
}
} | go | func NewDetector(location string, pool *redis.Pool, strategy Strategy) Detector {
return SimpleDetector{
location: location,
pool: pool,
strategy: strategy,
}
} | [
"func",
"NewDetector",
"(",
"location",
"string",
",",
"pool",
"*",
"redis",
".",
"Pool",
",",
"strategy",
"Strategy",
")",
"Detector",
"{",
"return",
"SimpleDetector",
"{",
"location",
":",
"location",
",",
"pool",
":",
"pool",
",",
"strategy",
":",
"stra... | // NewDetector initializes and returns a new SimpleDetector instance with the
// given parameters. | [
"NewDetector",
"initializes",
"and",
"returns",
"a",
"new",
"SimpleDetector",
"instance",
"with",
"the",
"given",
"parameters",
"."
] | a5663a71d6be64b703bd3dccb819ba06f3f25a52 | https://github.com/mixer/redutil/blob/a5663a71d6be64b703bd3dccb819ba06f3f25a52/heartbeat/simple_detector.go#L15-L21 |
15,177 | mixer/redutil | heartbeat/simple_detector.go | Detect | func (d SimpleDetector) Detect() (expired []string, err error) {
return d.strategy.Expired(d.location, d.pool)
} | go | func (d SimpleDetector) Detect() (expired []string, err error) {
return d.strategy.Expired(d.location, d.pool)
} | [
"func",
"(",
"d",
"SimpleDetector",
")",
"Detect",
"(",
")",
"(",
"expired",
"[",
"]",
"string",
",",
"err",
"error",
")",
"{",
"return",
"d",
".",
"strategy",
".",
"Expired",
"(",
"d",
".",
"location",
",",
"d",
".",
"pool",
")",
"\n",
"}"
] | // Detect implements the `func Detect` on the `type Detector interface`. This
// implementation simply delegates into the provided Strategy. | [
"Detect",
"implements",
"the",
"func",
"Detect",
"on",
"the",
"type",
"Detector",
"interface",
".",
"This",
"implementation",
"simply",
"delegates",
"into",
"the",
"provided",
"Strategy",
"."
] | a5663a71d6be64b703bd3dccb819ba06f3f25a52 | https://github.com/mixer/redutil/blob/a5663a71d6be64b703bd3dccb819ba06f3f25a52/heartbeat/simple_detector.go#L32-L34 |
15,178 | mixer/redutil | heartbeat/simple_detector.go | Purge | func (d SimpleDetector) Purge(id string) (err error) {
return d.strategy.Purge(d.location, id, d.pool)
} | go | func (d SimpleDetector) Purge(id string) (err error) {
return d.strategy.Purge(d.location, id, d.pool)
} | [
"func",
"(",
"d",
"SimpleDetector",
")",
"Purge",
"(",
"id",
"string",
")",
"(",
"err",
"error",
")",
"{",
"return",
"d",
".",
"strategy",
".",
"Purge",
"(",
"d",
".",
"location",
",",
"id",
",",
"d",
".",
"pool",
")",
"\n",
"}"
] | // Purge implements the `func Purge` on the `type Detector interface`. This
// implementation simply delegates into the provided Strategy. | [
"Purge",
"implements",
"the",
"func",
"Purge",
"on",
"the",
"type",
"Detector",
"interface",
".",
"This",
"implementation",
"simply",
"delegates",
"into",
"the",
"provided",
"Strategy",
"."
] | a5663a71d6be64b703bd3dccb819ba06f3f25a52 | https://github.com/mixer/redutil/blob/a5663a71d6be64b703bd3dccb819ba06f3f25a52/heartbeat/simple_detector.go#L38-L40 |
15,179 | mixer/redutil | queue/lifo_processor.go | Push | func (l *lifoProcessor) Push(cnx redis.Conn, src string, payload []byte) (err error) {
_, err = cnx.Do("RPUSH", src, payload)
return
} | go | func (l *lifoProcessor) Push(cnx redis.Conn, src string, payload []byte) (err error) {
_, err = cnx.Do("RPUSH", src, payload)
return
} | [
"func",
"(",
"l",
"*",
"lifoProcessor",
")",
"Push",
"(",
"cnx",
"redis",
".",
"Conn",
",",
"src",
"string",
",",
"payload",
"[",
"]",
"byte",
")",
"(",
"err",
"error",
")",
"{",
"_",
",",
"err",
"=",
"cnx",
".",
"Do",
"(",
"\"",
"\"",
",",
"... | // Push implements the `func Push` from `Processor`. It pushes the right-side
// of the Redis structure using RPUSH, and returns any errors encountered while
// runnning that command. | [
"Push",
"implements",
"the",
"func",
"Push",
"from",
"Processor",
".",
"It",
"pushes",
"the",
"right",
"-",
"side",
"of",
"the",
"Redis",
"structure",
"using",
"RPUSH",
"and",
"returns",
"any",
"errors",
"encountered",
"while",
"runnning",
"that",
"command",
... | a5663a71d6be64b703bd3dccb819ba06f3f25a52 | https://github.com/mixer/redutil/blob/a5663a71d6be64b703bd3dccb819ba06f3f25a52/queue/lifo_processor.go#L17-L20 |
15,180 | cybozu-go/well | log.go | FieldsFromContext | func FieldsFromContext(ctx context.Context) map[string]interface{} {
m := make(map[string]interface{})
v := ctx.Value(RequestIDContextKey)
if v != nil {
m[log.FnRequestID] = v.(string)
}
return m
} | go | func FieldsFromContext(ctx context.Context) map[string]interface{} {
m := make(map[string]interface{})
v := ctx.Value(RequestIDContextKey)
if v != nil {
m[log.FnRequestID] = v.(string)
}
return m
} | [
"func",
"FieldsFromContext",
"(",
"ctx",
"context",
".",
"Context",
")",
"map",
"[",
"string",
"]",
"interface",
"{",
"}",
"{",
"m",
":=",
"make",
"(",
"map",
"[",
"string",
"]",
"interface",
"{",
"}",
")",
"\n",
"v",
":=",
"ctx",
".",
"Value",
"("... | // FieldsFromContext returns a map of fields containing
// context information. Currently, request ID field is
// included, if any. | [
"FieldsFromContext",
"returns",
"a",
"map",
"of",
"fields",
"containing",
"context",
"information",
".",
"Currently",
"request",
"ID",
"field",
"is",
"included",
"if",
"any",
"."
] | cdbf0b975515ab2a1673c52308b0dd1683ebf1e0 | https://github.com/cybozu-go/well/blob/cdbf0b975515ab2a1673c52308b0dd1683ebf1e0/log.go#L128-L135 |
15,181 | cybozu-go/well | idgen.go | NewIDGenerator | func NewIDGenerator() *IDGenerator {
g := new(IDGenerator)
_, err := rand.Read(g.seed[:])
if err != nil {
panic(err)
}
return g
} | go | func NewIDGenerator() *IDGenerator {
g := new(IDGenerator)
_, err := rand.Read(g.seed[:])
if err != nil {
panic(err)
}
return g
} | [
"func",
"NewIDGenerator",
"(",
")",
"*",
"IDGenerator",
"{",
"g",
":=",
"new",
"(",
"IDGenerator",
")",
"\n",
"_",
",",
"err",
":=",
"rand",
".",
"Read",
"(",
"g",
".",
"seed",
"[",
":",
"]",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"panic",
"... | // NewIDGenerator creates a new IDGenerator. | [
"NewIDGenerator",
"creates",
"a",
"new",
"IDGenerator",
"."
] | cdbf0b975515ab2a1673c52308b0dd1683ebf1e0 | https://github.com/cybozu-go/well/blob/cdbf0b975515ab2a1673c52308b0dd1683ebf1e0/idgen.go#L39-L46 |
15,182 | cybozu-go/well | idgen.go | Generate | func (g *IDGenerator) Generate() string {
var nb [8]byte
n := atomic.AddUint64(&g.n, 1)
binary.LittleEndian.PutUint64(nb[:], n)
id := g.seed
for i, b := range nb {
id[i] ^= b
}
var strbuf [36]byte
for i := 0; i < 4; i++ {
strbuf[i*2] = hexData[int(id[i])*2]
strbuf[i*2+1] = hexData[int(id[i])*2+1]
}
strbuf[8] = '-'
for i := 4; i < 6; i++ {
strbuf[i*2+1] = hexData[int(id[i])*2]
strbuf[i*2+2] = hexData[int(id[i])*2+1]
}
strbuf[13] = '-'
for i := 6; i < 8; i++ {
strbuf[i*2+2] = hexData[int(id[i])*2]
strbuf[i*2+3] = hexData[int(id[i])*2+1]
}
strbuf[18] = '-'
for i := 8; i < 10; i++ {
strbuf[i*2+3] = hexData[int(id[i])*2]
strbuf[i*2+4] = hexData[int(id[i])*2+1]
}
strbuf[23] = '-'
for i := 10; i < 16; i++ {
strbuf[i*2+4] = hexData[int(id[i])*2]
strbuf[i*2+5] = hexData[int(id[i])*2+1]
}
return string(strbuf[:])
} | go | func (g *IDGenerator) Generate() string {
var nb [8]byte
n := atomic.AddUint64(&g.n, 1)
binary.LittleEndian.PutUint64(nb[:], n)
id := g.seed
for i, b := range nb {
id[i] ^= b
}
var strbuf [36]byte
for i := 0; i < 4; i++ {
strbuf[i*2] = hexData[int(id[i])*2]
strbuf[i*2+1] = hexData[int(id[i])*2+1]
}
strbuf[8] = '-'
for i := 4; i < 6; i++ {
strbuf[i*2+1] = hexData[int(id[i])*2]
strbuf[i*2+2] = hexData[int(id[i])*2+1]
}
strbuf[13] = '-'
for i := 6; i < 8; i++ {
strbuf[i*2+2] = hexData[int(id[i])*2]
strbuf[i*2+3] = hexData[int(id[i])*2+1]
}
strbuf[18] = '-'
for i := 8; i < 10; i++ {
strbuf[i*2+3] = hexData[int(id[i])*2]
strbuf[i*2+4] = hexData[int(id[i])*2+1]
}
strbuf[23] = '-'
for i := 10; i < 16; i++ {
strbuf[i*2+4] = hexData[int(id[i])*2]
strbuf[i*2+5] = hexData[int(id[i])*2+1]
}
return string(strbuf[:])
} | [
"func",
"(",
"g",
"*",
"IDGenerator",
")",
"Generate",
"(",
")",
"string",
"{",
"var",
"nb",
"[",
"8",
"]",
"byte",
"\n",
"n",
":=",
"atomic",
".",
"AddUint64",
"(",
"&",
"g",
".",
"n",
",",
"1",
")",
"\n",
"binary",
".",
"LittleEndian",
".",
"... | // Generate generates an ID.
// Multiple goroutines can safely call this. | [
"Generate",
"generates",
"an",
"ID",
".",
"Multiple",
"goroutines",
"can",
"safely",
"call",
"this",
"."
] | cdbf0b975515ab2a1673c52308b0dd1683ebf1e0 | https://github.com/cybozu-go/well/blob/cdbf0b975515ab2a1673c52308b0dd1683ebf1e0/idgen.go#L50-L86 |
15,183 | cybozu-go/well | exec.go | UTF8StringFromBytes | func UTF8StringFromBytes(b []byte) string {
if utf8.Valid(b) {
return string(b)
}
// This effectively replaces invalid bytes to \uFFFD (replacement char).
return string(bytes.Runes(b))
} | go | func UTF8StringFromBytes(b []byte) string {
if utf8.Valid(b) {
return string(b)
}
// This effectively replaces invalid bytes to \uFFFD (replacement char).
return string(bytes.Runes(b))
} | [
"func",
"UTF8StringFromBytes",
"(",
"b",
"[",
"]",
"byte",
")",
"string",
"{",
"if",
"utf8",
".",
"Valid",
"(",
"b",
")",
"{",
"return",
"string",
"(",
"b",
")",
"\n",
"}",
"\n\n",
"// This effectively replaces invalid bytes to \\uFFFD (replacement char).",
"ret... | // UTF8StringFromBytes returns a valid UTF-8 string from
// maybe invalid slice of bytes. | [
"UTF8StringFromBytes",
"returns",
"a",
"valid",
"UTF",
"-",
"8",
"string",
"from",
"maybe",
"invalid",
"slice",
"of",
"bytes",
"."
] | cdbf0b975515ab2a1673c52308b0dd1683ebf1e0 | https://github.com/cybozu-go/well/blob/cdbf0b975515ab2a1673c52308b0dd1683ebf1e0/exec.go#L15-L22 |
15,184 | cybozu-go/well | exec.go | CombinedOutput | func (c *LogCmd) CombinedOutput() ([]byte, error) {
st := time.Now()
data, err := c.Cmd.CombinedOutput()
c.log(st, err, nil)
return data, err
} | go | func (c *LogCmd) CombinedOutput() ([]byte, error) {
st := time.Now()
data, err := c.Cmd.CombinedOutput()
c.log(st, err, nil)
return data, err
} | [
"func",
"(",
"c",
"*",
"LogCmd",
")",
"CombinedOutput",
"(",
")",
"(",
"[",
"]",
"byte",
",",
"error",
")",
"{",
"st",
":=",
"time",
".",
"Now",
"(",
")",
"\n",
"data",
",",
"err",
":=",
"c",
".",
"Cmd",
".",
"CombinedOutput",
"(",
")",
"\n",
... | // CombinedOutput overrides exec.Cmd.CombinedOutput to record the result. | [
"CombinedOutput",
"overrides",
"exec",
".",
"Cmd",
".",
"CombinedOutput",
"to",
"record",
"the",
"result",
"."
] | cdbf0b975515ab2a1673c52308b0dd1683ebf1e0 | https://github.com/cybozu-go/well/blob/cdbf0b975515ab2a1673c52308b0dd1683ebf1e0/exec.go#L78-L83 |
15,185 | cybozu-go/well | exec.go | Output | func (c *LogCmd) Output() ([]byte, error) {
st := time.Now()
data, err := c.Cmd.Output()
if err != nil {
ee, ok := err.(*exec.ExitError)
if ok {
c.log(st, err, ee.Stderr)
return data, err
}
}
c.log(st, err, nil)
return data, err
} | go | func (c *LogCmd) Output() ([]byte, error) {
st := time.Now()
data, err := c.Cmd.Output()
if err != nil {
ee, ok := err.(*exec.ExitError)
if ok {
c.log(st, err, ee.Stderr)
return data, err
}
}
c.log(st, err, nil)
return data, err
} | [
"func",
"(",
"c",
"*",
"LogCmd",
")",
"Output",
"(",
")",
"(",
"[",
"]",
"byte",
",",
"error",
")",
"{",
"st",
":=",
"time",
".",
"Now",
"(",
")",
"\n",
"data",
",",
"err",
":=",
"c",
".",
"Cmd",
".",
"Output",
"(",
")",
"\n",
"if",
"err",
... | // Output overrides exec.Cmd.Output to record the result.
// If Cmd.Stderr is nil, Output logs outputs to stderr as well. | [
"Output",
"overrides",
"exec",
".",
"Cmd",
".",
"Output",
"to",
"record",
"the",
"result",
".",
"If",
"Cmd",
".",
"Stderr",
"is",
"nil",
"Output",
"logs",
"outputs",
"to",
"stderr",
"as",
"well",
"."
] | cdbf0b975515ab2a1673c52308b0dd1683ebf1e0 | https://github.com/cybozu-go/well/blob/cdbf0b975515ab2a1673c52308b0dd1683ebf1e0/exec.go#L87-L99 |
15,186 | cybozu-go/well | exec.go | Run | func (c *LogCmd) Run() error {
if c.Cmd.Stdout == nil && c.Cmd.Stderr == nil {
_, err := c.Output()
return err
}
st := time.Now()
err := c.Cmd.Run()
c.log(st, err, nil)
return err
} | go | func (c *LogCmd) Run() error {
if c.Cmd.Stdout == nil && c.Cmd.Stderr == nil {
_, err := c.Output()
return err
}
st := time.Now()
err := c.Cmd.Run()
c.log(st, err, nil)
return err
} | [
"func",
"(",
"c",
"*",
"LogCmd",
")",
"Run",
"(",
")",
"error",
"{",
"if",
"c",
".",
"Cmd",
".",
"Stdout",
"==",
"nil",
"&&",
"c",
".",
"Cmd",
".",
"Stderr",
"==",
"nil",
"{",
"_",
",",
"err",
":=",
"c",
".",
"Output",
"(",
")",
"\n",
"retu... | // Run overrides exec.Cmd.Run to record the result.
// If both Cmd.Stdout and Cmd.Stderr are nil, this calls Output
// instead to log stderr. | [
"Run",
"overrides",
"exec",
".",
"Cmd",
".",
"Run",
"to",
"record",
"the",
"result",
".",
"If",
"both",
"Cmd",
".",
"Stdout",
"and",
"Cmd",
".",
"Stderr",
"are",
"nil",
"this",
"calls",
"Output",
"instead",
"to",
"log",
"stderr",
"."
] | cdbf0b975515ab2a1673c52308b0dd1683ebf1e0 | https://github.com/cybozu-go/well/blob/cdbf0b975515ab2a1673c52308b0dd1683ebf1e0/exec.go#L104-L114 |
15,187 | cybozu-go/well | exec.go | Wait | func (c *LogCmd) Wait() error {
st := time.Now()
err := c.Cmd.Wait()
c.log(st, err, nil)
return err
} | go | func (c *LogCmd) Wait() error {
st := time.Now()
err := c.Cmd.Wait()
c.log(st, err, nil)
return err
} | [
"func",
"(",
"c",
"*",
"LogCmd",
")",
"Wait",
"(",
")",
"error",
"{",
"st",
":=",
"time",
".",
"Now",
"(",
")",
"\n",
"err",
":=",
"c",
".",
"Cmd",
".",
"Wait",
"(",
")",
"\n",
"c",
".",
"log",
"(",
"st",
",",
"err",
",",
"nil",
")",
"\n"... | // Wait overrides exec.Cmd.Wait to record the result. | [
"Wait",
"overrides",
"exec",
".",
"Cmd",
".",
"Wait",
"to",
"record",
"the",
"result",
"."
] | cdbf0b975515ab2a1673c52308b0dd1683ebf1e0 | https://github.com/cybozu-go/well/blob/cdbf0b975515ab2a1673c52308b0dd1683ebf1e0/exec.go#L117-L122 |
15,188 | cybozu-go/well | http_17.go | ListenAndServe | func (s *HTTPServer) ListenAndServe() error {
addr := s.Server.Addr
if addr == "" {
addr = ":http"
}
ln, err := net.Listen("tcp", addr)
if err != nil {
return err
}
return s.Serve(ln)
} | go | func (s *HTTPServer) ListenAndServe() error {
addr := s.Server.Addr
if addr == "" {
addr = ":http"
}
ln, err := net.Listen("tcp", addr)
if err != nil {
return err
}
return s.Serve(ln)
} | [
"func",
"(",
"s",
"*",
"HTTPServer",
")",
"ListenAndServe",
"(",
")",
"error",
"{",
"addr",
":=",
"s",
".",
"Server",
".",
"Addr",
"\n",
"if",
"addr",
"==",
"\"",
"\"",
"{",
"addr",
"=",
"\"",
"\"",
"\n",
"}",
"\n",
"ln",
",",
"err",
":=",
"net... | // ListenAndServe overrides http.Server's method.
//
// Unlike the original, this method returns immediately just after
// starting a goroutine to accept connections. To stop listening,
// call the environment's Cancel.
//
// ListenAndServe returns non-nil error if and only if net.Listen failed. | [
"ListenAndServe",
"overrides",
"http",
".",
"Server",
"s",
"method",
".",
"Unlike",
"the",
"original",
"this",
"method",
"returns",
"immediately",
"just",
"after",
"starting",
"a",
"goroutine",
"to",
"accept",
"connections",
".",
"To",
"stop",
"listening",
"call... | cdbf0b975515ab2a1673c52308b0dd1683ebf1e0 | https://github.com/cybozu-go/well/blob/cdbf0b975515ab2a1673c52308b0dd1683ebf1e0/http_17.go#L298-L308 |
15,189 | cybozu-go/well | http_17.go | Do | func (c *HTTPClient) Do(req *http.Request) (*http.Response, error) {
ctx := req.Context()
v := ctx.Value(RequestIDContextKey)
if v != nil {
req.Header.Set(requestIDHeader, v.(string))
}
st := time.Now()
resp, err := c.Client.Do(req)
logger := c.Logger
if logger == nil {
logger = log.DefaultLogger()
}
if err == nil && (c.Severity == 0 || !logger.Enabled(c.Severity)) {
// successful logs are suppressed if c.Severity is 0 or
// logger threshold is under c.Severity.
return resp, err
}
fields := FieldsFromContext(ctx)
fields[log.FnType] = "http"
fields[log.FnResponseTime] = time.Since(st).Seconds()
fields[log.FnHTTPMethod] = req.Method
fields[log.FnURL] = req.URL.String()
fields[log.FnStartAt] = st
if err != nil {
fields["error"] = err.Error()
logger.Error("well: http", fields)
return resp, err
}
fields[log.FnHTTPStatusCode] = resp.StatusCode
logger.Log(c.Severity, "well: http", fields)
return resp, err
} | go | func (c *HTTPClient) Do(req *http.Request) (*http.Response, error) {
ctx := req.Context()
v := ctx.Value(RequestIDContextKey)
if v != nil {
req.Header.Set(requestIDHeader, v.(string))
}
st := time.Now()
resp, err := c.Client.Do(req)
logger := c.Logger
if logger == nil {
logger = log.DefaultLogger()
}
if err == nil && (c.Severity == 0 || !logger.Enabled(c.Severity)) {
// successful logs are suppressed if c.Severity is 0 or
// logger threshold is under c.Severity.
return resp, err
}
fields := FieldsFromContext(ctx)
fields[log.FnType] = "http"
fields[log.FnResponseTime] = time.Since(st).Seconds()
fields[log.FnHTTPMethod] = req.Method
fields[log.FnURL] = req.URL.String()
fields[log.FnStartAt] = st
if err != nil {
fields["error"] = err.Error()
logger.Error("well: http", fields)
return resp, err
}
fields[log.FnHTTPStatusCode] = resp.StatusCode
logger.Log(c.Severity, "well: http", fields)
return resp, err
} | [
"func",
"(",
"c",
"*",
"HTTPClient",
")",
"Do",
"(",
"req",
"*",
"http",
".",
"Request",
")",
"(",
"*",
"http",
".",
"Response",
",",
"error",
")",
"{",
"ctx",
":=",
"req",
".",
"Context",
"(",
")",
"\n",
"v",
":=",
"ctx",
".",
"Value",
"(",
... | // Do overrides http.Client.Do.
//
// req's context should have been set by http.Request.WithContext
// for request tracking and context-based cancelation. | [
"Do",
"overrides",
"http",
".",
"Client",
".",
"Do",
".",
"req",
"s",
"context",
"should",
"have",
"been",
"set",
"by",
"http",
".",
"Request",
".",
"WithContext",
"for",
"request",
"tracking",
"and",
"context",
"-",
"based",
"cancelation",
"."
] | cdbf0b975515ab2a1673c52308b0dd1683ebf1e0 | https://github.com/cybozu-go/well/blob/cdbf0b975515ab2a1673c52308b0dd1683ebf1e0/http_17.go#L378-L414 |
15,190 | cybozu-go/well | http_17.go | Post | func (c *HTTPClient) Post(url, bodyType string, body io.Reader) (*http.Response, error) {
panic("Use Do")
} | go | func (c *HTTPClient) Post(url, bodyType string, body io.Reader) (*http.Response, error) {
panic("Use Do")
} | [
"func",
"(",
"c",
"*",
"HTTPClient",
")",
"Post",
"(",
"url",
",",
"bodyType",
"string",
",",
"body",
"io",
".",
"Reader",
")",
"(",
"*",
"http",
".",
"Response",
",",
"error",
")",
"{",
"panic",
"(",
"\"",
"\"",
")",
"\n",
"}"
] | // Post panics. | [
"Post",
"panics",
"."
] | cdbf0b975515ab2a1673c52308b0dd1683ebf1e0 | https://github.com/cybozu-go/well/blob/cdbf0b975515ab2a1673c52308b0dd1683ebf1e0/http_17.go#L427-L429 |
15,191 | cybozu-go/well | http_17.go | PostForm | func (c *HTTPClient) PostForm(url string, data url.Values) (*http.Response, error) {
panic("Use Do")
} | go | func (c *HTTPClient) PostForm(url string, data url.Values) (*http.Response, error) {
panic("Use Do")
} | [
"func",
"(",
"c",
"*",
"HTTPClient",
")",
"PostForm",
"(",
"url",
"string",
",",
"data",
"url",
".",
"Values",
")",
"(",
"*",
"http",
".",
"Response",
",",
"error",
")",
"{",
"panic",
"(",
"\"",
"\"",
")",
"\n",
"}"
] | // PostForm panics. | [
"PostForm",
"panics",
"."
] | cdbf0b975515ab2a1673c52308b0dd1683ebf1e0 | https://github.com/cybozu-go/well/blob/cdbf0b975515ab2a1673c52308b0dd1683ebf1e0/http_17.go#L432-L434 |
15,192 | cybozu-go/well | graceful_unix.go | SystemdListeners | func SystemdListeners() ([]net.Listener, error) {
pid, err := strconv.Atoi(os.Getenv("LISTEN_PID"))
if err != nil {
return nil, err
}
if pid != os.Getpid() {
return nil, nil
}
return restoreListeners("LISTEN_FDS")
} | go | func SystemdListeners() ([]net.Listener, error) {
pid, err := strconv.Atoi(os.Getenv("LISTEN_PID"))
if err != nil {
return nil, err
}
if pid != os.Getpid() {
return nil, nil
}
return restoreListeners("LISTEN_FDS")
} | [
"func",
"SystemdListeners",
"(",
")",
"(",
"[",
"]",
"net",
".",
"Listener",
",",
"error",
")",
"{",
"pid",
",",
"err",
":=",
"strconv",
".",
"Atoi",
"(",
"os",
".",
"Getenv",
"(",
"\"",
"\"",
")",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"ret... | // SystemdListeners returns listeners from systemd socket activation. | [
"SystemdListeners",
"returns",
"listeners",
"from",
"systemd",
"socket",
"activation",
"."
] | cdbf0b975515ab2a1673c52308b0dd1683ebf1e0 | https://github.com/cybozu-go/well/blob/cdbf0b975515ab2a1673c52308b0dd1683ebf1e0/graceful_unix.go#L80-L89 |
15,193 | cybozu-go/well | graceful_unix.go | Run | func (g *Graceful) Run() {
if isMaster() {
env := g.Env
if env == nil {
env = defaultEnv
}
env.Go(g.runMaster)
return
}
lns, err := restoreListeners(listenEnv)
if err != nil {
log.ErrorExit(err)
}
log.DefaultLogger().SetDefaults(map[string]interface{}{
"pid": os.Getpid(),
})
log.Info("well: new child", nil)
g.Serve(lns)
// child process should not return.
os.Exit(0)
return
} | go | func (g *Graceful) Run() {
if isMaster() {
env := g.Env
if env == nil {
env = defaultEnv
}
env.Go(g.runMaster)
return
}
lns, err := restoreListeners(listenEnv)
if err != nil {
log.ErrorExit(err)
}
log.DefaultLogger().SetDefaults(map[string]interface{}{
"pid": os.Getpid(),
})
log.Info("well: new child", nil)
g.Serve(lns)
// child process should not return.
os.Exit(0)
return
} | [
"func",
"(",
"g",
"*",
"Graceful",
")",
"Run",
"(",
")",
"{",
"if",
"isMaster",
"(",
")",
"{",
"env",
":=",
"g",
".",
"Env",
"\n",
"if",
"env",
"==",
"nil",
"{",
"env",
"=",
"defaultEnv",
"\n",
"}",
"\n",
"env",
".",
"Go",
"(",
"g",
".",
"r... | // Run runs the graceful restarting server.
//
// If this is the master process, Run starts a child process,
// and installs SIGHUP handler to restarts the child process.
//
// If this is a child process, Run simply calls g.Serve.
//
// Run returns immediately in the master process, and never
// returns in the child process. | [
"Run",
"runs",
"the",
"graceful",
"restarting",
"server",
".",
"If",
"this",
"is",
"the",
"master",
"process",
"Run",
"starts",
"a",
"child",
"process",
"and",
"installs",
"SIGHUP",
"handler",
"to",
"restarts",
"the",
"child",
"process",
".",
"If",
"this",
... | cdbf0b975515ab2a1673c52308b0dd1683ebf1e0 | https://github.com/cybozu-go/well/blob/cdbf0b975515ab2a1673c52308b0dd1683ebf1e0/graceful_unix.go#L100-L123 |
15,194 | cybozu-go/well | graceful_unix.go | runMaster | func (g *Graceful) runMaster(ctx context.Context) error {
logger := log.DefaultLogger()
// prepare listener files
listeners, err := g.Listen()
if err != nil {
return err
}
files, err := listenerFiles(listeners)
if err != nil {
return err
}
if len(files) == 0 {
return errors.New("no listener")
}
defer func() {
for _, f := range files {
f.Close()
}
// we cannot close listeners no sooner than this point
// because net.UnixListener removes the socket file on Close.
for _, l := range listeners {
l.Close()
}
}()
sighup := make(chan os.Signal, 2)
signal.Notify(sighup, syscall.SIGHUP)
RESTART:
child := g.makeChild(files)
clog, err := child.StderrPipe()
if err != nil {
return err
}
copyDone := make(chan struct{})
// clog will be closed on child.Wait().
go copyLog(logger, clog, copyDone)
done := make(chan error, 1)
err = child.Start()
if err != nil {
return err
}
go func() {
<-copyDone
done <- child.Wait()
}()
select {
case err := <-done:
return err
case <-sighup:
child.Process.Signal(syscall.SIGTERM)
log.Warn("well: got sighup", nil)
time.Sleep(restartWait)
goto RESTART
case <-ctx.Done():
child.Process.Signal(syscall.SIGTERM)
if g.ExitTimeout == 0 {
<-done
return nil
}
select {
case <-done:
return nil
case <-time.After(g.ExitTimeout):
logger.Warn("well: timeout child exit", nil)
return nil
}
}
} | go | func (g *Graceful) runMaster(ctx context.Context) error {
logger := log.DefaultLogger()
// prepare listener files
listeners, err := g.Listen()
if err != nil {
return err
}
files, err := listenerFiles(listeners)
if err != nil {
return err
}
if len(files) == 0 {
return errors.New("no listener")
}
defer func() {
for _, f := range files {
f.Close()
}
// we cannot close listeners no sooner than this point
// because net.UnixListener removes the socket file on Close.
for _, l := range listeners {
l.Close()
}
}()
sighup := make(chan os.Signal, 2)
signal.Notify(sighup, syscall.SIGHUP)
RESTART:
child := g.makeChild(files)
clog, err := child.StderrPipe()
if err != nil {
return err
}
copyDone := make(chan struct{})
// clog will be closed on child.Wait().
go copyLog(logger, clog, copyDone)
done := make(chan error, 1)
err = child.Start()
if err != nil {
return err
}
go func() {
<-copyDone
done <- child.Wait()
}()
select {
case err := <-done:
return err
case <-sighup:
child.Process.Signal(syscall.SIGTERM)
log.Warn("well: got sighup", nil)
time.Sleep(restartWait)
goto RESTART
case <-ctx.Done():
child.Process.Signal(syscall.SIGTERM)
if g.ExitTimeout == 0 {
<-done
return nil
}
select {
case <-done:
return nil
case <-time.After(g.ExitTimeout):
logger.Warn("well: timeout child exit", nil)
return nil
}
}
} | [
"func",
"(",
"g",
"*",
"Graceful",
")",
"runMaster",
"(",
"ctx",
"context",
".",
"Context",
")",
"error",
"{",
"logger",
":=",
"log",
".",
"DefaultLogger",
"(",
")",
"\n\n",
"// prepare listener files",
"listeners",
",",
"err",
":=",
"g",
".",
"Listen",
... | // runMaster is the main function of the master process. | [
"runMaster",
"is",
"the",
"main",
"function",
"of",
"the",
"master",
"process",
"."
] | cdbf0b975515ab2a1673c52308b0dd1683ebf1e0 | https://github.com/cybozu-go/well/blob/cdbf0b975515ab2a1673c52308b0dd1683ebf1e0/graceful_unix.go#L126-L197 |
15,195 | cybozu-go/well | env.go | Stop | func (e *Environment) Stop() {
e.mu.Lock()
if !e.stopped {
e.stopped = true
close(e.stopCh)
}
e.mu.Unlock()
} | go | func (e *Environment) Stop() {
e.mu.Lock()
if !e.stopped {
e.stopped = true
close(e.stopCh)
}
e.mu.Unlock()
} | [
"func",
"(",
"e",
"*",
"Environment",
")",
"Stop",
"(",
")",
"{",
"e",
".",
"mu",
".",
"Lock",
"(",
")",
"\n\n",
"if",
"!",
"e",
".",
"stopped",
"{",
"e",
".",
"stopped",
"=",
"true",
"\n",
"close",
"(",
"e",
".",
"stopCh",
")",
"\n",
"}",
... | // Stop just declares no further Go will be called.
//
// Calling Stop is optional if and only if Cancel is guaranteed
// to be called at some point. For instance, if the program runs
// until SIGINT or SIGTERM, Stop is optional. | [
"Stop",
"just",
"declares",
"no",
"further",
"Go",
"will",
"be",
"called",
".",
"Calling",
"Stop",
"is",
"optional",
"if",
"and",
"only",
"if",
"Cancel",
"is",
"guaranteed",
"to",
"be",
"called",
"at",
"some",
"point",
".",
"For",
"instance",
"if",
"the"... | cdbf0b975515ab2a1673c52308b0dd1683ebf1e0 | https://github.com/cybozu-go/well/blob/cdbf0b975515ab2a1673c52308b0dd1683ebf1e0/env.go#L45-L54 |
15,196 | cybozu-go/well | env.go | Wait | func (e *Environment) Wait() error {
<-e.stopCh
if log.Enabled(log.LvDebug) {
log.Debug("well: waiting for all goroutines to complete", nil)
}
e.wg.Wait()
e.cancel() // in case no one calls Cancel
e.mu.Lock()
defer e.mu.Unlock()
return e.err
} | go | func (e *Environment) Wait() error {
<-e.stopCh
if log.Enabled(log.LvDebug) {
log.Debug("well: waiting for all goroutines to complete", nil)
}
e.wg.Wait()
e.cancel() // in case no one calls Cancel
e.mu.Lock()
defer e.mu.Unlock()
return e.err
} | [
"func",
"(",
"e",
"*",
"Environment",
")",
"Wait",
"(",
")",
"error",
"{",
"<-",
"e",
".",
"stopCh",
"\n",
"if",
"log",
".",
"Enabled",
"(",
"log",
".",
"LvDebug",
")",
"{",
"log",
".",
"Debug",
"(",
"\"",
"\"",
",",
"nil",
")",
"\n",
"}",
"\... | // Wait waits for Stop or Cancel, and for all goroutines started by
// Go to finish.
//
// The returned err is the one passed to Cancel, or nil.
// err can be tested by IsSignaled to determine whether the
// program got SIGINT or SIGTERM. | [
"Wait",
"waits",
"for",
"Stop",
"or",
"Cancel",
"and",
"for",
"all",
"goroutines",
"started",
"by",
"Go",
"to",
"finish",
".",
"The",
"returned",
"err",
"is",
"the",
"one",
"passed",
"to",
"Cancel",
"or",
"nil",
".",
"err",
"can",
"be",
"tested",
"by",... | cdbf0b975515ab2a1673c52308b0dd1683ebf1e0 | https://github.com/cybozu-go/well/blob/cdbf0b975515ab2a1673c52308b0dd1683ebf1e0/env.go#L94-L106 |
15,197 | cybozu-go/well | env.go | GoWithID | func (e *Environment) GoWithID(f func(ctx context.Context) error) {
e.Go(func(ctx context.Context) error {
return f(WithRequestID(ctx, e.generator.Generate()))
})
} | go | func (e *Environment) GoWithID(f func(ctx context.Context) error) {
e.Go(func(ctx context.Context) error {
return f(WithRequestID(ctx, e.generator.Generate()))
})
} | [
"func",
"(",
"e",
"*",
"Environment",
")",
"GoWithID",
"(",
"f",
"func",
"(",
"ctx",
"context",
".",
"Context",
")",
"error",
")",
"{",
"e",
".",
"Go",
"(",
"func",
"(",
"ctx",
"context",
".",
"Context",
")",
"error",
"{",
"return",
"f",
"(",
"Wi... | // GoWithID calls Go with a context having a new request tracking ID. | [
"GoWithID",
"calls",
"Go",
"with",
"a",
"context",
"having",
"a",
"new",
"request",
"tracking",
"ID",
"."
] | cdbf0b975515ab2a1673c52308b0dd1683ebf1e0 | https://github.com/cybozu-go/well/blob/cdbf0b975515ab2a1673c52308b0dd1683ebf1e0/env.go#L142-L146 |
15,198 | cybozu-go/well | graceful_windows.go | Run | func (g *Graceful) Run() {
env := g.Env
if env == nil {
env = defaultEnv
}
// prepare listener files
listeners, err := g.Listen()
if err != nil {
env.Cancel(err)
return
}
g.Serve(listeners)
} | go | func (g *Graceful) Run() {
env := g.Env
if env == nil {
env = defaultEnv
}
// prepare listener files
listeners, err := g.Listen()
if err != nil {
env.Cancel(err)
return
}
g.Serve(listeners)
} | [
"func",
"(",
"g",
"*",
"Graceful",
")",
"Run",
"(",
")",
"{",
"env",
":=",
"g",
".",
"Env",
"\n",
"if",
"env",
"==",
"nil",
"{",
"env",
"=",
"defaultEnv",
"\n",
"}",
"\n\n",
"// prepare listener files",
"listeners",
",",
"err",
":=",
"g",
".",
"Lis... | // Run simply calls g.Listen then g.Serve on Windows. | [
"Run",
"simply",
"calls",
"g",
".",
"Listen",
"then",
"g",
".",
"Serve",
"on",
"Windows",
"."
] | cdbf0b975515ab2a1673c52308b0dd1683ebf1e0 | https://github.com/cybozu-go/well/blob/cdbf0b975515ab2a1673c52308b0dd1683ebf1e0/graceful_windows.go#L17-L30 |
15,199 | cybozu-go/well | signal.go | handleSignal | func handleSignal(env *Environment) {
ch := make(chan os.Signal, 2)
signal.Notify(ch, stopSignals...)
go func() {
s := <-ch
log.Warn("well: got signal", map[string]interface{}{
"signal": s.String(),
})
env.Cancel(errSignaled)
}()
} | go | func handleSignal(env *Environment) {
ch := make(chan os.Signal, 2)
signal.Notify(ch, stopSignals...)
go func() {
s := <-ch
log.Warn("well: got signal", map[string]interface{}{
"signal": s.String(),
})
env.Cancel(errSignaled)
}()
} | [
"func",
"handleSignal",
"(",
"env",
"*",
"Environment",
")",
"{",
"ch",
":=",
"make",
"(",
"chan",
"os",
".",
"Signal",
",",
"2",
")",
"\n",
"signal",
".",
"Notify",
"(",
"ch",
",",
"stopSignals",
"...",
")",
"\n\n",
"go",
"func",
"(",
")",
"{",
... | // handleSignal runs independent goroutine to cancel an environment. | [
"handleSignal",
"runs",
"independent",
"goroutine",
"to",
"cancel",
"an",
"environment",
"."
] | cdbf0b975515ab2a1673c52308b0dd1683ebf1e0 | https://github.com/cybozu-go/well/blob/cdbf0b975515ab2a1673c52308b0dd1683ebf1e0/signal.go#L22-L33 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.