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
partition
stringclasses
1 value
jaegertracing/jaeger-client-go
reporter.go
SpansSubmitted
func (r *InMemoryReporter) SpansSubmitted() int { r.lock.Lock() defer r.lock.Unlock() return len(r.spans) }
go
func (r *InMemoryReporter) SpansSubmitted() int { r.lock.Lock() defer r.lock.Unlock() return len(r.spans) }
[ "func", "(", "r", "*", "InMemoryReporter", ")", "SpansSubmitted", "(", ")", "int", "{", "r", ".", "lock", ".", "Lock", "(", ")", "\n", "defer", "r", ".", "lock", ".", "Unlock", "(", ")", "\n", "return", "len", "(", "r", ".", "spans", ")", "\n", "}" ]
// SpansSubmitted returns the number of spans accumulated in the buffer.
[ "SpansSubmitted", "returns", "the", "number", "of", "spans", "accumulated", "in", "the", "buffer", "." ]
896f2abd37e099bae3eae942250d1a37e4bdce0b
https://github.com/jaegertracing/jaeger-client-go/blob/896f2abd37e099bae3eae942250d1a37e4bdce0b/reporter.go#L107-L111
train
jaegertracing/jaeger-client-go
reporter.go
GetSpans
func (r *InMemoryReporter) GetSpans() []opentracing.Span { r.lock.Lock() defer r.lock.Unlock() copied := make([]opentracing.Span, len(r.spans)) copy(copied, r.spans) return copied }
go
func (r *InMemoryReporter) GetSpans() []opentracing.Span { r.lock.Lock() defer r.lock.Unlock() copied := make([]opentracing.Span, len(r.spans)) copy(copied, r.spans) return copied }
[ "func", "(", "r", "*", "InMemoryReporter", ")", "GetSpans", "(", ")", "[", "]", "opentracing", ".", "Span", "{", "r", ".", "lock", ".", "Lock", "(", ")", "\n", "defer", "r", ".", "lock", ".", "Unlock", "(", ")", "\n", "copied", ":=", "make", "(", "[", "]", "opentracing", ".", "Span", ",", "len", "(", "r", ".", "spans", ")", ")", "\n", "copy", "(", "copied", ",", "r", ".", "spans", ")", "\n", "return", "copied", "\n", "}" ]
// GetSpans returns accumulated spans as a copy of the buffer.
[ "GetSpans", "returns", "accumulated", "spans", "as", "a", "copy", "of", "the", "buffer", "." ]
896f2abd37e099bae3eae942250d1a37e4bdce0b
https://github.com/jaegertracing/jaeger-client-go/blob/896f2abd37e099bae3eae942250d1a37e4bdce0b/reporter.go#L114-L120
train
jaegertracing/jaeger-client-go
reporter.go
Reset
func (r *InMemoryReporter) Reset() { r.lock.Lock() defer r.lock.Unlock() // Before reset the collection need to release Span memory for _, span := range r.spans { span.(*Span).Release() } r.spans = r.spans[:0] }
go
func (r *InMemoryReporter) Reset() { r.lock.Lock() defer r.lock.Unlock() // Before reset the collection need to release Span memory for _, span := range r.spans { span.(*Span).Release() } r.spans = r.spans[:0] }
[ "func", "(", "r", "*", "InMemoryReporter", ")", "Reset", "(", ")", "{", "r", ".", "lock", ".", "Lock", "(", ")", "\n", "defer", "r", ".", "lock", ".", "Unlock", "(", ")", "\n\n", "// Before reset the collection need to release Span memory", "for", "_", ",", "span", ":=", "range", "r", ".", "spans", "{", "span", ".", "(", "*", "Span", ")", ".", "Release", "(", ")", "\n", "}", "\n", "r", ".", "spans", "=", "r", ".", "spans", "[", ":", "0", "]", "\n", "}" ]
// Reset clears all accumulated spans.
[ "Reset", "clears", "all", "accumulated", "spans", "." ]
896f2abd37e099bae3eae942250d1a37e4bdce0b
https://github.com/jaegertracing/jaeger-client-go/blob/896f2abd37e099bae3eae942250d1a37e4bdce0b/reporter.go#L123-L132
train
jaegertracing/jaeger-client-go
reporter.go
processQueue
func (r *remoteReporter) processQueue() { // flush causes the Sender to flush its accumulated spans and clear the buffer flush := func() { if flushed, err := r.sender.Flush(); err != nil { r.metrics.ReporterFailure.Inc(int64(flushed)) r.logger.Error(fmt.Sprintf("error when flushing the buffer: %s", err.Error())) } else if flushed > 0 { r.metrics.ReporterSuccess.Inc(int64(flushed)) } } timer := time.NewTicker(r.bufferFlushInterval) for { select { case <-timer.C: flush() case item := <-r.queue: atomic.AddInt64(&r.queueLength, -1) switch item.itemType { case reporterQueueItemSpan: span := item.span if flushed, err := r.sender.Append(span); err != nil { r.metrics.ReporterFailure.Inc(int64(flushed)) r.logger.Error(fmt.Sprintf("error reporting span %q: %s", span.OperationName(), err.Error())) } else if flushed > 0 { r.metrics.ReporterSuccess.Inc(int64(flushed)) // to reduce the number of gauge stats, we only emit queue length on flush r.metrics.ReporterQueueLength.Update(atomic.LoadInt64(&r.queueLength)) } span.Release() case reporterQueueItemClose: timer.Stop() flush() item.close.Done() return } } } }
go
func (r *remoteReporter) processQueue() { // flush causes the Sender to flush its accumulated spans and clear the buffer flush := func() { if flushed, err := r.sender.Flush(); err != nil { r.metrics.ReporterFailure.Inc(int64(flushed)) r.logger.Error(fmt.Sprintf("error when flushing the buffer: %s", err.Error())) } else if flushed > 0 { r.metrics.ReporterSuccess.Inc(int64(flushed)) } } timer := time.NewTicker(r.bufferFlushInterval) for { select { case <-timer.C: flush() case item := <-r.queue: atomic.AddInt64(&r.queueLength, -1) switch item.itemType { case reporterQueueItemSpan: span := item.span if flushed, err := r.sender.Append(span); err != nil { r.metrics.ReporterFailure.Inc(int64(flushed)) r.logger.Error(fmt.Sprintf("error reporting span %q: %s", span.OperationName(), err.Error())) } else if flushed > 0 { r.metrics.ReporterSuccess.Inc(int64(flushed)) // to reduce the number of gauge stats, we only emit queue length on flush r.metrics.ReporterQueueLength.Update(atomic.LoadInt64(&r.queueLength)) } span.Release() case reporterQueueItemClose: timer.Stop() flush() item.close.Done() return } } } }
[ "func", "(", "r", "*", "remoteReporter", ")", "processQueue", "(", ")", "{", "// flush causes the Sender to flush its accumulated spans and clear the buffer", "flush", ":=", "func", "(", ")", "{", "if", "flushed", ",", "err", ":=", "r", ".", "sender", ".", "Flush", "(", ")", ";", "err", "!=", "nil", "{", "r", ".", "metrics", ".", "ReporterFailure", ".", "Inc", "(", "int64", "(", "flushed", ")", ")", "\n", "r", ".", "logger", ".", "Error", "(", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "err", ".", "Error", "(", ")", ")", ")", "\n", "}", "else", "if", "flushed", ">", "0", "{", "r", ".", "metrics", ".", "ReporterSuccess", ".", "Inc", "(", "int64", "(", "flushed", ")", ")", "\n", "}", "\n", "}", "\n\n", "timer", ":=", "time", ".", "NewTicker", "(", "r", ".", "bufferFlushInterval", ")", "\n", "for", "{", "select", "{", "case", "<-", "timer", ".", "C", ":", "flush", "(", ")", "\n", "case", "item", ":=", "<-", "r", ".", "queue", ":", "atomic", ".", "AddInt64", "(", "&", "r", ".", "queueLength", ",", "-", "1", ")", "\n", "switch", "item", ".", "itemType", "{", "case", "reporterQueueItemSpan", ":", "span", ":=", "item", ".", "span", "\n", "if", "flushed", ",", "err", ":=", "r", ".", "sender", ".", "Append", "(", "span", ")", ";", "err", "!=", "nil", "{", "r", ".", "metrics", ".", "ReporterFailure", ".", "Inc", "(", "int64", "(", "flushed", ")", ")", "\n", "r", ".", "logger", ".", "Error", "(", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "span", ".", "OperationName", "(", ")", ",", "err", ".", "Error", "(", ")", ")", ")", "\n", "}", "else", "if", "flushed", ">", "0", "{", "r", ".", "metrics", ".", "ReporterSuccess", ".", "Inc", "(", "int64", "(", "flushed", ")", ")", "\n", "// to reduce the number of gauge stats, we only emit queue length on flush", "r", ".", "metrics", ".", "ReporterQueueLength", ".", "Update", "(", "atomic", ".", "LoadInt64", "(", "&", "r", ".", "queueLength", ")", ")", "\n", "}", "\n", "span", ".", "Release", "(", ")", "\n", "case", "reporterQueueItemClose", ":", "timer", ".", "Stop", "(", ")", "\n", "flush", "(", ")", "\n", "item", ".", "close", ".", "Done", "(", ")", "\n", "return", "\n", "}", "\n", "}", "\n", "}", "\n", "}" ]
// processQueue reads spans from the queue, converts them to Thrift, and stores them in an internal buffer. // When the buffer length reaches batchSize, it is flushed by submitting the accumulated spans to Jaeger. // Buffer also gets flushed automatically every batchFlushInterval seconds, just in case the tracer stopped // reporting new spans.
[ "processQueue", "reads", "spans", "from", "the", "queue", "converts", "them", "to", "Thrift", "and", "stores", "them", "in", "an", "internal", "buffer", ".", "When", "the", "buffer", "length", "reaches", "batchSize", "it", "is", "flushed", "by", "submitting", "the", "accumulated", "spans", "to", "Jaeger", ".", "Buffer", "also", "gets", "flushed", "automatically", "every", "batchFlushInterval", "seconds", "just", "in", "case", "the", "tracer", "stopped", "reporting", "new", "spans", "." ]
896f2abd37e099bae3eae942250d1a37e4bdce0b
https://github.com/jaegertracing/jaeger-client-go/blob/896f2abd37e099bae3eae942250d1a37e4bdce0b/reporter.go#L259-L297
train
jaegertracing/jaeger-client-go
tracer.go
addCodec
func (t *Tracer) addCodec(format interface{}, injector Injector, extractor Extractor) { if _, ok := t.injectors[format]; !ok { t.injectors[format] = injector } if _, ok := t.extractors[format]; !ok { t.extractors[format] = extractor } }
go
func (t *Tracer) addCodec(format interface{}, injector Injector, extractor Extractor) { if _, ok := t.injectors[format]; !ok { t.injectors[format] = injector } if _, ok := t.extractors[format]; !ok { t.extractors[format] = extractor } }
[ "func", "(", "t", "*", "Tracer", ")", "addCodec", "(", "format", "interface", "{", "}", ",", "injector", "Injector", ",", "extractor", "Extractor", ")", "{", "if", "_", ",", "ok", ":=", "t", ".", "injectors", "[", "format", "]", ";", "!", "ok", "{", "t", ".", "injectors", "[", "format", "]", "=", "injector", "\n", "}", "\n", "if", "_", ",", "ok", ":=", "t", ".", "extractors", "[", "format", "]", ";", "!", "ok", "{", "t", ".", "extractors", "[", "format", "]", "=", "extractor", "\n", "}", "\n", "}" ]
// addCodec adds registers injector and extractor for given propagation format if not already defined.
[ "addCodec", "adds", "registers", "injector", "and", "extractor", "for", "given", "propagation", "format", "if", "not", "already", "defined", "." ]
896f2abd37e099bae3eae942250d1a37e4bdce0b
https://github.com/jaegertracing/jaeger-client-go/blob/896f2abd37e099bae3eae942250d1a37e4bdce0b/tracer.go#L179-L186
train
jaegertracing/jaeger-client-go
tracer.go
Close
func (t *Tracer) Close() error { t.reporter.Close() t.sampler.Close() if mgr, ok := t.baggageRestrictionManager.(io.Closer); ok { mgr.Close() } if throttler, ok := t.debugThrottler.(io.Closer); ok { throttler.Close() } return nil }
go
func (t *Tracer) Close() error { t.reporter.Close() t.sampler.Close() if mgr, ok := t.baggageRestrictionManager.(io.Closer); ok { mgr.Close() } if throttler, ok := t.debugThrottler.(io.Closer); ok { throttler.Close() } return nil }
[ "func", "(", "t", "*", "Tracer", ")", "Close", "(", ")", "error", "{", "t", ".", "reporter", ".", "Close", "(", ")", "\n", "t", ".", "sampler", ".", "Close", "(", ")", "\n", "if", "mgr", ",", "ok", ":=", "t", ".", "baggageRestrictionManager", ".", "(", "io", ".", "Closer", ")", ";", "ok", "{", "mgr", ".", "Close", "(", ")", "\n", "}", "\n", "if", "throttler", ",", "ok", ":=", "t", ".", "debugThrottler", ".", "(", "io", ".", "Closer", ")", ";", "ok", "{", "throttler", ".", "Close", "(", ")", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// Close releases all resources used by the Tracer and flushes any remaining buffered spans.
[ "Close", "releases", "all", "resources", "used", "by", "the", "Tracer", "and", "flushes", "any", "remaining", "buffered", "spans", "." ]
896f2abd37e099bae3eae942250d1a37e4bdce0b
https://github.com/jaegertracing/jaeger-client-go/blob/896f2abd37e099bae3eae942250d1a37e4bdce0b/tracer.go#L329-L339
train
jaegertracing/jaeger-client-go
tracer.go
Tags
func (t *Tracer) Tags() []opentracing.Tag { tags := make([]opentracing.Tag, len(t.tags)) for i, tag := range t.tags { tags[i] = opentracing.Tag{Key: tag.key, Value: tag.value} } return tags }
go
func (t *Tracer) Tags() []opentracing.Tag { tags := make([]opentracing.Tag, len(t.tags)) for i, tag := range t.tags { tags[i] = opentracing.Tag{Key: tag.key, Value: tag.value} } return tags }
[ "func", "(", "t", "*", "Tracer", ")", "Tags", "(", ")", "[", "]", "opentracing", ".", "Tag", "{", "tags", ":=", "make", "(", "[", "]", "opentracing", ".", "Tag", ",", "len", "(", "t", ".", "tags", ")", ")", "\n", "for", "i", ",", "tag", ":=", "range", "t", ".", "tags", "{", "tags", "[", "i", "]", "=", "opentracing", ".", "Tag", "{", "Key", ":", "tag", ".", "key", ",", "Value", ":", "tag", ".", "value", "}", "\n", "}", "\n", "return", "tags", "\n", "}" ]
// Tags returns a slice of tracer-level tags.
[ "Tags", "returns", "a", "slice", "of", "tracer", "-", "level", "tags", "." ]
896f2abd37e099bae3eae942250d1a37e4bdce0b
https://github.com/jaegertracing/jaeger-client-go/blob/896f2abd37e099bae3eae942250d1a37e4bdce0b/tracer.go#L342-L348
train
jaegertracing/jaeger-client-go
transport/zipkin/http.go
HTTPLogger
func HTTPLogger(logger jaeger.Logger) HTTPOption { return func(c *HTTPTransport) { c.logger = logger } }
go
func HTTPLogger(logger jaeger.Logger) HTTPOption { return func(c *HTTPTransport) { c.logger = logger } }
[ "func", "HTTPLogger", "(", "logger", "jaeger", ".", "Logger", ")", "HTTPOption", "{", "return", "func", "(", "c", "*", "HTTPTransport", ")", "{", "c", ".", "logger", "=", "logger", "}", "\n", "}" ]
// HTTPLogger sets the logger used to report errors in the collection // process. By default, a no-op logger is used, i.e. no errors are logged // anywhere. It's important to set this option in a production service.
[ "HTTPLogger", "sets", "the", "logger", "used", "to", "report", "errors", "in", "the", "collection", "process", ".", "By", "default", "a", "no", "-", "op", "logger", "is", "used", "i", ".", "e", ".", "no", "errors", "are", "logged", "anywhere", ".", "It", "s", "important", "to", "set", "this", "option", "in", "a", "production", "service", "." ]
896f2abd37e099bae3eae942250d1a37e4bdce0b
https://github.com/jaegertracing/jaeger-client-go/blob/896f2abd37e099bae3eae942250d1a37e4bdce0b/transport/zipkin/http.go#L67-L69
train
jaegertracing/jaeger-client-go
sampler.go
NewConstSampler
func NewConstSampler(sample bool) Sampler { tags := []Tag{ {key: SamplerTypeTagKey, value: SamplerTypeConst}, {key: SamplerParamTagKey, value: sample}, } return &ConstSampler{Decision: sample, tags: tags} }
go
func NewConstSampler(sample bool) Sampler { tags := []Tag{ {key: SamplerTypeTagKey, value: SamplerTypeConst}, {key: SamplerParamTagKey, value: sample}, } return &ConstSampler{Decision: sample, tags: tags} }
[ "func", "NewConstSampler", "(", "sample", "bool", ")", "Sampler", "{", "tags", ":=", "[", "]", "Tag", "{", "{", "key", ":", "SamplerTypeTagKey", ",", "value", ":", "SamplerTypeConst", "}", ",", "{", "key", ":", "SamplerParamTagKey", ",", "value", ":", "sample", "}", ",", "}", "\n", "return", "&", "ConstSampler", "{", "Decision", ":", "sample", ",", "tags", ":", "tags", "}", "\n", "}" ]
// NewConstSampler creates a ConstSampler.
[ "NewConstSampler", "creates", "a", "ConstSampler", "." ]
896f2abd37e099bae3eae942250d1a37e4bdce0b
https://github.com/jaegertracing/jaeger-client-go/blob/896f2abd37e099bae3eae942250d1a37e4bdce0b/sampler.go#L66-L72
train
jaegertracing/jaeger-client-go
sampler.go
NewRateLimitingSampler
func NewRateLimitingSampler(maxTracesPerSecond float64) Sampler { tags := []Tag{ {key: SamplerTypeTagKey, value: SamplerTypeRateLimiting}, {key: SamplerParamTagKey, value: maxTracesPerSecond}, } return &rateLimitingSampler{ maxTracesPerSecond: maxTracesPerSecond, rateLimiter: utils.NewRateLimiter(maxTracesPerSecond, math.Max(maxTracesPerSecond, 1.0)), tags: tags, } }
go
func NewRateLimitingSampler(maxTracesPerSecond float64) Sampler { tags := []Tag{ {key: SamplerTypeTagKey, value: SamplerTypeRateLimiting}, {key: SamplerParamTagKey, value: maxTracesPerSecond}, } return &rateLimitingSampler{ maxTracesPerSecond: maxTracesPerSecond, rateLimiter: utils.NewRateLimiter(maxTracesPerSecond, math.Max(maxTracesPerSecond, 1.0)), tags: tags, } }
[ "func", "NewRateLimitingSampler", "(", "maxTracesPerSecond", "float64", ")", "Sampler", "{", "tags", ":=", "[", "]", "Tag", "{", "{", "key", ":", "SamplerTypeTagKey", ",", "value", ":", "SamplerTypeRateLimiting", "}", ",", "{", "key", ":", "SamplerParamTagKey", ",", "value", ":", "maxTracesPerSecond", "}", ",", "}", "\n", "return", "&", "rateLimitingSampler", "{", "maxTracesPerSecond", ":", "maxTracesPerSecond", ",", "rateLimiter", ":", "utils", ".", "NewRateLimiter", "(", "maxTracesPerSecond", ",", "math", ".", "Max", "(", "maxTracesPerSecond", ",", "1.0", ")", ")", ",", "tags", ":", "tags", ",", "}", "\n", "}" ]
// NewRateLimitingSampler creates a sampler that samples at most maxTracesPerSecond. The distribution of sampled // traces follows burstiness of the service, i.e. a service with uniformly distributed requests will have those // requests sampled uniformly as well, but if requests are bursty, especially sub-second, then a number of // sequential requests can be sampled each second.
[ "NewRateLimitingSampler", "creates", "a", "sampler", "that", "samples", "at", "most", "maxTracesPerSecond", ".", "The", "distribution", "of", "sampled", "traces", "follows", "burstiness", "of", "the", "service", "i", ".", "e", ".", "a", "service", "with", "uniformly", "distributed", "requests", "will", "have", "those", "requests", "sampled", "uniformly", "as", "well", "but", "if", "requests", "are", "bursty", "especially", "sub", "-", "second", "then", "a", "number", "of", "sequential", "requests", "can", "be", "sampled", "each", "second", "." ]
896f2abd37e099bae3eae942250d1a37e4bdce0b
https://github.com/jaegertracing/jaeger-client-go/blob/896f2abd37e099bae3eae942250d1a37e4bdce0b/sampler.go#L165-L175
train
jaegertracing/jaeger-client-go
sampler.go
NewGuaranteedThroughputProbabilisticSampler
func NewGuaranteedThroughputProbabilisticSampler( lowerBound, samplingRate float64, ) (*GuaranteedThroughputProbabilisticSampler, error) { return newGuaranteedThroughputProbabilisticSampler(lowerBound, samplingRate), nil }
go
func NewGuaranteedThroughputProbabilisticSampler( lowerBound, samplingRate float64, ) (*GuaranteedThroughputProbabilisticSampler, error) { return newGuaranteedThroughputProbabilisticSampler(lowerBound, samplingRate), nil }
[ "func", "NewGuaranteedThroughputProbabilisticSampler", "(", "lowerBound", ",", "samplingRate", "float64", ",", ")", "(", "*", "GuaranteedThroughputProbabilisticSampler", ",", "error", ")", "{", "return", "newGuaranteedThroughputProbabilisticSampler", "(", "lowerBound", ",", "samplingRate", ")", ",", "nil", "\n", "}" ]
// NewGuaranteedThroughputProbabilisticSampler returns a delegating sampler that applies both // probabilisticSampler and rateLimitingSampler.
[ "NewGuaranteedThroughputProbabilisticSampler", "returns", "a", "delegating", "sampler", "that", "applies", "both", "probabilisticSampler", "and", "rateLimitingSampler", "." ]
896f2abd37e099bae3eae942250d1a37e4bdce0b
https://github.com/jaegertracing/jaeger-client-go/blob/896f2abd37e099bae3eae942250d1a37e4bdce0b/sampler.go#L212-L216
train
jaegertracing/jaeger-client-go
sampler.go
NewAdaptiveSampler
func NewAdaptiveSampler(strategies *sampling.PerOperationSamplingStrategies, maxOperations int) (Sampler, error) { return newAdaptiveSampler(strategies, maxOperations), nil }
go
func NewAdaptiveSampler(strategies *sampling.PerOperationSamplingStrategies, maxOperations int) (Sampler, error) { return newAdaptiveSampler(strategies, maxOperations), nil }
[ "func", "NewAdaptiveSampler", "(", "strategies", "*", "sampling", ".", "PerOperationSamplingStrategies", ",", "maxOperations", "int", ")", "(", "Sampler", ",", "error", ")", "{", "return", "newAdaptiveSampler", "(", "strategies", ",", "maxOperations", ")", ",", "nil", "\n", "}" ]
// NewAdaptiveSampler returns a delegating sampler that applies both probabilisticSampler and // rateLimitingSampler via the guaranteedThroughputProbabilisticSampler. This sampler keeps track of all // operations and delegates calls to the respective guaranteedThroughputProbabilisticSampler.
[ "NewAdaptiveSampler", "returns", "a", "delegating", "sampler", "that", "applies", "both", "probabilisticSampler", "and", "rateLimitingSampler", "via", "the", "guaranteedThroughputProbabilisticSampler", ".", "This", "sampler", "keeps", "track", "of", "all", "operations", "and", "delegates", "calls", "to", "the", "respective", "guaranteedThroughputProbabilisticSampler", "." ]
896f2abd37e099bae3eae942250d1a37e4bdce0b
https://github.com/jaegertracing/jaeger-client-go/blob/896f2abd37e099bae3eae942250d1a37e4bdce0b/sampler.go#L284-L286
train
jaegertracing/jaeger-client-go
header.go
ApplyDefaults
func (c *HeadersConfig) ApplyDefaults() *HeadersConfig { if c.JaegerBaggageHeader == "" { c.JaegerBaggageHeader = JaegerBaggageHeader } if c.JaegerDebugHeader == "" { c.JaegerDebugHeader = JaegerDebugHeader } if c.TraceBaggageHeaderPrefix == "" { c.TraceBaggageHeaderPrefix = TraceBaggageHeaderPrefix } if c.TraceContextHeaderName == "" { c.TraceContextHeaderName = TraceContextHeaderName } return c }
go
func (c *HeadersConfig) ApplyDefaults() *HeadersConfig { if c.JaegerBaggageHeader == "" { c.JaegerBaggageHeader = JaegerBaggageHeader } if c.JaegerDebugHeader == "" { c.JaegerDebugHeader = JaegerDebugHeader } if c.TraceBaggageHeaderPrefix == "" { c.TraceBaggageHeaderPrefix = TraceBaggageHeaderPrefix } if c.TraceContextHeaderName == "" { c.TraceContextHeaderName = TraceContextHeaderName } return c }
[ "func", "(", "c", "*", "HeadersConfig", ")", "ApplyDefaults", "(", ")", "*", "HeadersConfig", "{", "if", "c", ".", "JaegerBaggageHeader", "==", "\"", "\"", "{", "c", ".", "JaegerBaggageHeader", "=", "JaegerBaggageHeader", "\n", "}", "\n", "if", "c", ".", "JaegerDebugHeader", "==", "\"", "\"", "{", "c", ".", "JaegerDebugHeader", "=", "JaegerDebugHeader", "\n", "}", "\n", "if", "c", ".", "TraceBaggageHeaderPrefix", "==", "\"", "\"", "{", "c", ".", "TraceBaggageHeaderPrefix", "=", "TraceBaggageHeaderPrefix", "\n", "}", "\n", "if", "c", ".", "TraceContextHeaderName", "==", "\"", "\"", "{", "c", ".", "TraceContextHeaderName", "=", "TraceContextHeaderName", "\n", "}", "\n", "return", "c", "\n", "}" ]
// ApplyDefaults sets missing configuration keys to default values
[ "ApplyDefaults", "sets", "missing", "configuration", "keys", "to", "default", "values" ]
896f2abd37e099bae3eae942250d1a37e4bdce0b
https://github.com/jaegertracing/jaeger-client-go/blob/896f2abd37e099bae3eae942250d1a37e4bdce0b/header.go#L42-L56
train
jaegertracing/jaeger-client-go
log/logger.go
Infof
func (l *BytesBufferLogger) Infof(msg string, args ...interface{}) { l.mux.Lock() l.buf.WriteString("INFO: " + fmt.Sprintf(msg, args...) + "\n") l.mux.Unlock() }
go
func (l *BytesBufferLogger) Infof(msg string, args ...interface{}) { l.mux.Lock() l.buf.WriteString("INFO: " + fmt.Sprintf(msg, args...) + "\n") l.mux.Unlock() }
[ "func", "(", "l", "*", "BytesBufferLogger", ")", "Infof", "(", "msg", "string", ",", "args", "...", "interface", "{", "}", ")", "{", "l", ".", "mux", ".", "Lock", "(", ")", "\n", "l", ".", "buf", ".", "WriteString", "(", "\"", "\"", "+", "fmt", ".", "Sprintf", "(", "msg", ",", "args", "...", ")", "+", "\"", "\\n", "\"", ")", "\n", "l", ".", "mux", ".", "Unlock", "(", ")", "\n", "}" ]
// Infof implements Logger.
[ "Infof", "implements", "Logger", "." ]
896f2abd37e099bae3eae942250d1a37e4bdce0b
https://github.com/jaegertracing/jaeger-client-go/blob/896f2abd37e099bae3eae942250d1a37e4bdce0b/log/logger.go#L72-L76
train
jaegertracing/jaeger-client-go
log/logger.go
String
func (l *BytesBufferLogger) String() string { l.mux.Lock() defer l.mux.Unlock() return l.buf.String() }
go
func (l *BytesBufferLogger) String() string { l.mux.Lock() defer l.mux.Unlock() return l.buf.String() }
[ "func", "(", "l", "*", "BytesBufferLogger", ")", "String", "(", ")", "string", "{", "l", ".", "mux", ".", "Lock", "(", ")", "\n", "defer", "l", ".", "mux", ".", "Unlock", "(", ")", "\n", "return", "l", ".", "buf", ".", "String", "(", ")", "\n", "}" ]
// String returns string representation of the underlying buffer.
[ "String", "returns", "string", "representation", "of", "the", "underlying", "buffer", "." ]
896f2abd37e099bae3eae942250d1a37e4bdce0b
https://github.com/jaegertracing/jaeger-client-go/blob/896f2abd37e099bae3eae942250d1a37e4bdce0b/log/logger.go#L79-L83
train
jaegertracing/jaeger-client-go
log/logger.go
Flush
func (l *BytesBufferLogger) Flush() { l.mux.Lock() defer l.mux.Unlock() l.buf.Reset() }
go
func (l *BytesBufferLogger) Flush() { l.mux.Lock() defer l.mux.Unlock() l.buf.Reset() }
[ "func", "(", "l", "*", "BytesBufferLogger", ")", "Flush", "(", ")", "{", "l", ".", "mux", ".", "Lock", "(", ")", "\n", "defer", "l", ".", "mux", ".", "Unlock", "(", ")", "\n", "l", ".", "buf", ".", "Reset", "(", ")", "\n", "}" ]
// Flush empties the underlying buffer.
[ "Flush", "empties", "the", "underlying", "buffer", "." ]
896f2abd37e099bae3eae942250d1a37e4bdce0b
https://github.com/jaegertracing/jaeger-client-go/blob/896f2abd37e099bae3eae942250d1a37e4bdce0b/log/logger.go#L86-L90
train
jaegertracing/jaeger-client-go
config/config.go
InitGlobalTracer
func (c Configuration) InitGlobalTracer( serviceName string, options ...Option, ) (io.Closer, error) { if c.Disabled { return &nullCloser{}, nil } tracer, closer, err := c.New(serviceName, options...) if err != nil { return nil, err } opentracing.SetGlobalTracer(tracer) return closer, nil }
go
func (c Configuration) InitGlobalTracer( serviceName string, options ...Option, ) (io.Closer, error) { if c.Disabled { return &nullCloser{}, nil } tracer, closer, err := c.New(serviceName, options...) if err != nil { return nil, err } opentracing.SetGlobalTracer(tracer) return closer, nil }
[ "func", "(", "c", "Configuration", ")", "InitGlobalTracer", "(", "serviceName", "string", ",", "options", "...", "Option", ",", ")", "(", "io", ".", "Closer", ",", "error", ")", "{", "if", "c", ".", "Disabled", "{", "return", "&", "nullCloser", "{", "}", ",", "nil", "\n", "}", "\n", "tracer", ",", "closer", ",", "err", ":=", "c", ".", "New", "(", "serviceName", ",", "options", "...", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "opentracing", ".", "SetGlobalTracer", "(", "tracer", ")", "\n", "return", "closer", ",", "nil", "\n", "}" ]
// InitGlobalTracer creates a new Jaeger Tracer, and sets it as global OpenTracing Tracer. // It returns a closer func that can be used to flush buffers before shutdown.
[ "InitGlobalTracer", "creates", "a", "new", "Jaeger", "Tracer", "and", "sets", "it", "as", "global", "OpenTracing", "Tracer", ".", "It", "returns", "a", "closer", "func", "that", "can", "be", "used", "to", "flush", "buffers", "before", "shutdown", "." ]
896f2abd37e099bae3eae942250d1a37e4bdce0b
https://github.com/jaegertracing/jaeger-client-go/blob/896f2abd37e099bae3eae942250d1a37e4bdce0b/config/config.go#L304-L317
train
jaegertracing/jaeger-client-go
config/config.go
NewSampler
func (sc *SamplerConfig) NewSampler( serviceName string, metrics *jaeger.Metrics, ) (jaeger.Sampler, error) { samplerType := strings.ToLower(sc.Type) if samplerType == jaeger.SamplerTypeConst { return jaeger.NewConstSampler(sc.Param != 0), nil } if samplerType == jaeger.SamplerTypeProbabilistic { if sc.Param >= 0 && sc.Param <= 1.0 { return jaeger.NewProbabilisticSampler(sc.Param) } return nil, fmt.Errorf( "Invalid Param for probabilistic sampler: %v. Expecting value between 0 and 1", sc.Param, ) } if samplerType == jaeger.SamplerTypeRateLimiting { return jaeger.NewRateLimitingSampler(sc.Param), nil } if samplerType == jaeger.SamplerTypeRemote || sc.Type == "" { sc2 := *sc sc2.Type = jaeger.SamplerTypeProbabilistic initSampler, err := sc2.NewSampler(serviceName, nil) if err != nil { return nil, err } options := []jaeger.SamplerOption{ jaeger.SamplerOptions.Metrics(metrics), jaeger.SamplerOptions.InitialSampler(initSampler), jaeger.SamplerOptions.SamplingServerURL(sc.SamplingServerURL), } if sc.MaxOperations != 0 { options = append(options, jaeger.SamplerOptions.MaxOperations(sc.MaxOperations)) } if sc.SamplingRefreshInterval != 0 { options = append(options, jaeger.SamplerOptions.SamplingRefreshInterval(sc.SamplingRefreshInterval)) } return jaeger.NewRemotelyControlledSampler(serviceName, options...), nil } return nil, fmt.Errorf("Unknown sampler type %v", sc.Type) }
go
func (sc *SamplerConfig) NewSampler( serviceName string, metrics *jaeger.Metrics, ) (jaeger.Sampler, error) { samplerType := strings.ToLower(sc.Type) if samplerType == jaeger.SamplerTypeConst { return jaeger.NewConstSampler(sc.Param != 0), nil } if samplerType == jaeger.SamplerTypeProbabilistic { if sc.Param >= 0 && sc.Param <= 1.0 { return jaeger.NewProbabilisticSampler(sc.Param) } return nil, fmt.Errorf( "Invalid Param for probabilistic sampler: %v. Expecting value between 0 and 1", sc.Param, ) } if samplerType == jaeger.SamplerTypeRateLimiting { return jaeger.NewRateLimitingSampler(sc.Param), nil } if samplerType == jaeger.SamplerTypeRemote || sc.Type == "" { sc2 := *sc sc2.Type = jaeger.SamplerTypeProbabilistic initSampler, err := sc2.NewSampler(serviceName, nil) if err != nil { return nil, err } options := []jaeger.SamplerOption{ jaeger.SamplerOptions.Metrics(metrics), jaeger.SamplerOptions.InitialSampler(initSampler), jaeger.SamplerOptions.SamplingServerURL(sc.SamplingServerURL), } if sc.MaxOperations != 0 { options = append(options, jaeger.SamplerOptions.MaxOperations(sc.MaxOperations)) } if sc.SamplingRefreshInterval != 0 { options = append(options, jaeger.SamplerOptions.SamplingRefreshInterval(sc.SamplingRefreshInterval)) } return jaeger.NewRemotelyControlledSampler(serviceName, options...), nil } return nil, fmt.Errorf("Unknown sampler type %v", sc.Type) }
[ "func", "(", "sc", "*", "SamplerConfig", ")", "NewSampler", "(", "serviceName", "string", ",", "metrics", "*", "jaeger", ".", "Metrics", ",", ")", "(", "jaeger", ".", "Sampler", ",", "error", ")", "{", "samplerType", ":=", "strings", ".", "ToLower", "(", "sc", ".", "Type", ")", "\n", "if", "samplerType", "==", "jaeger", ".", "SamplerTypeConst", "{", "return", "jaeger", ".", "NewConstSampler", "(", "sc", ".", "Param", "!=", "0", ")", ",", "nil", "\n", "}", "\n", "if", "samplerType", "==", "jaeger", ".", "SamplerTypeProbabilistic", "{", "if", "sc", ".", "Param", ">=", "0", "&&", "sc", ".", "Param", "<=", "1.0", "{", "return", "jaeger", ".", "NewProbabilisticSampler", "(", "sc", ".", "Param", ")", "\n", "}", "\n", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "sc", ".", "Param", ",", ")", "\n", "}", "\n", "if", "samplerType", "==", "jaeger", ".", "SamplerTypeRateLimiting", "{", "return", "jaeger", ".", "NewRateLimitingSampler", "(", "sc", ".", "Param", ")", ",", "nil", "\n", "}", "\n", "if", "samplerType", "==", "jaeger", ".", "SamplerTypeRemote", "||", "sc", ".", "Type", "==", "\"", "\"", "{", "sc2", ":=", "*", "sc", "\n", "sc2", ".", "Type", "=", "jaeger", ".", "SamplerTypeProbabilistic", "\n", "initSampler", ",", "err", ":=", "sc2", ".", "NewSampler", "(", "serviceName", ",", "nil", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "options", ":=", "[", "]", "jaeger", ".", "SamplerOption", "{", "jaeger", ".", "SamplerOptions", ".", "Metrics", "(", "metrics", ")", ",", "jaeger", ".", "SamplerOptions", ".", "InitialSampler", "(", "initSampler", ")", ",", "jaeger", ".", "SamplerOptions", ".", "SamplingServerURL", "(", "sc", ".", "SamplingServerURL", ")", ",", "}", "\n", "if", "sc", ".", "MaxOperations", "!=", "0", "{", "options", "=", "append", "(", "options", ",", "jaeger", ".", "SamplerOptions", ".", "MaxOperations", "(", "sc", ".", "MaxOperations", ")", ")", "\n", "}", "\n", "if", "sc", ".", "SamplingRefreshInterval", "!=", "0", "{", "options", "=", "append", "(", "options", ",", "jaeger", ".", "SamplerOptions", ".", "SamplingRefreshInterval", "(", "sc", ".", "SamplingRefreshInterval", ")", ")", "\n", "}", "\n", "return", "jaeger", ".", "NewRemotelyControlledSampler", "(", "serviceName", ",", "options", "...", ")", ",", "nil", "\n", "}", "\n", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "sc", ".", "Type", ")", "\n", "}" ]
// NewSampler creates a new sampler based on the configuration
[ "NewSampler", "creates", "a", "new", "sampler", "based", "on", "the", "configuration" ]
896f2abd37e099bae3eae942250d1a37e4bdce0b
https://github.com/jaegertracing/jaeger-client-go/blob/896f2abd37e099bae3eae942250d1a37e4bdce0b/config/config.go#L320-L361
train
jaegertracing/jaeger-client-go
config/config.go
NewReporter
func (rc *ReporterConfig) NewReporter( serviceName string, metrics *jaeger.Metrics, logger jaeger.Logger, ) (jaeger.Reporter, error) { sender, err := rc.newTransport() if err != nil { return nil, err } reporter := jaeger.NewRemoteReporter( sender, jaeger.ReporterOptions.QueueSize(rc.QueueSize), jaeger.ReporterOptions.BufferFlushInterval(rc.BufferFlushInterval), jaeger.ReporterOptions.Logger(logger), jaeger.ReporterOptions.Metrics(metrics)) if rc.LogSpans && logger != nil { logger.Infof("Initializing logging reporter\n") reporter = jaeger.NewCompositeReporter(jaeger.NewLoggingReporter(logger), reporter) } return reporter, err }
go
func (rc *ReporterConfig) NewReporter( serviceName string, metrics *jaeger.Metrics, logger jaeger.Logger, ) (jaeger.Reporter, error) { sender, err := rc.newTransport() if err != nil { return nil, err } reporter := jaeger.NewRemoteReporter( sender, jaeger.ReporterOptions.QueueSize(rc.QueueSize), jaeger.ReporterOptions.BufferFlushInterval(rc.BufferFlushInterval), jaeger.ReporterOptions.Logger(logger), jaeger.ReporterOptions.Metrics(metrics)) if rc.LogSpans && logger != nil { logger.Infof("Initializing logging reporter\n") reporter = jaeger.NewCompositeReporter(jaeger.NewLoggingReporter(logger), reporter) } return reporter, err }
[ "func", "(", "rc", "*", "ReporterConfig", ")", "NewReporter", "(", "serviceName", "string", ",", "metrics", "*", "jaeger", ".", "Metrics", ",", "logger", "jaeger", ".", "Logger", ",", ")", "(", "jaeger", ".", "Reporter", ",", "error", ")", "{", "sender", ",", "err", ":=", "rc", ".", "newTransport", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "reporter", ":=", "jaeger", ".", "NewRemoteReporter", "(", "sender", ",", "jaeger", ".", "ReporterOptions", ".", "QueueSize", "(", "rc", ".", "QueueSize", ")", ",", "jaeger", ".", "ReporterOptions", ".", "BufferFlushInterval", "(", "rc", ".", "BufferFlushInterval", ")", ",", "jaeger", ".", "ReporterOptions", ".", "Logger", "(", "logger", ")", ",", "jaeger", ".", "ReporterOptions", ".", "Metrics", "(", "metrics", ")", ")", "\n", "if", "rc", ".", "LogSpans", "&&", "logger", "!=", "nil", "{", "logger", ".", "Infof", "(", "\"", "\\n", "\"", ")", "\n", "reporter", "=", "jaeger", ".", "NewCompositeReporter", "(", "jaeger", ".", "NewLoggingReporter", "(", "logger", ")", ",", "reporter", ")", "\n", "}", "\n", "return", "reporter", ",", "err", "\n", "}" ]
// NewReporter instantiates a new reporter that submits spans to the collector
[ "NewReporter", "instantiates", "a", "new", "reporter", "that", "submits", "spans", "to", "the", "collector" ]
896f2abd37e099bae3eae942250d1a37e4bdce0b
https://github.com/jaegertracing/jaeger-client-go/blob/896f2abd37e099bae3eae942250d1a37e4bdce0b/config/config.go#L364-L384
train
jaegertracing/jaeger-client-go
config/config_env.go
FromEnv
func FromEnv() (*Configuration, error) { c := &Configuration{} if e := os.Getenv(envServiceName); e != "" { c.ServiceName = e } if e := os.Getenv(envRPCMetrics); e != "" { if value, err := strconv.ParseBool(e); err == nil { c.RPCMetrics = value } else { return nil, errors.Wrapf(err, "cannot parse env var %s=%s", envRPCMetrics, e) } } if e := os.Getenv(envDisabled); e != "" { if value, err := strconv.ParseBool(e); err == nil { c.Disabled = value } else { return nil, errors.Wrapf(err, "cannot parse env var %s=%s", envDisabled, e) } } if e := os.Getenv(envTags); e != "" { c.Tags = parseTags(e) } if s, err := samplerConfigFromEnv(); err == nil { c.Sampler = s } else { return nil, errors.Wrap(err, "cannot obtain sampler config from env") } if r, err := reporterConfigFromEnv(); err == nil { c.Reporter = r } else { return nil, errors.Wrap(err, "cannot obtain reporter config from env") } return c, nil }
go
func FromEnv() (*Configuration, error) { c := &Configuration{} if e := os.Getenv(envServiceName); e != "" { c.ServiceName = e } if e := os.Getenv(envRPCMetrics); e != "" { if value, err := strconv.ParseBool(e); err == nil { c.RPCMetrics = value } else { return nil, errors.Wrapf(err, "cannot parse env var %s=%s", envRPCMetrics, e) } } if e := os.Getenv(envDisabled); e != "" { if value, err := strconv.ParseBool(e); err == nil { c.Disabled = value } else { return nil, errors.Wrapf(err, "cannot parse env var %s=%s", envDisabled, e) } } if e := os.Getenv(envTags); e != "" { c.Tags = parseTags(e) } if s, err := samplerConfigFromEnv(); err == nil { c.Sampler = s } else { return nil, errors.Wrap(err, "cannot obtain sampler config from env") } if r, err := reporterConfigFromEnv(); err == nil { c.Reporter = r } else { return nil, errors.Wrap(err, "cannot obtain reporter config from env") } return c, nil }
[ "func", "FromEnv", "(", ")", "(", "*", "Configuration", ",", "error", ")", "{", "c", ":=", "&", "Configuration", "{", "}", "\n\n", "if", "e", ":=", "os", ".", "Getenv", "(", "envServiceName", ")", ";", "e", "!=", "\"", "\"", "{", "c", ".", "ServiceName", "=", "e", "\n", "}", "\n\n", "if", "e", ":=", "os", ".", "Getenv", "(", "envRPCMetrics", ")", ";", "e", "!=", "\"", "\"", "{", "if", "value", ",", "err", ":=", "strconv", ".", "ParseBool", "(", "e", ")", ";", "err", "==", "nil", "{", "c", ".", "RPCMetrics", "=", "value", "\n", "}", "else", "{", "return", "nil", ",", "errors", ".", "Wrapf", "(", "err", ",", "\"", "\"", ",", "envRPCMetrics", ",", "e", ")", "\n", "}", "\n", "}", "\n\n", "if", "e", ":=", "os", ".", "Getenv", "(", "envDisabled", ")", ";", "e", "!=", "\"", "\"", "{", "if", "value", ",", "err", ":=", "strconv", ".", "ParseBool", "(", "e", ")", ";", "err", "==", "nil", "{", "c", ".", "Disabled", "=", "value", "\n", "}", "else", "{", "return", "nil", ",", "errors", ".", "Wrapf", "(", "err", ",", "\"", "\"", ",", "envDisabled", ",", "e", ")", "\n", "}", "\n", "}", "\n\n", "if", "e", ":=", "os", ".", "Getenv", "(", "envTags", ")", ";", "e", "!=", "\"", "\"", "{", "c", ".", "Tags", "=", "parseTags", "(", "e", ")", "\n", "}", "\n\n", "if", "s", ",", "err", ":=", "samplerConfigFromEnv", "(", ")", ";", "err", "==", "nil", "{", "c", ".", "Sampler", "=", "s", "\n", "}", "else", "{", "return", "nil", ",", "errors", ".", "Wrap", "(", "err", ",", "\"", "\"", ")", "\n", "}", "\n\n", "if", "r", ",", "err", ":=", "reporterConfigFromEnv", "(", ")", ";", "err", "==", "nil", "{", "c", ".", "Reporter", "=", "r", "\n", "}", "else", "{", "return", "nil", ",", "errors", ".", "Wrap", "(", "err", ",", "\"", "\"", ")", "\n", "}", "\n\n", "return", "c", ",", "nil", "\n", "}" ]
// FromEnv uses environment variables to set the tracer's Configuration
[ "FromEnv", "uses", "environment", "variables", "to", "set", "the", "tracer", "s", "Configuration" ]
896f2abd37e099bae3eae942250d1a37e4bdce0b
https://github.com/jaegertracing/jaeger-client-go/blob/896f2abd37e099bae3eae942250d1a37e4bdce0b/config/config_env.go#L53-L93
train
jaegertracing/jaeger-client-go
config/config_env.go
samplerConfigFromEnv
func samplerConfigFromEnv() (*SamplerConfig, error) { sc := &SamplerConfig{} if e := os.Getenv(envSamplerType); e != "" { sc.Type = e } if e := os.Getenv(envSamplerParam); e != "" { if value, err := strconv.ParseFloat(e, 64); err == nil { sc.Param = value } else { return nil, errors.Wrapf(err, "cannot parse env var %s=%s", envSamplerParam, e) } } if e := os.Getenv(envSamplerManagerHostPort); e != "" { sc.SamplingServerURL = e } if e := os.Getenv(envSamplerMaxOperations); e != "" { if value, err := strconv.ParseInt(e, 10, 0); err == nil { sc.MaxOperations = int(value) } else { return nil, errors.Wrapf(err, "cannot parse env var %s=%s", envSamplerMaxOperations, e) } } if e := os.Getenv(envSamplerRefreshInterval); e != "" { if value, err := time.ParseDuration(e); err == nil { sc.SamplingRefreshInterval = value } else { return nil, errors.Wrapf(err, "cannot parse env var %s=%s", envSamplerRefreshInterval, e) } } return sc, nil }
go
func samplerConfigFromEnv() (*SamplerConfig, error) { sc := &SamplerConfig{} if e := os.Getenv(envSamplerType); e != "" { sc.Type = e } if e := os.Getenv(envSamplerParam); e != "" { if value, err := strconv.ParseFloat(e, 64); err == nil { sc.Param = value } else { return nil, errors.Wrapf(err, "cannot parse env var %s=%s", envSamplerParam, e) } } if e := os.Getenv(envSamplerManagerHostPort); e != "" { sc.SamplingServerURL = e } if e := os.Getenv(envSamplerMaxOperations); e != "" { if value, err := strconv.ParseInt(e, 10, 0); err == nil { sc.MaxOperations = int(value) } else { return nil, errors.Wrapf(err, "cannot parse env var %s=%s", envSamplerMaxOperations, e) } } if e := os.Getenv(envSamplerRefreshInterval); e != "" { if value, err := time.ParseDuration(e); err == nil { sc.SamplingRefreshInterval = value } else { return nil, errors.Wrapf(err, "cannot parse env var %s=%s", envSamplerRefreshInterval, e) } } return sc, nil }
[ "func", "samplerConfigFromEnv", "(", ")", "(", "*", "SamplerConfig", ",", "error", ")", "{", "sc", ":=", "&", "SamplerConfig", "{", "}", "\n\n", "if", "e", ":=", "os", ".", "Getenv", "(", "envSamplerType", ")", ";", "e", "!=", "\"", "\"", "{", "sc", ".", "Type", "=", "e", "\n", "}", "\n\n", "if", "e", ":=", "os", ".", "Getenv", "(", "envSamplerParam", ")", ";", "e", "!=", "\"", "\"", "{", "if", "value", ",", "err", ":=", "strconv", ".", "ParseFloat", "(", "e", ",", "64", ")", ";", "err", "==", "nil", "{", "sc", ".", "Param", "=", "value", "\n", "}", "else", "{", "return", "nil", ",", "errors", ".", "Wrapf", "(", "err", ",", "\"", "\"", ",", "envSamplerParam", ",", "e", ")", "\n", "}", "\n", "}", "\n\n", "if", "e", ":=", "os", ".", "Getenv", "(", "envSamplerManagerHostPort", ")", ";", "e", "!=", "\"", "\"", "{", "sc", ".", "SamplingServerURL", "=", "e", "\n", "}", "\n\n", "if", "e", ":=", "os", ".", "Getenv", "(", "envSamplerMaxOperations", ")", ";", "e", "!=", "\"", "\"", "{", "if", "value", ",", "err", ":=", "strconv", ".", "ParseInt", "(", "e", ",", "10", ",", "0", ")", ";", "err", "==", "nil", "{", "sc", ".", "MaxOperations", "=", "int", "(", "value", ")", "\n", "}", "else", "{", "return", "nil", ",", "errors", ".", "Wrapf", "(", "err", ",", "\"", "\"", ",", "envSamplerMaxOperations", ",", "e", ")", "\n", "}", "\n", "}", "\n\n", "if", "e", ":=", "os", ".", "Getenv", "(", "envSamplerRefreshInterval", ")", ";", "e", "!=", "\"", "\"", "{", "if", "value", ",", "err", ":=", "time", ".", "ParseDuration", "(", "e", ")", ";", "err", "==", "nil", "{", "sc", ".", "SamplingRefreshInterval", "=", "value", "\n", "}", "else", "{", "return", "nil", ",", "errors", ".", "Wrapf", "(", "err", ",", "\"", "\"", ",", "envSamplerRefreshInterval", ",", "e", ")", "\n", "}", "\n", "}", "\n\n", "return", "sc", ",", "nil", "\n", "}" ]
// samplerConfigFromEnv creates a new SamplerConfig based on the environment variables
[ "samplerConfigFromEnv", "creates", "a", "new", "SamplerConfig", "based", "on", "the", "environment", "variables" ]
896f2abd37e099bae3eae942250d1a37e4bdce0b
https://github.com/jaegertracing/jaeger-client-go/blob/896f2abd37e099bae3eae942250d1a37e4bdce0b/config/config_env.go#L96-L132
train
jaegertracing/jaeger-client-go
config/config_env.go
reporterConfigFromEnv
func reporterConfigFromEnv() (*ReporterConfig, error) { rc := &ReporterConfig{} if e := os.Getenv(envReporterMaxQueueSize); e != "" { if value, err := strconv.ParseInt(e, 10, 0); err == nil { rc.QueueSize = int(value) } else { return nil, errors.Wrapf(err, "cannot parse env var %s=%s", envReporterMaxQueueSize, e) } } if e := os.Getenv(envReporterFlushInterval); e != "" { if value, err := time.ParseDuration(e); err == nil { rc.BufferFlushInterval = value } else { return nil, errors.Wrapf(err, "cannot parse env var %s=%s", envReporterFlushInterval, e) } } if e := os.Getenv(envReporterLogSpans); e != "" { if value, err := strconv.ParseBool(e); err == nil { rc.LogSpans = value } else { return nil, errors.Wrapf(err, "cannot parse env var %s=%s", envReporterLogSpans, e) } } if e := os.Getenv(envEndpoint); e != "" { u, err := url.ParseRequestURI(e) if err != nil { return nil, errors.Wrapf(err, "cannot parse env var %s=%s", envEndpoint, e) } rc.CollectorEndpoint = u.String() user := os.Getenv(envUser) pswd := os.Getenv(envPassword) if user != "" && pswd == "" || user == "" && pswd != "" { return nil, errors.Errorf("you must set %s and %s env vars together", envUser, envPassword) } rc.User = user rc.Password = pswd } else { host := jaeger.DefaultUDPSpanServerHost if e := os.Getenv(envAgentHost); e != "" { host = e } port := jaeger.DefaultUDPSpanServerPort if e := os.Getenv(envAgentPort); e != "" { if value, err := strconv.ParseInt(e, 10, 0); err == nil { port = int(value) } else { return nil, errors.Wrapf(err, "cannot parse env var %s=%s", envAgentPort, e) } } rc.LocalAgentHostPort = fmt.Sprintf("%s:%d", host, port) } return rc, nil }
go
func reporterConfigFromEnv() (*ReporterConfig, error) { rc := &ReporterConfig{} if e := os.Getenv(envReporterMaxQueueSize); e != "" { if value, err := strconv.ParseInt(e, 10, 0); err == nil { rc.QueueSize = int(value) } else { return nil, errors.Wrapf(err, "cannot parse env var %s=%s", envReporterMaxQueueSize, e) } } if e := os.Getenv(envReporterFlushInterval); e != "" { if value, err := time.ParseDuration(e); err == nil { rc.BufferFlushInterval = value } else { return nil, errors.Wrapf(err, "cannot parse env var %s=%s", envReporterFlushInterval, e) } } if e := os.Getenv(envReporterLogSpans); e != "" { if value, err := strconv.ParseBool(e); err == nil { rc.LogSpans = value } else { return nil, errors.Wrapf(err, "cannot parse env var %s=%s", envReporterLogSpans, e) } } if e := os.Getenv(envEndpoint); e != "" { u, err := url.ParseRequestURI(e) if err != nil { return nil, errors.Wrapf(err, "cannot parse env var %s=%s", envEndpoint, e) } rc.CollectorEndpoint = u.String() user := os.Getenv(envUser) pswd := os.Getenv(envPassword) if user != "" && pswd == "" || user == "" && pswd != "" { return nil, errors.Errorf("you must set %s and %s env vars together", envUser, envPassword) } rc.User = user rc.Password = pswd } else { host := jaeger.DefaultUDPSpanServerHost if e := os.Getenv(envAgentHost); e != "" { host = e } port := jaeger.DefaultUDPSpanServerPort if e := os.Getenv(envAgentPort); e != "" { if value, err := strconv.ParseInt(e, 10, 0); err == nil { port = int(value) } else { return nil, errors.Wrapf(err, "cannot parse env var %s=%s", envAgentPort, e) } } rc.LocalAgentHostPort = fmt.Sprintf("%s:%d", host, port) } return rc, nil }
[ "func", "reporterConfigFromEnv", "(", ")", "(", "*", "ReporterConfig", ",", "error", ")", "{", "rc", ":=", "&", "ReporterConfig", "{", "}", "\n\n", "if", "e", ":=", "os", ".", "Getenv", "(", "envReporterMaxQueueSize", ")", ";", "e", "!=", "\"", "\"", "{", "if", "value", ",", "err", ":=", "strconv", ".", "ParseInt", "(", "e", ",", "10", ",", "0", ")", ";", "err", "==", "nil", "{", "rc", ".", "QueueSize", "=", "int", "(", "value", ")", "\n", "}", "else", "{", "return", "nil", ",", "errors", ".", "Wrapf", "(", "err", ",", "\"", "\"", ",", "envReporterMaxQueueSize", ",", "e", ")", "\n", "}", "\n", "}", "\n\n", "if", "e", ":=", "os", ".", "Getenv", "(", "envReporterFlushInterval", ")", ";", "e", "!=", "\"", "\"", "{", "if", "value", ",", "err", ":=", "time", ".", "ParseDuration", "(", "e", ")", ";", "err", "==", "nil", "{", "rc", ".", "BufferFlushInterval", "=", "value", "\n", "}", "else", "{", "return", "nil", ",", "errors", ".", "Wrapf", "(", "err", ",", "\"", "\"", ",", "envReporterFlushInterval", ",", "e", ")", "\n", "}", "\n", "}", "\n\n", "if", "e", ":=", "os", ".", "Getenv", "(", "envReporterLogSpans", ")", ";", "e", "!=", "\"", "\"", "{", "if", "value", ",", "err", ":=", "strconv", ".", "ParseBool", "(", "e", ")", ";", "err", "==", "nil", "{", "rc", ".", "LogSpans", "=", "value", "\n", "}", "else", "{", "return", "nil", ",", "errors", ".", "Wrapf", "(", "err", ",", "\"", "\"", ",", "envReporterLogSpans", ",", "e", ")", "\n", "}", "\n", "}", "\n\n", "if", "e", ":=", "os", ".", "Getenv", "(", "envEndpoint", ")", ";", "e", "!=", "\"", "\"", "{", "u", ",", "err", ":=", "url", ".", "ParseRequestURI", "(", "e", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "errors", ".", "Wrapf", "(", "err", ",", "\"", "\"", ",", "envEndpoint", ",", "e", ")", "\n", "}", "\n", "rc", ".", "CollectorEndpoint", "=", "u", ".", "String", "(", ")", "\n", "user", ":=", "os", ".", "Getenv", "(", "envUser", ")", "\n", "pswd", ":=", "os", ".", "Getenv", "(", "envPassword", ")", "\n", "if", "user", "!=", "\"", "\"", "&&", "pswd", "==", "\"", "\"", "||", "user", "==", "\"", "\"", "&&", "pswd", "!=", "\"", "\"", "{", "return", "nil", ",", "errors", ".", "Errorf", "(", "\"", "\"", ",", "envUser", ",", "envPassword", ")", "\n", "}", "\n", "rc", ".", "User", "=", "user", "\n", "rc", ".", "Password", "=", "pswd", "\n", "}", "else", "{", "host", ":=", "jaeger", ".", "DefaultUDPSpanServerHost", "\n", "if", "e", ":=", "os", ".", "Getenv", "(", "envAgentHost", ")", ";", "e", "!=", "\"", "\"", "{", "host", "=", "e", "\n", "}", "\n\n", "port", ":=", "jaeger", ".", "DefaultUDPSpanServerPort", "\n", "if", "e", ":=", "os", ".", "Getenv", "(", "envAgentPort", ")", ";", "e", "!=", "\"", "\"", "{", "if", "value", ",", "err", ":=", "strconv", ".", "ParseInt", "(", "e", ",", "10", ",", "0", ")", ";", "err", "==", "nil", "{", "port", "=", "int", "(", "value", ")", "\n", "}", "else", "{", "return", "nil", ",", "errors", ".", "Wrapf", "(", "err", ",", "\"", "\"", ",", "envAgentPort", ",", "e", ")", "\n", "}", "\n", "}", "\n", "rc", ".", "LocalAgentHostPort", "=", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "host", ",", "port", ")", "\n", "}", "\n\n", "return", "rc", ",", "nil", "\n", "}" ]
// reporterConfigFromEnv creates a new ReporterConfig based on the environment variables
[ "reporterConfigFromEnv", "creates", "a", "new", "ReporterConfig", "based", "on", "the", "environment", "variables" ]
896f2abd37e099bae3eae942250d1a37e4bdce0b
https://github.com/jaegertracing/jaeger-client-go/blob/896f2abd37e099bae3eae942250d1a37e4bdce0b/config/config_env.go#L135-L193
train
jaegertracing/jaeger-client-go
internal/throttler/remote/options.go
SynchronousInitialization
func (options) SynchronousInitialization(b bool) Option { return func(o *options) { o.synchronousInitialization = b } }
go
func (options) SynchronousInitialization(b bool) Option { return func(o *options) { o.synchronousInitialization = b } }
[ "func", "(", "options", ")", "SynchronousInitialization", "(", "b", "bool", ")", "Option", "{", "return", "func", "(", "o", "*", "options", ")", "{", "o", ".", "synchronousInitialization", "=", "b", "\n", "}", "\n", "}" ]
// SynchronousInitialization creates an Option that determines whether the throttler should synchronously // fetch credits from the agent when an operation is seen for the first time. This should be set to true // if the client will be used by a short lived service that needs to ensure that credits are fetched upfront // such that sampling or throttling occurs.
[ "SynchronousInitialization", "creates", "an", "Option", "that", "determines", "whether", "the", "throttler", "should", "synchronously", "fetch", "credits", "from", "the", "agent", "when", "an", "operation", "is", "seen", "for", "the", "first", "time", ".", "This", "should", "be", "set", "to", "true", "if", "the", "client", "will", "be", "used", "by", "a", "short", "lived", "service", "that", "needs", "to", "ensure", "that", "credits", "are", "fetched", "upfront", "such", "that", "sampling", "or", "throttling", "occurs", "." ]
896f2abd37e099bae3eae942250d1a37e4bdce0b
https://github.com/jaegertracing/jaeger-client-go/blob/896f2abd37e099bae3eae942250d1a37e4bdce0b/internal/throttler/remote/options.go#L75-L79
train
hashicorp/go-retryablehttp
client.go
BodyBytes
func (r *Request) BodyBytes() ([]byte, error) { if r.body == nil { return nil, nil } body, err := r.body() if err != nil { return nil, err } buf := new(bytes.Buffer) _, err = buf.ReadFrom(body) if err != nil { return nil, err } return buf.Bytes(), nil }
go
func (r *Request) BodyBytes() ([]byte, error) { if r.body == nil { return nil, nil } body, err := r.body() if err != nil { return nil, err } buf := new(bytes.Buffer) _, err = buf.ReadFrom(body) if err != nil { return nil, err } return buf.Bytes(), nil }
[ "func", "(", "r", "*", "Request", ")", "BodyBytes", "(", ")", "(", "[", "]", "byte", ",", "error", ")", "{", "if", "r", ".", "body", "==", "nil", "{", "return", "nil", ",", "nil", "\n", "}", "\n", "body", ",", "err", ":=", "r", ".", "body", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "buf", ":=", "new", "(", "bytes", ".", "Buffer", ")", "\n", "_", ",", "err", "=", "buf", ".", "ReadFrom", "(", "body", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "return", "buf", ".", "Bytes", "(", ")", ",", "nil", "\n", "}" ]
// BodyBytes allows accessing the request body. It is an analogue to // http.Request's Body variable, but it returns a copy of the underlying data // rather than consuming it. // // This function is not thread-safe; do not call it at the same time as another // call, or at the same time this request is being used with Client.Do.
[ "BodyBytes", "allows", "accessing", "the", "request", "body", ".", "It", "is", "an", "analogue", "to", "http", ".", "Request", "s", "Body", "variable", "but", "it", "returns", "a", "copy", "of", "the", "underlying", "data", "rather", "than", "consuming", "it", ".", "This", "function", "is", "not", "thread", "-", "safe", ";", "do", "not", "call", "it", "at", "the", "same", "time", "as", "another", "call", "or", "at", "the", "same", "time", "this", "request", "is", "being", "used", "with", "Client", ".", "Do", "." ]
4ea34a9a437e0e910fe5fea5be81372a39336bb0
https://github.com/hashicorp/go-retryablehttp/blob/4ea34a9a437e0e910fe5fea5be81372a39336bb0/client.go#L90-L104
train
hashicorp/go-retryablehttp
client.go
NewClient
func NewClient() *Client { return &Client{ HTTPClient: cleanhttp.DefaultClient(), Logger: log.New(os.Stderr, "", log.LstdFlags), RetryWaitMin: defaultRetryWaitMin, RetryWaitMax: defaultRetryWaitMax, RetryMax: defaultRetryMax, CheckRetry: DefaultRetryPolicy, Backoff: DefaultBackoff, } }
go
func NewClient() *Client { return &Client{ HTTPClient: cleanhttp.DefaultClient(), Logger: log.New(os.Stderr, "", log.LstdFlags), RetryWaitMin: defaultRetryWaitMin, RetryWaitMax: defaultRetryWaitMax, RetryMax: defaultRetryMax, CheckRetry: DefaultRetryPolicy, Backoff: DefaultBackoff, } }
[ "func", "NewClient", "(", ")", "*", "Client", "{", "return", "&", "Client", "{", "HTTPClient", ":", "cleanhttp", ".", "DefaultClient", "(", ")", ",", "Logger", ":", "log", ".", "New", "(", "os", ".", "Stderr", ",", "\"", "\"", ",", "log", ".", "LstdFlags", ")", ",", "RetryWaitMin", ":", "defaultRetryWaitMin", ",", "RetryWaitMax", ":", "defaultRetryWaitMax", ",", "RetryMax", ":", "defaultRetryMax", ",", "CheckRetry", ":", "DefaultRetryPolicy", ",", "Backoff", ":", "DefaultBackoff", ",", "}", "\n", "}" ]
// NewClient creates a new Client with default settings.
[ "NewClient", "creates", "a", "new", "Client", "with", "default", "settings", "." ]
4ea34a9a437e0e910fe5fea5be81372a39336bb0
https://github.com/hashicorp/go-retryablehttp/blob/4ea34a9a437e0e910fe5fea5be81372a39336bb0/client.go#L278-L288
train
hashicorp/go-retryablehttp
client.go
DefaultRetryPolicy
func DefaultRetryPolicy(ctx context.Context, resp *http.Response, err error) (bool, error) { // do not retry on context.Canceled or context.DeadlineExceeded if ctx.Err() != nil { return false, ctx.Err() } if err != nil { return true, err } // Check the response code. We retry on 500-range responses to allow // the server time to recover, as 500's are typically not permanent // errors and may relate to outages on the server side. This will catch // invalid response codes as well, like 0 and 999. if resp.StatusCode == 0 || (resp.StatusCode >= 500 && resp.StatusCode != 501) { return true, nil } return false, nil }
go
func DefaultRetryPolicy(ctx context.Context, resp *http.Response, err error) (bool, error) { // do not retry on context.Canceled or context.DeadlineExceeded if ctx.Err() != nil { return false, ctx.Err() } if err != nil { return true, err } // Check the response code. We retry on 500-range responses to allow // the server time to recover, as 500's are typically not permanent // errors and may relate to outages on the server side. This will catch // invalid response codes as well, like 0 and 999. if resp.StatusCode == 0 || (resp.StatusCode >= 500 && resp.StatusCode != 501) { return true, nil } return false, nil }
[ "func", "DefaultRetryPolicy", "(", "ctx", "context", ".", "Context", ",", "resp", "*", "http", ".", "Response", ",", "err", "error", ")", "(", "bool", ",", "error", ")", "{", "// do not retry on context.Canceled or context.DeadlineExceeded", "if", "ctx", ".", "Err", "(", ")", "!=", "nil", "{", "return", "false", ",", "ctx", ".", "Err", "(", ")", "\n", "}", "\n\n", "if", "err", "!=", "nil", "{", "return", "true", ",", "err", "\n", "}", "\n", "// Check the response code. We retry on 500-range responses to allow", "// the server time to recover, as 500's are typically not permanent", "// errors and may relate to outages on the server side. This will catch", "// invalid response codes as well, like 0 and 999.", "if", "resp", ".", "StatusCode", "==", "0", "||", "(", "resp", ".", "StatusCode", ">=", "500", "&&", "resp", ".", "StatusCode", "!=", "501", ")", "{", "return", "true", ",", "nil", "\n", "}", "\n\n", "return", "false", ",", "nil", "\n", "}" ]
// DefaultRetryPolicy provides a default callback for Client.CheckRetry, which // will retry on connection errors and server errors.
[ "DefaultRetryPolicy", "provides", "a", "default", "callback", "for", "Client", ".", "CheckRetry", "which", "will", "retry", "on", "connection", "errors", "and", "server", "errors", "." ]
4ea34a9a437e0e910fe5fea5be81372a39336bb0
https://github.com/hashicorp/go-retryablehttp/blob/4ea34a9a437e0e910fe5fea5be81372a39336bb0/client.go#L292-L310
train
hashicorp/go-retryablehttp
client.go
DefaultBackoff
func DefaultBackoff(min, max time.Duration, attemptNum int, resp *http.Response) time.Duration { mult := math.Pow(2, float64(attemptNum)) * float64(min) sleep := time.Duration(mult) if float64(sleep) != mult || sleep > max { sleep = max } return sleep }
go
func DefaultBackoff(min, max time.Duration, attemptNum int, resp *http.Response) time.Duration { mult := math.Pow(2, float64(attemptNum)) * float64(min) sleep := time.Duration(mult) if float64(sleep) != mult || sleep > max { sleep = max } return sleep }
[ "func", "DefaultBackoff", "(", "min", ",", "max", "time", ".", "Duration", ",", "attemptNum", "int", ",", "resp", "*", "http", ".", "Response", ")", "time", ".", "Duration", "{", "mult", ":=", "math", ".", "Pow", "(", "2", ",", "float64", "(", "attemptNum", ")", ")", "*", "float64", "(", "min", ")", "\n", "sleep", ":=", "time", ".", "Duration", "(", "mult", ")", "\n", "if", "float64", "(", "sleep", ")", "!=", "mult", "||", "sleep", ">", "max", "{", "sleep", "=", "max", "\n", "}", "\n", "return", "sleep", "\n", "}" ]
// DefaultBackoff provides a default callback for Client.Backoff which // will perform exponential backoff based on the attempt number and limited // by the provided minimum and maximum durations.
[ "DefaultBackoff", "provides", "a", "default", "callback", "for", "Client", ".", "Backoff", "which", "will", "perform", "exponential", "backoff", "based", "on", "the", "attempt", "number", "and", "limited", "by", "the", "provided", "minimum", "and", "maximum", "durations", "." ]
4ea34a9a437e0e910fe5fea5be81372a39336bb0
https://github.com/hashicorp/go-retryablehttp/blob/4ea34a9a437e0e910fe5fea5be81372a39336bb0/client.go#L315-L322
train
hashicorp/go-retryablehttp
client.go
Do
func (c *Client) Do(req *Request) (*http.Response, error) { if c.Logger != nil { c.Logger.Printf("[DEBUG] %s %s", req.Method, req.URL) } var resp *http.Response var err error for i := 0; ; i++ { var code int // HTTP response code // Always rewind the request body when non-nil. if req.body != nil { body, err := req.body() if err != nil { return resp, err } if c, ok := body.(io.ReadCloser); ok { req.Body = c } else { req.Body = ioutil.NopCloser(body) } } if c.RequestLogHook != nil { c.RequestLogHook(c.Logger, req.Request, i) } // Attempt the request resp, err = c.HTTPClient.Do(req.Request) if resp != nil { code = resp.StatusCode } // Check if we should continue with retries. checkOK, checkErr := c.CheckRetry(req.Context(), resp, err) if err != nil { if c.Logger != nil { c.Logger.Printf("[ERR] %s %s request failed: %v", req.Method, req.URL, err) } } else { // Call this here to maintain the behavior of logging all requests, // even if CheckRetry signals to stop. if c.ResponseLogHook != nil { // Call the response logger function if provided. c.ResponseLogHook(c.Logger, resp) } } // Now decide if we should continue. if !checkOK { if checkErr != nil { err = checkErr } return resp, err } // We do this before drainBody beause there's no need for the I/O if // we're breaking out remain := c.RetryMax - i if remain <= 0 { break } // We're going to retry, consume any response to reuse the connection. if err == nil && resp != nil { c.drainBody(resp.Body) } wait := c.Backoff(c.RetryWaitMin, c.RetryWaitMax, i, resp) desc := fmt.Sprintf("%s %s", req.Method, req.URL) if code > 0 { desc = fmt.Sprintf("%s (status: %d)", desc, code) } if c.Logger != nil { c.Logger.Printf("[DEBUG] %s: retrying in %s (%d left)", desc, wait, remain) } select { case <-req.Context().Done(): return nil, req.Context().Err() case <-time.After(wait): } } if c.ErrorHandler != nil { return c.ErrorHandler(resp, err, c.RetryMax+1) } // By default, we close the response body and return an error without // returning the response if resp != nil { resp.Body.Close() } return nil, fmt.Errorf("%s %s giving up after %d attempts", req.Method, req.URL, c.RetryMax+1) }
go
func (c *Client) Do(req *Request) (*http.Response, error) { if c.Logger != nil { c.Logger.Printf("[DEBUG] %s %s", req.Method, req.URL) } var resp *http.Response var err error for i := 0; ; i++ { var code int // HTTP response code // Always rewind the request body when non-nil. if req.body != nil { body, err := req.body() if err != nil { return resp, err } if c, ok := body.(io.ReadCloser); ok { req.Body = c } else { req.Body = ioutil.NopCloser(body) } } if c.RequestLogHook != nil { c.RequestLogHook(c.Logger, req.Request, i) } // Attempt the request resp, err = c.HTTPClient.Do(req.Request) if resp != nil { code = resp.StatusCode } // Check if we should continue with retries. checkOK, checkErr := c.CheckRetry(req.Context(), resp, err) if err != nil { if c.Logger != nil { c.Logger.Printf("[ERR] %s %s request failed: %v", req.Method, req.URL, err) } } else { // Call this here to maintain the behavior of logging all requests, // even if CheckRetry signals to stop. if c.ResponseLogHook != nil { // Call the response logger function if provided. c.ResponseLogHook(c.Logger, resp) } } // Now decide if we should continue. if !checkOK { if checkErr != nil { err = checkErr } return resp, err } // We do this before drainBody beause there's no need for the I/O if // we're breaking out remain := c.RetryMax - i if remain <= 0 { break } // We're going to retry, consume any response to reuse the connection. if err == nil && resp != nil { c.drainBody(resp.Body) } wait := c.Backoff(c.RetryWaitMin, c.RetryWaitMax, i, resp) desc := fmt.Sprintf("%s %s", req.Method, req.URL) if code > 0 { desc = fmt.Sprintf("%s (status: %d)", desc, code) } if c.Logger != nil { c.Logger.Printf("[DEBUG] %s: retrying in %s (%d left)", desc, wait, remain) } select { case <-req.Context().Done(): return nil, req.Context().Err() case <-time.After(wait): } } if c.ErrorHandler != nil { return c.ErrorHandler(resp, err, c.RetryMax+1) } // By default, we close the response body and return an error without // returning the response if resp != nil { resp.Body.Close() } return nil, fmt.Errorf("%s %s giving up after %d attempts", req.Method, req.URL, c.RetryMax+1) }
[ "func", "(", "c", "*", "Client", ")", "Do", "(", "req", "*", "Request", ")", "(", "*", "http", ".", "Response", ",", "error", ")", "{", "if", "c", ".", "Logger", "!=", "nil", "{", "c", ".", "Logger", ".", "Printf", "(", "\"", "\"", ",", "req", ".", "Method", ",", "req", ".", "URL", ")", "\n", "}", "\n\n", "var", "resp", "*", "http", ".", "Response", "\n", "var", "err", "error", "\n\n", "for", "i", ":=", "0", ";", ";", "i", "++", "{", "var", "code", "int", "// HTTP response code", "\n\n", "// Always rewind the request body when non-nil.", "if", "req", ".", "body", "!=", "nil", "{", "body", ",", "err", ":=", "req", ".", "body", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "resp", ",", "err", "\n", "}", "\n", "if", "c", ",", "ok", ":=", "body", ".", "(", "io", ".", "ReadCloser", ")", ";", "ok", "{", "req", ".", "Body", "=", "c", "\n", "}", "else", "{", "req", ".", "Body", "=", "ioutil", ".", "NopCloser", "(", "body", ")", "\n", "}", "\n", "}", "\n\n", "if", "c", ".", "RequestLogHook", "!=", "nil", "{", "c", ".", "RequestLogHook", "(", "c", ".", "Logger", ",", "req", ".", "Request", ",", "i", ")", "\n", "}", "\n\n", "// Attempt the request", "resp", ",", "err", "=", "c", ".", "HTTPClient", ".", "Do", "(", "req", ".", "Request", ")", "\n", "if", "resp", "!=", "nil", "{", "code", "=", "resp", ".", "StatusCode", "\n", "}", "\n\n", "// Check if we should continue with retries.", "checkOK", ",", "checkErr", ":=", "c", ".", "CheckRetry", "(", "req", ".", "Context", "(", ")", ",", "resp", ",", "err", ")", "\n\n", "if", "err", "!=", "nil", "{", "if", "c", ".", "Logger", "!=", "nil", "{", "c", ".", "Logger", ".", "Printf", "(", "\"", "\"", ",", "req", ".", "Method", ",", "req", ".", "URL", ",", "err", ")", "\n", "}", "\n", "}", "else", "{", "// Call this here to maintain the behavior of logging all requests,", "// even if CheckRetry signals to stop.", "if", "c", ".", "ResponseLogHook", "!=", "nil", "{", "// Call the response logger function if provided.", "c", ".", "ResponseLogHook", "(", "c", ".", "Logger", ",", "resp", ")", "\n", "}", "\n", "}", "\n\n", "// Now decide if we should continue.", "if", "!", "checkOK", "{", "if", "checkErr", "!=", "nil", "{", "err", "=", "checkErr", "\n", "}", "\n", "return", "resp", ",", "err", "\n", "}", "\n\n", "// We do this before drainBody beause there's no need for the I/O if", "// we're breaking out", "remain", ":=", "c", ".", "RetryMax", "-", "i", "\n", "if", "remain", "<=", "0", "{", "break", "\n", "}", "\n\n", "// We're going to retry, consume any response to reuse the connection.", "if", "err", "==", "nil", "&&", "resp", "!=", "nil", "{", "c", ".", "drainBody", "(", "resp", ".", "Body", ")", "\n", "}", "\n\n", "wait", ":=", "c", ".", "Backoff", "(", "c", ".", "RetryWaitMin", ",", "c", ".", "RetryWaitMax", ",", "i", ",", "resp", ")", "\n", "desc", ":=", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "req", ".", "Method", ",", "req", ".", "URL", ")", "\n", "if", "code", ">", "0", "{", "desc", "=", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "desc", ",", "code", ")", "\n", "}", "\n", "if", "c", ".", "Logger", "!=", "nil", "{", "c", ".", "Logger", ".", "Printf", "(", "\"", "\"", ",", "desc", ",", "wait", ",", "remain", ")", "\n", "}", "\n", "select", "{", "case", "<-", "req", ".", "Context", "(", ")", ".", "Done", "(", ")", ":", "return", "nil", ",", "req", ".", "Context", "(", ")", ".", "Err", "(", ")", "\n", "case", "<-", "time", ".", "After", "(", "wait", ")", ":", "}", "\n", "}", "\n\n", "if", "c", ".", "ErrorHandler", "!=", "nil", "{", "return", "c", ".", "ErrorHandler", "(", "resp", ",", "err", ",", "c", ".", "RetryMax", "+", "1", ")", "\n", "}", "\n\n", "// By default, we close the response body and return an error without", "// returning the response", "if", "resp", "!=", "nil", "{", "resp", ".", "Body", ".", "Close", "(", ")", "\n", "}", "\n", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "req", ".", "Method", ",", "req", ".", "URL", ",", "c", ".", "RetryMax", "+", "1", ")", "\n", "}" ]
// Do wraps calling an HTTP method with retries.
[ "Do", "wraps", "calling", "an", "HTTP", "method", "with", "retries", "." ]
4ea34a9a437e0e910fe5fea5be81372a39336bb0
https://github.com/hashicorp/go-retryablehttp/blob/4ea34a9a437e0e910fe5fea5be81372a39336bb0/client.go#L370-L466
train
hashicorp/go-retryablehttp
client.go
drainBody
func (c *Client) drainBody(body io.ReadCloser) { defer body.Close() _, err := io.Copy(ioutil.Discard, io.LimitReader(body, respReadLimit)) if err != nil { if c.Logger != nil { c.Logger.Printf("[ERR] error reading response body: %v", err) } } }
go
func (c *Client) drainBody(body io.ReadCloser) { defer body.Close() _, err := io.Copy(ioutil.Discard, io.LimitReader(body, respReadLimit)) if err != nil { if c.Logger != nil { c.Logger.Printf("[ERR] error reading response body: %v", err) } } }
[ "func", "(", "c", "*", "Client", ")", "drainBody", "(", "body", "io", ".", "ReadCloser", ")", "{", "defer", "body", ".", "Close", "(", ")", "\n", "_", ",", "err", ":=", "io", ".", "Copy", "(", "ioutil", ".", "Discard", ",", "io", ".", "LimitReader", "(", "body", ",", "respReadLimit", ")", ")", "\n", "if", "err", "!=", "nil", "{", "if", "c", ".", "Logger", "!=", "nil", "{", "c", ".", "Logger", ".", "Printf", "(", "\"", "\"", ",", "err", ")", "\n", "}", "\n", "}", "\n", "}" ]
// Try to read the response body so we can reuse this connection.
[ "Try", "to", "read", "the", "response", "body", "so", "we", "can", "reuse", "this", "connection", "." ]
4ea34a9a437e0e910fe5fea5be81372a39336bb0
https://github.com/hashicorp/go-retryablehttp/blob/4ea34a9a437e0e910fe5fea5be81372a39336bb0/client.go#L469-L477
train
hashicorp/go-retryablehttp
client.go
Post
func Post(url, bodyType string, body interface{}) (*http.Response, error) { return defaultClient.Post(url, bodyType, body) }
go
func Post(url, bodyType string, body interface{}) (*http.Response, error) { return defaultClient.Post(url, bodyType, body) }
[ "func", "Post", "(", "url", ",", "bodyType", "string", ",", "body", "interface", "{", "}", ")", "(", "*", "http", ".", "Response", ",", "error", ")", "{", "return", "defaultClient", ".", "Post", "(", "url", ",", "bodyType", ",", "body", ")", "\n", "}" ]
// Post is a shortcut for doing a POST request without making a new client.
[ "Post", "is", "a", "shortcut", "for", "doing", "a", "POST", "request", "without", "making", "a", "new", "client", "." ]
4ea34a9a437e0e910fe5fea5be81372a39336bb0
https://github.com/hashicorp/go-retryablehttp/blob/4ea34a9a437e0e910fe5fea5be81372a39336bb0/client.go#L508-L510
train
hashicorp/go-retryablehttp
client.go
PostForm
func PostForm(url string, data url.Values) (*http.Response, error) { return defaultClient.PostForm(url, data) }
go
func PostForm(url string, data url.Values) (*http.Response, error) { return defaultClient.PostForm(url, data) }
[ "func", "PostForm", "(", "url", "string", ",", "data", "url", ".", "Values", ")", "(", "*", "http", ".", "Response", ",", "error", ")", "{", "return", "defaultClient", ".", "PostForm", "(", "url", ",", "data", ")", "\n", "}" ]
// PostForm is a shortcut to perform a POST with form data without creating // a new client.
[ "PostForm", "is", "a", "shortcut", "to", "perform", "a", "POST", "with", "form", "data", "without", "creating", "a", "new", "client", "." ]
4ea34a9a437e0e910fe5fea5be81372a39336bb0
https://github.com/hashicorp/go-retryablehttp/blob/4ea34a9a437e0e910fe5fea5be81372a39336bb0/client.go#L524-L526
train
jolestar/go-commons-pool
concurrent/atomic.go
GetAndIncrement
func (i *AtomicInteger) GetAndIncrement() int32 { ret := atomic.LoadInt32((*int32)(i)) atomic.AddInt32((*int32)(i), int32(1)) return ret }
go
func (i *AtomicInteger) GetAndIncrement() int32 { ret := atomic.LoadInt32((*int32)(i)) atomic.AddInt32((*int32)(i), int32(1)) return ret }
[ "func", "(", "i", "*", "AtomicInteger", ")", "GetAndIncrement", "(", ")", "int32", "{", "ret", ":=", "atomic", ".", "LoadInt32", "(", "(", "*", "int32", ")", "(", "i", ")", ")", "\n", "atomic", ".", "AddInt32", "(", "(", "*", "int32", ")", "(", "i", ")", ",", "int32", "(", "1", ")", ")", "\n", "return", "ret", "\n", "}" ]
// GetAndIncrement increment wrapped int32 with 1 and return old value.
[ "GetAndIncrement", "increment", "wrapped", "int32", "with", "1", "and", "return", "old", "value", "." ]
5cc5d37d092a27de00a69e4501f50bb4ead1b304
https://github.com/jolestar/go-commons-pool/blob/5cc5d37d092a27de00a69e4501f50bb4ead1b304/concurrent/atomic.go#L14-L18
train
jolestar/go-commons-pool
concurrent/atomic.go
GetAndDecrement
func (i *AtomicInteger) GetAndDecrement() int32 { ret := atomic.LoadInt32((*int32)(i)) atomic.AddInt32((*int32)(i), int32(-1)) return ret }
go
func (i *AtomicInteger) GetAndDecrement() int32 { ret := atomic.LoadInt32((*int32)(i)) atomic.AddInt32((*int32)(i), int32(-1)) return ret }
[ "func", "(", "i", "*", "AtomicInteger", ")", "GetAndDecrement", "(", ")", "int32", "{", "ret", ":=", "atomic", ".", "LoadInt32", "(", "(", "*", "int32", ")", "(", "i", ")", ")", "\n", "atomic", ".", "AddInt32", "(", "(", "*", "int32", ")", "(", "i", ")", ",", "int32", "(", "-", "1", ")", ")", "\n", "return", "ret", "\n", "}" ]
// GetAndDecrement decrement wrapped int32 with 1 and return old value.
[ "GetAndDecrement", "decrement", "wrapped", "int32", "with", "1", "and", "return", "old", "value", "." ]
5cc5d37d092a27de00a69e4501f50bb4ead1b304
https://github.com/jolestar/go-commons-pool/blob/5cc5d37d092a27de00a69e4501f50bb4ead1b304/concurrent/atomic.go#L26-L30
train
jolestar/go-commons-pool
concurrent/cond.go
NewTimeoutCond
func NewTimeoutCond(l sync.Locker) *TimeoutCond { cond := TimeoutCond{L: l, signal: make(chan int, 0)} return &cond }
go
func NewTimeoutCond(l sync.Locker) *TimeoutCond { cond := TimeoutCond{L: l, signal: make(chan int, 0)} return &cond }
[ "func", "NewTimeoutCond", "(", "l", "sync", ".", "Locker", ")", "*", "TimeoutCond", "{", "cond", ":=", "TimeoutCond", "{", "L", ":", "l", ",", "signal", ":", "make", "(", "chan", "int", ",", "0", ")", "}", "\n", "return", "&", "cond", "\n", "}" ]
// NewTimeoutCond return a new TimeoutCond
[ "NewTimeoutCond", "return", "a", "new", "TimeoutCond" ]
5cc5d37d092a27de00a69e4501f50bb4ead1b304
https://github.com/jolestar/go-commons-pool/blob/5cc5d37d092a27de00a69e4501f50bb4ead1b304/concurrent/cond.go#L19-L22
train
jolestar/go-commons-pool
concurrent/cond.go
Wait
func (cond *TimeoutCond) Wait(ctx context.Context) bool { cond.addWaiter() //copy signal in lock, avoid data race with Interrupt ch := cond.signal //wait should unlock mutex, if not will cause deadlock cond.L.Unlock() defer cond.removeWaiter() defer cond.L.Lock() select { case _, ok := <-ch: return !ok case <-ctx.Done(): return false } }
go
func (cond *TimeoutCond) Wait(ctx context.Context) bool { cond.addWaiter() //copy signal in lock, avoid data race with Interrupt ch := cond.signal //wait should unlock mutex, if not will cause deadlock cond.L.Unlock() defer cond.removeWaiter() defer cond.L.Lock() select { case _, ok := <-ch: return !ok case <-ctx.Done(): return false } }
[ "func", "(", "cond", "*", "TimeoutCond", ")", "Wait", "(", "ctx", "context", ".", "Context", ")", "bool", "{", "cond", ".", "addWaiter", "(", ")", "\n", "//copy signal in lock, avoid data race with Interrupt", "ch", ":=", "cond", ".", "signal", "\n", "//wait should unlock mutex, if not will cause deadlock", "cond", ".", "L", ".", "Unlock", "(", ")", "\n", "defer", "cond", ".", "removeWaiter", "(", ")", "\n", "defer", "cond", ".", "L", ".", "Lock", "(", ")", "\n\n", "select", "{", "case", "_", ",", "ok", ":=", "<-", "ch", ":", "return", "!", "ok", "\n", "case", "<-", "ctx", ".", "Done", "(", ")", ":", "return", "false", "\n", "}", "\n", "}" ]
// Wait waits for a signal, or for the context do be done. Returns true if signaled.
[ "Wait", "waits", "for", "a", "signal", "or", "for", "the", "context", "do", "be", "done", ".", "Returns", "true", "if", "signaled", "." ]
5cc5d37d092a27de00a69e4501f50bb4ead1b304
https://github.com/jolestar/go-commons-pool/blob/5cc5d37d092a27de00a69e4501f50bb4ead1b304/concurrent/cond.go#L46-L61
train
jolestar/go-commons-pool
concurrent/cond.go
Interrupt
func (cond *TimeoutCond) Interrupt() { cond.L.Lock() defer cond.L.Unlock() close(cond.signal) cond.signal = make(chan int, 0) }
go
func (cond *TimeoutCond) Interrupt() { cond.L.Lock() defer cond.L.Unlock() close(cond.signal) cond.signal = make(chan int, 0) }
[ "func", "(", "cond", "*", "TimeoutCond", ")", "Interrupt", "(", ")", "{", "cond", ".", "L", ".", "Lock", "(", ")", "\n", "defer", "cond", ".", "L", ".", "Unlock", "(", ")", "\n", "close", "(", "cond", ".", "signal", ")", "\n", "cond", ".", "signal", "=", "make", "(", "chan", "int", ",", "0", ")", "\n", "}" ]
// Interrupt goroutine wait on this TimeoutCond
[ "Interrupt", "goroutine", "wait", "on", "this", "TimeoutCond" ]
5cc5d37d092a27de00a69e4501f50bb4ead1b304
https://github.com/jolestar/go-commons-pool/blob/5cc5d37d092a27de00a69e4501f50bb4ead1b304/concurrent/cond.go#L72-L77
train
jolestar/go-commons-pool
pool.go
NewObjectPool
func NewObjectPool(ctx context.Context, factory PooledObjectFactory, config *ObjectPoolConfig) *ObjectPool { return NewObjectPoolWithAbandonedConfig(ctx, factory, config, nil) }
go
func NewObjectPool(ctx context.Context, factory PooledObjectFactory, config *ObjectPoolConfig) *ObjectPool { return NewObjectPoolWithAbandonedConfig(ctx, factory, config, nil) }
[ "func", "NewObjectPool", "(", "ctx", "context", ".", "Context", ",", "factory", "PooledObjectFactory", ",", "config", "*", "ObjectPoolConfig", ")", "*", "ObjectPool", "{", "return", "NewObjectPoolWithAbandonedConfig", "(", "ctx", ",", "factory", ",", "config", ",", "nil", ")", "\n", "}" ]
// NewObjectPool return new ObjectPool, init with PooledObjectFactory and ObjectPoolConfig
[ "NewObjectPool", "return", "new", "ObjectPool", "init", "with", "PooledObjectFactory", "and", "ObjectPoolConfig" ]
5cc5d37d092a27de00a69e4501f50bb4ead1b304
https://github.com/jolestar/go-commons-pool/blob/5cc5d37d092a27de00a69e4501f50bb4ead1b304/pool.go#L63-L65
train
jolestar/go-commons-pool
pool.go
NewObjectPoolWithDefaultConfig
func NewObjectPoolWithDefaultConfig(ctx context.Context, factory PooledObjectFactory) *ObjectPool { return NewObjectPool(ctx, factory, NewDefaultPoolConfig()) }
go
func NewObjectPoolWithDefaultConfig(ctx context.Context, factory PooledObjectFactory) *ObjectPool { return NewObjectPool(ctx, factory, NewDefaultPoolConfig()) }
[ "func", "NewObjectPoolWithDefaultConfig", "(", "ctx", "context", ".", "Context", ",", "factory", "PooledObjectFactory", ")", "*", "ObjectPool", "{", "return", "NewObjectPool", "(", "ctx", ",", "factory", ",", "NewDefaultPoolConfig", "(", ")", ")", "\n", "}" ]
// NewObjectPoolWithDefaultConfig return new ObjectPool init with PooledObjectFactory and default config
[ "NewObjectPoolWithDefaultConfig", "return", "new", "ObjectPool", "init", "with", "PooledObjectFactory", "and", "default", "config" ]
5cc5d37d092a27de00a69e4501f50bb4ead1b304
https://github.com/jolestar/go-commons-pool/blob/5cc5d37d092a27de00a69e4501f50bb4ead1b304/pool.go#L68-L70
train
jolestar/go-commons-pool
pool.go
NewObjectPoolWithAbandonedConfig
func NewObjectPoolWithAbandonedConfig(ctx context.Context, factory PooledObjectFactory, config *ObjectPoolConfig, abandonedConfig *AbandonedConfig) *ObjectPool { pool := ObjectPool{factory: factory, Config: config, idleObjects: collections.NewDeque(math.MaxInt32), allObjects: collections.NewSyncMap(), createCount: concurrent.AtomicInteger(0), destroyedByEvictorCount: concurrent.AtomicInteger(0), destroyedCount: concurrent.AtomicInteger(0), AbandonedConfig: abandonedConfig} pool.StartEvictor() return &pool }
go
func NewObjectPoolWithAbandonedConfig(ctx context.Context, factory PooledObjectFactory, config *ObjectPoolConfig, abandonedConfig *AbandonedConfig) *ObjectPool { pool := ObjectPool{factory: factory, Config: config, idleObjects: collections.NewDeque(math.MaxInt32), allObjects: collections.NewSyncMap(), createCount: concurrent.AtomicInteger(0), destroyedByEvictorCount: concurrent.AtomicInteger(0), destroyedCount: concurrent.AtomicInteger(0), AbandonedConfig: abandonedConfig} pool.StartEvictor() return &pool }
[ "func", "NewObjectPoolWithAbandonedConfig", "(", "ctx", "context", ".", "Context", ",", "factory", "PooledObjectFactory", ",", "config", "*", "ObjectPoolConfig", ",", "abandonedConfig", "*", "AbandonedConfig", ")", "*", "ObjectPool", "{", "pool", ":=", "ObjectPool", "{", "factory", ":", "factory", ",", "Config", ":", "config", ",", "idleObjects", ":", "collections", ".", "NewDeque", "(", "math", ".", "MaxInt32", ")", ",", "allObjects", ":", "collections", ".", "NewSyncMap", "(", ")", ",", "createCount", ":", "concurrent", ".", "AtomicInteger", "(", "0", ")", ",", "destroyedByEvictorCount", ":", "concurrent", ".", "AtomicInteger", "(", "0", ")", ",", "destroyedCount", ":", "concurrent", ".", "AtomicInteger", "(", "0", ")", ",", "AbandonedConfig", ":", "abandonedConfig", "}", "\n", "pool", ".", "StartEvictor", "(", ")", "\n", "return", "&", "pool", "\n", "}" ]
// NewObjectPoolWithAbandonedConfig return new ObjectPool init with PooledObjectFactory, ObjectPoolConfig, and AbandonedConfig
[ "NewObjectPoolWithAbandonedConfig", "return", "new", "ObjectPool", "init", "with", "PooledObjectFactory", "ObjectPoolConfig", "and", "AbandonedConfig" ]
5cc5d37d092a27de00a69e4501f50bb4ead1b304
https://github.com/jolestar/go-commons-pool/blob/5cc5d37d092a27de00a69e4501f50bb4ead1b304/pool.go#L73-L83
train
jolestar/go-commons-pool
pool.go
GetNumActive
func (pool *ObjectPool) GetNumActive() int { return pool.allObjects.Size() - pool.idleObjects.Size() }
go
func (pool *ObjectPool) GetNumActive() int { return pool.allObjects.Size() - pool.idleObjects.Size() }
[ "func", "(", "pool", "*", "ObjectPool", ")", "GetNumActive", "(", ")", "int", "{", "return", "pool", ".", "allObjects", ".", "Size", "(", ")", "-", "pool", ".", "idleObjects", ".", "Size", "(", ")", "\n", "}" ]
// GetNumActive return the number of instances currently borrowed from pool.
[ "GetNumActive", "return", "the", "number", "of", "instances", "currently", "borrowed", "from", "pool", "." ]
5cc5d37d092a27de00a69e4501f50bb4ead1b304
https://github.com/jolestar/go-commons-pool/blob/5cc5d37d092a27de00a69e4501f50bb4ead1b304/pool.go#L152-L154
train
jolestar/go-commons-pool
pool.go
IsClosed
func (pool *ObjectPool) IsClosed() bool { pool.closeLock.Lock() defer pool.closeLock.Unlock() // in java commons pool, closed is volatile, golang has not volatile, so use mutex to avoid data race return pool.closed }
go
func (pool *ObjectPool) IsClosed() bool { pool.closeLock.Lock() defer pool.closeLock.Unlock() // in java commons pool, closed is volatile, golang has not volatile, so use mutex to avoid data race return pool.closed }
[ "func", "(", "pool", "*", "ObjectPool", ")", "IsClosed", "(", ")", "bool", "{", "pool", ".", "closeLock", ".", "Lock", "(", ")", "\n", "defer", "pool", ".", "closeLock", ".", "Unlock", "(", ")", "\n", "// in java commons pool, closed is volatile, golang has not volatile, so use mutex to avoid data race", "return", "pool", ".", "closed", "\n", "}" ]
// IsClosed return this pool is closed
[ "IsClosed", "return", "this", "pool", "is", "closed" ]
5cc5d37d092a27de00a69e4501f50bb4ead1b304
https://github.com/jolestar/go-commons-pool/blob/5cc5d37d092a27de00a69e4501f50bb4ead1b304/pool.go#L366-L371
train
jolestar/go-commons-pool
pool.go
Close
func (pool *ObjectPool) Close(ctx context.Context) { if pool.IsClosed() { return } pool.closeLock.Lock() defer pool.closeLock.Unlock() if pool.closed { return } // Stop the evictor before the pool is closed since evict() calls // assertOpen() pool.startEvictor(-1) pool.closed = true // This clear removes any idle objects pool.Clear(ctx) // Release any goroutines that were waiting for an object pool.idleObjects.InterruptTakeWaiters() }
go
func (pool *ObjectPool) Close(ctx context.Context) { if pool.IsClosed() { return } pool.closeLock.Lock() defer pool.closeLock.Unlock() if pool.closed { return } // Stop the evictor before the pool is closed since evict() calls // assertOpen() pool.startEvictor(-1) pool.closed = true // This clear removes any idle objects pool.Clear(ctx) // Release any goroutines that were waiting for an object pool.idleObjects.InterruptTakeWaiters() }
[ "func", "(", "pool", "*", "ObjectPool", ")", "Close", "(", "ctx", "context", ".", "Context", ")", "{", "if", "pool", ".", "IsClosed", "(", ")", "{", "return", "\n", "}", "\n", "pool", ".", "closeLock", ".", "Lock", "(", ")", "\n", "defer", "pool", ".", "closeLock", ".", "Unlock", "(", ")", "\n", "if", "pool", ".", "closed", "{", "return", "\n", "}", "\n\n", "// Stop the evictor before the pool is closed since evict() calls", "// assertOpen()", "pool", ".", "startEvictor", "(", "-", "1", ")", "\n\n", "pool", ".", "closed", "=", "true", "\n", "// This clear removes any idle objects", "pool", ".", "Clear", "(", "ctx", ")", "\n\n", "// Release any goroutines that were waiting for an object", "pool", ".", "idleObjects", ".", "InterruptTakeWaiters", "(", ")", "\n", "}" ]
// Close pool, and free any resources associated with it.
[ "Close", "pool", "and", "free", "any", "resources", "associated", "with", "it", "." ]
5cc5d37d092a27de00a69e4501f50bb4ead1b304
https://github.com/jolestar/go-commons-pool/blob/5cc5d37d092a27de00a69e4501f50bb4ead1b304/pool.go#L482-L502
train
jolestar/go-commons-pool
pool.go
idleIterator
func (pool *ObjectPool) idleIterator() collections.Iterator { if pool.Config.LIFO { return pool.idleObjects.DescendingIterator() } return pool.idleObjects.Iterator() }
go
func (pool *ObjectPool) idleIterator() collections.Iterator { if pool.Config.LIFO { return pool.idleObjects.DescendingIterator() } return pool.idleObjects.Iterator() }
[ "func", "(", "pool", "*", "ObjectPool", ")", "idleIterator", "(", ")", "collections", ".", "Iterator", "{", "if", "pool", ".", "Config", ".", "LIFO", "{", "return", "pool", ".", "idleObjects", ".", "DescendingIterator", "(", ")", "\n", "}", "\n", "return", "pool", ".", "idleObjects", ".", "Iterator", "(", ")", "\n", "}" ]
// idleIterator return pool idleObjects iterator
[ "idleIterator", "return", "pool", "idleObjects", "iterator" ]
5cc5d37d092a27de00a69e4501f50bb4ead1b304
https://github.com/jolestar/go-commons-pool/blob/5cc5d37d092a27de00a69e4501f50bb4ead1b304/pool.go#L561-L566
train
jolestar/go-commons-pool
pool.go
Prefill
func Prefill(ctx context.Context, pool *ObjectPool, count int) { for i := 0; i < count; i++ { pool.AddObject(ctx) } }
go
func Prefill(ctx context.Context, pool *ObjectPool, count int) { for i := 0; i < count; i++ { pool.AddObject(ctx) } }
[ "func", "Prefill", "(", "ctx", "context", ".", "Context", ",", "pool", "*", "ObjectPool", ",", "count", "int", ")", "{", "for", "i", ":=", "0", ";", "i", "<", "count", ";", "i", "++", "{", "pool", ".", "AddObject", "(", "ctx", ")", "\n", "}", "\n", "}" ]
// Prefill is util func for pre fill pool object
[ "Prefill", "is", "util", "func", "for", "pre", "fill", "pool", "object" ]
5cc5d37d092a27de00a69e4501f50bb4ead1b304
https://github.com/jolestar/go-commons-pool/blob/5cc5d37d092a27de00a69e4501f50bb4ead1b304/pool.go#L676-L680
train
jolestar/go-commons-pool
collections/collections.go
Get
func (m *SyncIdentityMap) Get(key interface{}) interface{} { m.RLock() keyPtr := genKey(key) value := m.m[keyPtr] m.RUnlock() return value }
go
func (m *SyncIdentityMap) Get(key interface{}) interface{} { m.RLock() keyPtr := genKey(key) value := m.m[keyPtr] m.RUnlock() return value }
[ "func", "(", "m", "*", "SyncIdentityMap", ")", "Get", "(", "key", "interface", "{", "}", ")", "interface", "{", "}", "{", "m", ".", "RLock", "(", ")", "\n", "keyPtr", ":=", "genKey", "(", "key", ")", "\n", "value", ":=", "m", ".", "m", "[", "keyPtr", "]", "\n", "m", ".", "RUnlock", "(", ")", "\n", "return", "value", "\n", "}" ]
// Get by key
[ "Get", "by", "key" ]
5cc5d37d092a27de00a69e4501f50bb4ead1b304
https://github.com/jolestar/go-commons-pool/blob/5cc5d37d092a27de00a69e4501f50bb4ead1b304/collections/collections.go#L29-L35
train
jolestar/go-commons-pool
collections/collections.go
Put
func (m *SyncIdentityMap) Put(key interface{}, value interface{}) { m.Lock() keyPtr := genKey(key) m.m[keyPtr] = value m.Unlock() }
go
func (m *SyncIdentityMap) Put(key interface{}, value interface{}) { m.Lock() keyPtr := genKey(key) m.m[keyPtr] = value m.Unlock() }
[ "func", "(", "m", "*", "SyncIdentityMap", ")", "Put", "(", "key", "interface", "{", "}", ",", "value", "interface", "{", "}", ")", "{", "m", ".", "Lock", "(", ")", "\n", "keyPtr", ":=", "genKey", "(", "key", ")", "\n", "m", ".", "m", "[", "keyPtr", "]", "=", "value", "\n", "m", ".", "Unlock", "(", ")", "\n", "}" ]
// Put key and value to map
[ "Put", "key", "and", "value", "to", "map" ]
5cc5d37d092a27de00a69e4501f50bb4ead1b304
https://github.com/jolestar/go-commons-pool/blob/5cc5d37d092a27de00a69e4501f50bb4ead1b304/collections/collections.go#L43-L48
train
jolestar/go-commons-pool
collections/collections.go
Remove
func (m *SyncIdentityMap) Remove(key interface{}) { m.Lock() keyPtr := genKey(key) delete(m.m, keyPtr) m.Unlock() }
go
func (m *SyncIdentityMap) Remove(key interface{}) { m.Lock() keyPtr := genKey(key) delete(m.m, keyPtr) m.Unlock() }
[ "func", "(", "m", "*", "SyncIdentityMap", ")", "Remove", "(", "key", "interface", "{", "}", ")", "{", "m", ".", "Lock", "(", ")", "\n", "keyPtr", ":=", "genKey", "(", "key", ")", "\n", "delete", "(", "m", ".", "m", ",", "keyPtr", ")", "\n", "m", ".", "Unlock", "(", ")", "\n", "}" ]
// Remove value by key
[ "Remove", "value", "by", "key" ]
5cc5d37d092a27de00a69e4501f50bb4ead1b304
https://github.com/jolestar/go-commons-pool/blob/5cc5d37d092a27de00a69e4501f50bb4ead1b304/collections/collections.go#L51-L56
train
jolestar/go-commons-pool
collections/collections.go
Size
func (m *SyncIdentityMap) Size() int { m.RLock() defer m.RUnlock() return len(m.m) }
go
func (m *SyncIdentityMap) Size() int { m.RLock() defer m.RUnlock() return len(m.m) }
[ "func", "(", "m", "*", "SyncIdentityMap", ")", "Size", "(", ")", "int", "{", "m", ".", "RLock", "(", ")", "\n", "defer", "m", ".", "RUnlock", "(", ")", "\n", "return", "len", "(", "m", ".", "m", ")", "\n", "}" ]
// Size return map len, and is concurrent safe
[ "Size", "return", "map", "len", "and", "is", "concurrent", "safe" ]
5cc5d37d092a27de00a69e4501f50bb4ead1b304
https://github.com/jolestar/go-commons-pool/blob/5cc5d37d092a27de00a69e4501f50bb4ead1b304/collections/collections.go#L59-L63
train
jolestar/go-commons-pool
collections/collections.go
Values
func (m *SyncIdentityMap) Values() []interface{} { m.RLock() defer m.RUnlock() list := make([]interface{}, len(m.m)) i := 0 for _, v := range m.m { list[i] = v i++ } return list }
go
func (m *SyncIdentityMap) Values() []interface{} { m.RLock() defer m.RUnlock() list := make([]interface{}, len(m.m)) i := 0 for _, v := range m.m { list[i] = v i++ } return list }
[ "func", "(", "m", "*", "SyncIdentityMap", ")", "Values", "(", ")", "[", "]", "interface", "{", "}", "{", "m", ".", "RLock", "(", ")", "\n", "defer", "m", ".", "RUnlock", "(", ")", "\n", "list", ":=", "make", "(", "[", "]", "interface", "{", "}", ",", "len", "(", "m", ".", "m", ")", ")", "\n", "i", ":=", "0", "\n", "for", "_", ",", "v", ":=", "range", "m", ".", "m", "{", "list", "[", "i", "]", "=", "v", "\n", "i", "++", "\n", "}", "\n", "return", "list", "\n", "}" ]
// Values copy all map's value to slice
[ "Values", "copy", "all", "map", "s", "value", "to", "slice" ]
5cc5d37d092a27de00a69e4501f50bb4ead1b304
https://github.com/jolestar/go-commons-pool/blob/5cc5d37d092a27de00a69e4501f50bb4ead1b304/collections/collections.go#L66-L76
train
jolestar/go-commons-pool
object.go
NewPooledObject
func NewPooledObject(object interface{}) *PooledObject { time := time.Now() return &PooledObject{Object: object, state: StateIdle, CreateTime: time, LastUseTime: time, LastBorrowTime: time, LastReturnTime: time} }
go
func NewPooledObject(object interface{}) *PooledObject { time := time.Now() return &PooledObject{Object: object, state: StateIdle, CreateTime: time, LastUseTime: time, LastBorrowTime: time, LastReturnTime: time} }
[ "func", "NewPooledObject", "(", "object", "interface", "{", "}", ")", "*", "PooledObject", "{", "time", ":=", "time", ".", "Now", "(", ")", "\n", "return", "&", "PooledObject", "{", "Object", ":", "object", ",", "state", ":", "StateIdle", ",", "CreateTime", ":", "time", ",", "LastUseTime", ":", "time", ",", "LastBorrowTime", ":", "time", ",", "LastReturnTime", ":", "time", "}", "\n", "}" ]
// NewPooledObject return new init PooledObject
[ "NewPooledObject", "return", "new", "init", "PooledObject" ]
5cc5d37d092a27de00a69e4501f50bb4ead1b304
https://github.com/jolestar/go-commons-pool/blob/5cc5d37d092a27de00a69e4501f50bb4ead1b304/object.go#L61-L64
train
jolestar/go-commons-pool
object.go
GetActiveTime
func (o *PooledObject) GetActiveTime() time.Duration { // Take copies to avoid concurrent issues rTime := o.LastReturnTime bTime := o.LastBorrowTime if rTime.After(bTime) { return rTime.Sub(bTime) } return time.Since(bTime) }
go
func (o *PooledObject) GetActiveTime() time.Duration { // Take copies to avoid concurrent issues rTime := o.LastReturnTime bTime := o.LastBorrowTime if rTime.After(bTime) { return rTime.Sub(bTime) } return time.Since(bTime) }
[ "func", "(", "o", "*", "PooledObject", ")", "GetActiveTime", "(", ")", "time", ".", "Duration", "{", "// Take copies to avoid concurrent issues", "rTime", ":=", "o", ".", "LastReturnTime", "\n", "bTime", ":=", "o", ".", "LastBorrowTime", "\n\n", "if", "rTime", ".", "After", "(", "bTime", ")", "{", "return", "rTime", ".", "Sub", "(", "bTime", ")", "\n", "}", "\n", "return", "time", ".", "Since", "(", "bTime", ")", "\n", "}" ]
// GetActiveTime return the time that this object last spent in the the active state
[ "GetActiveTime", "return", "the", "time", "that", "this", "object", "last", "spent", "in", "the", "the", "active", "state" ]
5cc5d37d092a27de00a69e4501f50bb4ead1b304
https://github.com/jolestar/go-commons-pool/blob/5cc5d37d092a27de00a69e4501f50bb4ead1b304/object.go#L67-L76
train
jolestar/go-commons-pool
object.go
GetIdleTime
func (o *PooledObject) GetIdleTime() time.Duration { elapsed := time.Since(o.LastReturnTime) // elapsed may be negative if: // - another goroutine updates lastReturnTime during the calculation window if elapsed >= 0 { return elapsed } return 0 }
go
func (o *PooledObject) GetIdleTime() time.Duration { elapsed := time.Since(o.LastReturnTime) // elapsed may be negative if: // - another goroutine updates lastReturnTime during the calculation window if elapsed >= 0 { return elapsed } return 0 }
[ "func", "(", "o", "*", "PooledObject", ")", "GetIdleTime", "(", ")", "time", ".", "Duration", "{", "elapsed", ":=", "time", ".", "Since", "(", "o", ".", "LastReturnTime", ")", "\n", "// elapsed may be negative if:", "// - another goroutine updates lastReturnTime during the calculation window", "if", "elapsed", ">=", "0", "{", "return", "elapsed", "\n", "}", "\n", "return", "0", "\n", "}" ]
// GetIdleTime the time that this object last spend in the the idle state
[ "GetIdleTime", "the", "time", "that", "this", "object", "last", "spend", "in", "the", "the", "idle", "state" ]
5cc5d37d092a27de00a69e4501f50bb4ead1b304
https://github.com/jolestar/go-commons-pool/blob/5cc5d37d092a27de00a69e4501f50bb4ead1b304/object.go#L79-L87
train
jolestar/go-commons-pool
object.go
GetLastUsedTime
func (o *PooledObject) GetLastUsedTime() time.Time { trackedUse, ok := o.Object.(TrackedUse) if ok && trackedUse.GetLastUsed().After(o.LastUseTime) { return trackedUse.GetLastUsed() } return o.LastUseTime }
go
func (o *PooledObject) GetLastUsedTime() time.Time { trackedUse, ok := o.Object.(TrackedUse) if ok && trackedUse.GetLastUsed().After(o.LastUseTime) { return trackedUse.GetLastUsed() } return o.LastUseTime }
[ "func", "(", "o", "*", "PooledObject", ")", "GetLastUsedTime", "(", ")", "time", ".", "Time", "{", "trackedUse", ",", "ok", ":=", "o", ".", "Object", ".", "(", "TrackedUse", ")", "\n", "if", "ok", "&&", "trackedUse", ".", "GetLastUsed", "(", ")", ".", "After", "(", "o", ".", "LastUseTime", ")", "{", "return", "trackedUse", ".", "GetLastUsed", "(", ")", "\n", "}", "\n", "return", "o", ".", "LastUseTime", "\n", "}" ]
// GetLastUsedTime return an estimate of the last time this object was used.
[ "GetLastUsedTime", "return", "an", "estimate", "of", "the", "last", "time", "this", "object", "was", "used", "." ]
5cc5d37d092a27de00a69e4501f50bb4ead1b304
https://github.com/jolestar/go-commons-pool/blob/5cc5d37d092a27de00a69e4501f50bb4ead1b304/object.go#L90-L96
train
jolestar/go-commons-pool
object.go
Allocate
func (o *PooledObject) Allocate() bool { o.lock.Lock() result := o.doAllocate() o.lock.Unlock() return result }
go
func (o *PooledObject) Allocate() bool { o.lock.Lock() result := o.doAllocate() o.lock.Unlock() return result }
[ "func", "(", "o", "*", "PooledObject", ")", "Allocate", "(", ")", "bool", "{", "o", ".", "lock", ".", "Lock", "(", ")", "\n", "result", ":=", "o", ".", "doAllocate", "(", ")", "\n", "o", ".", "lock", ".", "Unlock", "(", ")", "\n", "return", "result", "\n", "}" ]
// Allocate this object
[ "Allocate", "this", "object" ]
5cc5d37d092a27de00a69e4501f50bb4ead1b304
https://github.com/jolestar/go-commons-pool/blob/5cc5d37d092a27de00a69e4501f50bb4ead1b304/object.go#L119-L124
train
jolestar/go-commons-pool
object.go
Deallocate
func (o *PooledObject) Deallocate() bool { o.lock.Lock() result := o.doDeallocate() o.lock.Unlock() return result }
go
func (o *PooledObject) Deallocate() bool { o.lock.Lock() result := o.doDeallocate() o.lock.Unlock() return result }
[ "func", "(", "o", "*", "PooledObject", ")", "Deallocate", "(", ")", "bool", "{", "o", ".", "lock", ".", "Lock", "(", ")", "\n", "result", ":=", "o", ".", "doDeallocate", "(", ")", "\n", "o", ".", "lock", ".", "Unlock", "(", ")", "\n", "return", "result", "\n", "}" ]
// Deallocate this object
[ "Deallocate", "this", "object" ]
5cc5d37d092a27de00a69e4501f50bb4ead1b304
https://github.com/jolestar/go-commons-pool/blob/5cc5d37d092a27de00a69e4501f50bb4ead1b304/object.go#L138-L143
train
jolestar/go-commons-pool
object.go
Invalidate
func (o *PooledObject) Invalidate() { o.lock.Lock() o.invalidate() o.lock.Unlock() }
go
func (o *PooledObject) Invalidate() { o.lock.Lock() o.invalidate() o.lock.Unlock() }
[ "func", "(", "o", "*", "PooledObject", ")", "Invalidate", "(", ")", "{", "o", ".", "lock", ".", "Lock", "(", ")", "\n", "o", ".", "invalidate", "(", ")", "\n", "o", ".", "lock", ".", "Unlock", "(", ")", "\n", "}" ]
// Invalidate this object
[ "Invalidate", "this", "object" ]
5cc5d37d092a27de00a69e4501f50bb4ead1b304
https://github.com/jolestar/go-commons-pool/blob/5cc5d37d092a27de00a69e4501f50bb4ead1b304/object.go#L146-L150
train
jolestar/go-commons-pool
object.go
GetState
func (o *PooledObject) GetState() PooledObjectState { o.lock.Lock() defer o.lock.Unlock() return o.state }
go
func (o *PooledObject) GetState() PooledObjectState { o.lock.Lock() defer o.lock.Unlock() return o.state }
[ "func", "(", "o", "*", "PooledObject", ")", "GetState", "(", ")", "PooledObjectState", "{", "o", ".", "lock", ".", "Lock", "(", ")", "\n", "defer", "o", ".", "lock", ".", "Unlock", "(", ")", "\n", "return", "o", ".", "state", "\n", "}" ]
// GetState return current state of this object
[ "GetState", "return", "current", "state", "of", "this", "object" ]
5cc5d37d092a27de00a69e4501f50bb4ead1b304
https://github.com/jolestar/go-commons-pool/blob/5cc5d37d092a27de00a69e4501f50bb4ead1b304/object.go#L157-L161
train
jolestar/go-commons-pool
object.go
MarkAbandoned
func (o *PooledObject) MarkAbandoned() { o.lock.Lock() o.markAbandoned() o.lock.Unlock() }
go
func (o *PooledObject) MarkAbandoned() { o.lock.Lock() o.markAbandoned() o.lock.Unlock() }
[ "func", "(", "o", "*", "PooledObject", ")", "MarkAbandoned", "(", ")", "{", "o", ".", "lock", ".", "Lock", "(", ")", "\n", "o", ".", "markAbandoned", "(", ")", "\n", "o", ".", "lock", ".", "Unlock", "(", ")", "\n", "}" ]
// MarkAbandoned mark this object to Abandoned state
[ "MarkAbandoned", "mark", "this", "object", "to", "Abandoned", "state" ]
5cc5d37d092a27de00a69e4501f50bb4ead1b304
https://github.com/jolestar/go-commons-pool/blob/5cc5d37d092a27de00a69e4501f50bb4ead1b304/object.go#L164-L168
train
jolestar/go-commons-pool
object.go
MarkReturning
func (o *PooledObject) MarkReturning() { o.lock.Lock() o.markReturning() o.lock.Unlock() }
go
func (o *PooledObject) MarkReturning() { o.lock.Lock() o.markReturning() o.lock.Unlock() }
[ "func", "(", "o", "*", "PooledObject", ")", "MarkReturning", "(", ")", "{", "o", ".", "lock", ".", "Lock", "(", ")", "\n", "o", ".", "markReturning", "(", ")", "\n", "o", ".", "lock", ".", "Unlock", "(", ")", "\n", "}" ]
// MarkReturning mark this object to Returning state
[ "MarkReturning", "mark", "this", "object", "to", "Returning", "state" ]
5cc5d37d092a27de00a69e4501f50bb4ead1b304
https://github.com/jolestar/go-commons-pool/blob/5cc5d37d092a27de00a69e4501f50bb4ead1b304/object.go#L175-L179
train
jolestar/go-commons-pool
collections/queue.go
NewDeque
func NewDeque(capacity int) *LinkedBlockingDeque { if capacity < 0 { panic(errors.New("capacity must > 0")) } lock := new(sync.Mutex) return &LinkedBlockingDeque{capacity: capacity, lock: lock, notEmpty: concurrent.NewTimeoutCond(lock), notFull: concurrent.NewTimeoutCond(lock)} }
go
func NewDeque(capacity int) *LinkedBlockingDeque { if capacity < 0 { panic(errors.New("capacity must > 0")) } lock := new(sync.Mutex) return &LinkedBlockingDeque{capacity: capacity, lock: lock, notEmpty: concurrent.NewTimeoutCond(lock), notFull: concurrent.NewTimeoutCond(lock)} }
[ "func", "NewDeque", "(", "capacity", "int", ")", "*", "LinkedBlockingDeque", "{", "if", "capacity", "<", "0", "{", "panic", "(", "errors", ".", "New", "(", "\"", "\"", ")", ")", "\n", "}", "\n", "lock", ":=", "new", "(", "sync", ".", "Mutex", ")", "\n", "return", "&", "LinkedBlockingDeque", "{", "capacity", ":", "capacity", ",", "lock", ":", "lock", ",", "notEmpty", ":", "concurrent", ".", "NewTimeoutCond", "(", "lock", ")", ",", "notFull", ":", "concurrent", ".", "NewTimeoutCond", "(", "lock", ")", "}", "\n", "}" ]
// NewDeque return a LinkedBlockingDeque with init capacity
[ "NewDeque", "return", "a", "LinkedBlockingDeque", "with", "init", "capacity" ]
5cc5d37d092a27de00a69e4501f50bb4ead1b304
https://github.com/jolestar/go-commons-pool/blob/5cc5d37d092a27de00a69e4501f50bb4ead1b304/collections/queue.go#L77-L83
train
jolestar/go-commons-pool
collections/queue.go
linkFirst
func (q *LinkedBlockingDeque) linkFirst(e interface{}) bool { if q.count >= q.capacity { return false } f := q.first x := newNode(e, nil, f) q.first = x if q.last == nil { q.last = x } else { f.prev = x } q.count = q.count + 1 q.notEmpty.Signal() return true }
go
func (q *LinkedBlockingDeque) linkFirst(e interface{}) bool { if q.count >= q.capacity { return false } f := q.first x := newNode(e, nil, f) q.first = x if q.last == nil { q.last = x } else { f.prev = x } q.count = q.count + 1 q.notEmpty.Signal() return true }
[ "func", "(", "q", "*", "LinkedBlockingDeque", ")", "linkFirst", "(", "e", "interface", "{", "}", ")", "bool", "{", "if", "q", ".", "count", ">=", "q", ".", "capacity", "{", "return", "false", "\n", "}", "\n", "f", ":=", "q", ".", "first", "\n", "x", ":=", "newNode", "(", "e", ",", "nil", ",", "f", ")", "\n", "q", ".", "first", "=", "x", "\n", "if", "q", ".", "last", "==", "nil", "{", "q", ".", "last", "=", "x", "\n", "}", "else", "{", "f", ".", "prev", "=", "x", "\n", "}", "\n", "q", ".", "count", "=", "q", ".", "count", "+", "1", "\n", "q", ".", "notEmpty", ".", "Signal", "(", ")", "\n", "return", "true", "\n", "}" ]
//Links provided element as first element, or returns false if full. //return true if successful, otherwise false
[ "Links", "provided", "element", "as", "first", "element", "or", "returns", "false", "if", "full", ".", "return", "true", "if", "successful", "otherwise", "false" ]
5cc5d37d092a27de00a69e4501f50bb4ead1b304
https://github.com/jolestar/go-commons-pool/blob/5cc5d37d092a27de00a69e4501f50bb4ead1b304/collections/queue.go#L87-L102
train
jolestar/go-commons-pool
collections/queue.go
linkLast
func (q *LinkedBlockingDeque) linkLast(e interface{}) bool { // assert lock.isHeldByCurrentThread(); if q.count >= q.capacity { return false } l := q.last x := newNode(e, l, nil) q.last = x if q.first == nil { q.first = x } else { l.next = x } q.count = q.count + 1 q.notEmpty.Signal() return true }
go
func (q *LinkedBlockingDeque) linkLast(e interface{}) bool { // assert lock.isHeldByCurrentThread(); if q.count >= q.capacity { return false } l := q.last x := newNode(e, l, nil) q.last = x if q.first == nil { q.first = x } else { l.next = x } q.count = q.count + 1 q.notEmpty.Signal() return true }
[ "func", "(", "q", "*", "LinkedBlockingDeque", ")", "linkLast", "(", "e", "interface", "{", "}", ")", "bool", "{", "// assert lock.isHeldByCurrentThread();", "if", "q", ".", "count", ">=", "q", ".", "capacity", "{", "return", "false", "\n", "}", "\n", "l", ":=", "q", ".", "last", "\n", "x", ":=", "newNode", "(", "e", ",", "l", ",", "nil", ")", "\n", "q", ".", "last", "=", "x", "\n", "if", "q", ".", "first", "==", "nil", "{", "q", ".", "first", "=", "x", "\n", "}", "else", "{", "l", ".", "next", "=", "x", "\n", "}", "\n", "q", ".", "count", "=", "q", ".", "count", "+", "1", "\n", "q", ".", "notEmpty", ".", "Signal", "(", ")", "\n", "return", "true", "\n", "}" ]
//Links provided element as last element, or returns false if full. //return true} if successful, otherwise false
[ "Links", "provided", "element", "as", "last", "element", "or", "returns", "false", "if", "full", ".", "return", "true", "}", "if", "successful", "otherwise", "false" ]
5cc5d37d092a27de00a69e4501f50bb4ead1b304
https://github.com/jolestar/go-commons-pool/blob/5cc5d37d092a27de00a69e4501f50bb4ead1b304/collections/queue.go#L106-L122
train
jolestar/go-commons-pool
collections/queue.go
unlinkFirst
func (q *LinkedBlockingDeque) unlinkFirst() interface{} { // assert lock.isHeldByCurrentThread(); f := q.first if f == nil { return nil } n := f.next item := f.item f.item = nil f.next = f //help GC q.first = n if n == nil { q.last = nil } else { n.prev = nil } q.count = q.count - 1 q.notFull.Signal() return item }
go
func (q *LinkedBlockingDeque) unlinkFirst() interface{} { // assert lock.isHeldByCurrentThread(); f := q.first if f == nil { return nil } n := f.next item := f.item f.item = nil f.next = f //help GC q.first = n if n == nil { q.last = nil } else { n.prev = nil } q.count = q.count - 1 q.notFull.Signal() return item }
[ "func", "(", "q", "*", "LinkedBlockingDeque", ")", "unlinkFirst", "(", ")", "interface", "{", "}", "{", "// assert lock.isHeldByCurrentThread();", "f", ":=", "q", ".", "first", "\n", "if", "f", "==", "nil", "{", "return", "nil", "\n", "}", "\n", "n", ":=", "f", ".", "next", "\n", "item", ":=", "f", ".", "item", "\n", "f", ".", "item", "=", "nil", "\n", "f", ".", "next", "=", "f", "//help GC", "\n", "q", ".", "first", "=", "n", "\n", "if", "n", "==", "nil", "{", "q", ".", "last", "=", "nil", "\n", "}", "else", "{", "n", ".", "prev", "=", "nil", "\n", "}", "\n", "q", ".", "count", "=", "q", ".", "count", "-", "1", "\n", "q", ".", "notFull", ".", "Signal", "(", ")", "\n", "return", "item", "\n", "}" ]
//Removes and returns the first element, or nil if empty.
[ "Removes", "and", "returns", "the", "first", "element", "or", "nil", "if", "empty", "." ]
5cc5d37d092a27de00a69e4501f50bb4ead1b304
https://github.com/jolestar/go-commons-pool/blob/5cc5d37d092a27de00a69e4501f50bb4ead1b304/collections/queue.go#L125-L144
train
jolestar/go-commons-pool
collections/queue.go
unlinkLast
func (q *LinkedBlockingDeque) unlinkLast() interface{} { l := q.last if l == nil { return nil } p := l.prev item := l.item l.item = nil l.prev = l // help GC q.last = p if p == nil { q.first = nil } else { p.next = nil } q.count = q.count - 1 q.notFull.Signal() return item }
go
func (q *LinkedBlockingDeque) unlinkLast() interface{} { l := q.last if l == nil { return nil } p := l.prev item := l.item l.item = nil l.prev = l // help GC q.last = p if p == nil { q.first = nil } else { p.next = nil } q.count = q.count - 1 q.notFull.Signal() return item }
[ "func", "(", "q", "*", "LinkedBlockingDeque", ")", "unlinkLast", "(", ")", "interface", "{", "}", "{", "l", ":=", "q", ".", "last", "\n", "if", "l", "==", "nil", "{", "return", "nil", "\n", "}", "\n", "p", ":=", "l", ".", "prev", "\n", "item", ":=", "l", ".", "item", "\n", "l", ".", "item", "=", "nil", "\n", "l", ".", "prev", "=", "l", "// help GC", "\n", "q", ".", "last", "=", "p", "\n", "if", "p", "==", "nil", "{", "q", ".", "first", "=", "nil", "\n", "}", "else", "{", "p", ".", "next", "=", "nil", "\n", "}", "\n", "q", ".", "count", "=", "q", ".", "count", "-", "1", "\n", "q", ".", "notFull", ".", "Signal", "(", ")", "\n", "return", "item", "\n", "}" ]
//Removes and returns the last element, or nil if empty.
[ "Removes", "and", "returns", "the", "last", "element", "or", "nil", "if", "empty", "." ]
5cc5d37d092a27de00a69e4501f50bb4ead1b304
https://github.com/jolestar/go-commons-pool/blob/5cc5d37d092a27de00a69e4501f50bb4ead1b304/collections/queue.go#L147-L165
train
jolestar/go-commons-pool
collections/queue.go
unlink
func (q *LinkedBlockingDeque) unlink(x *Node) { // assert lock.isHeldByCurrentThread(); p := x.prev n := x.next if p == nil { q.unlinkFirst() } else if n == nil { q.unlinkLast() } else { p.next = n n.prev = p x.item = nil // Don't mess with x's links. They may still be in use by // an iterator. q.count = q.count - 1 q.notFull.Signal() } }
go
func (q *LinkedBlockingDeque) unlink(x *Node) { // assert lock.isHeldByCurrentThread(); p := x.prev n := x.next if p == nil { q.unlinkFirst() } else if n == nil { q.unlinkLast() } else { p.next = n n.prev = p x.item = nil // Don't mess with x's links. They may still be in use by // an iterator. q.count = q.count - 1 q.notFull.Signal() } }
[ "func", "(", "q", "*", "LinkedBlockingDeque", ")", "unlink", "(", "x", "*", "Node", ")", "{", "// assert lock.isHeldByCurrentThread();", "p", ":=", "x", ".", "prev", "\n", "n", ":=", "x", ".", "next", "\n", "if", "p", "==", "nil", "{", "q", ".", "unlinkFirst", "(", ")", "\n", "}", "else", "if", "n", "==", "nil", "{", "q", ".", "unlinkLast", "(", ")", "\n", "}", "else", "{", "p", ".", "next", "=", "n", "\n", "n", ".", "prev", "=", "p", "\n", "x", ".", "item", "=", "nil", "\n", "// Don't mess with x's links. They may still be in use by", "// an iterator.", "q", ".", "count", "=", "q", ".", "count", "-", "1", "\n", "q", ".", "notFull", ".", "Signal", "(", ")", "\n", "}", "\n", "}" ]
//Unlink the provided node.
[ "Unlink", "the", "provided", "node", "." ]
5cc5d37d092a27de00a69e4501f50bb4ead1b304
https://github.com/jolestar/go-commons-pool/blob/5cc5d37d092a27de00a69e4501f50bb4ead1b304/collections/queue.go#L168-L185
train
jolestar/go-commons-pool
collections/queue.go
AddFirst
func (q *LinkedBlockingDeque) AddFirst(e interface{}) error { if e == nil { return errors.New("e is nil") } if !q.OfferFirst(e) { return errors.New("Deque full") } return nil }
go
func (q *LinkedBlockingDeque) AddFirst(e interface{}) error { if e == nil { return errors.New("e is nil") } if !q.OfferFirst(e) { return errors.New("Deque full") } return nil }
[ "func", "(", "q", "*", "LinkedBlockingDeque", ")", "AddFirst", "(", "e", "interface", "{", "}", ")", "error", "{", "if", "e", "==", "nil", "{", "return", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "}", "\n", "if", "!", "q", ".", "OfferFirst", "(", "e", ")", "{", "return", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// AddFirst inserts the specified element at the front of this deque if it is // possible to do so immediately without violating capacity restrictions, // return error if no space is currently available.
[ "AddFirst", "inserts", "the", "specified", "element", "at", "the", "front", "of", "this", "deque", "if", "it", "is", "possible", "to", "do", "so", "immediately", "without", "violating", "capacity", "restrictions", "return", "error", "if", "no", "space", "is", "currently", "available", "." ]
5cc5d37d092a27de00a69e4501f50bb4ead1b304
https://github.com/jolestar/go-commons-pool/blob/5cc5d37d092a27de00a69e4501f50bb4ead1b304/collections/queue.go#L190-L198
train
jolestar/go-commons-pool
collections/queue.go
AddLast
func (q *LinkedBlockingDeque) AddLast(e interface{}) error { if e == nil { return errors.New("e is nil") } if !q.OfferLast(e) { return errors.New("Deque full") } return nil }
go
func (q *LinkedBlockingDeque) AddLast(e interface{}) error { if e == nil { return errors.New("e is nil") } if !q.OfferLast(e) { return errors.New("Deque full") } return nil }
[ "func", "(", "q", "*", "LinkedBlockingDeque", ")", "AddLast", "(", "e", "interface", "{", "}", ")", "error", "{", "if", "e", "==", "nil", "{", "return", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "}", "\n", "if", "!", "q", ".", "OfferLast", "(", "e", ")", "{", "return", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// AddLast inserts the specified element at the end of this deque if it is // possible to do so immediately without violating capacity restrictions, // return error if no space is currently available.
[ "AddLast", "inserts", "the", "specified", "element", "at", "the", "end", "of", "this", "deque", "if", "it", "is", "possible", "to", "do", "so", "immediately", "without", "violating", "capacity", "restrictions", "return", "error", "if", "no", "space", "is", "currently", "available", "." ]
5cc5d37d092a27de00a69e4501f50bb4ead1b304
https://github.com/jolestar/go-commons-pool/blob/5cc5d37d092a27de00a69e4501f50bb4ead1b304/collections/queue.go#L203-L211
train
jolestar/go-commons-pool
collections/queue.go
OfferFirst
func (q *LinkedBlockingDeque) OfferFirst(e interface{}) bool { if e == nil { return false } q.lock.Lock() result := q.linkFirst(e) q.lock.Unlock() return result }
go
func (q *LinkedBlockingDeque) OfferFirst(e interface{}) bool { if e == nil { return false } q.lock.Lock() result := q.linkFirst(e) q.lock.Unlock() return result }
[ "func", "(", "q", "*", "LinkedBlockingDeque", ")", "OfferFirst", "(", "e", "interface", "{", "}", ")", "bool", "{", "if", "e", "==", "nil", "{", "return", "false", "\n", "}", "\n", "q", ".", "lock", ".", "Lock", "(", ")", "\n", "result", ":=", "q", ".", "linkFirst", "(", "e", ")", "\n", "q", ".", "lock", ".", "Unlock", "(", ")", "\n", "return", "result", "\n", "}" ]
// OfferFirst inserts the specified element at the front of this deque unless it would violate capacity restrictions. // return if the element was added to this deque
[ "OfferFirst", "inserts", "the", "specified", "element", "at", "the", "front", "of", "this", "deque", "unless", "it", "would", "violate", "capacity", "restrictions", ".", "return", "if", "the", "element", "was", "added", "to", "this", "deque" ]
5cc5d37d092a27de00a69e4501f50bb4ead1b304
https://github.com/jolestar/go-commons-pool/blob/5cc5d37d092a27de00a69e4501f50bb4ead1b304/collections/queue.go#L215-L223
train
jolestar/go-commons-pool
collections/queue.go
OfferLast
func (q *LinkedBlockingDeque) OfferLast(e interface{}) bool { if e == nil { return false } q.lock.Lock() result := q.linkLast(e) q.lock.Unlock() return result }
go
func (q *LinkedBlockingDeque) OfferLast(e interface{}) bool { if e == nil { return false } q.lock.Lock() result := q.linkLast(e) q.lock.Unlock() return result }
[ "func", "(", "q", "*", "LinkedBlockingDeque", ")", "OfferLast", "(", "e", "interface", "{", "}", ")", "bool", "{", "if", "e", "==", "nil", "{", "return", "false", "\n", "}", "\n", "q", ".", "lock", ".", "Lock", "(", ")", "\n", "result", ":=", "q", ".", "linkLast", "(", "e", ")", "\n", "q", ".", "lock", ".", "Unlock", "(", ")", "\n", "return", "result", "\n", "}" ]
// OfferLast inserts the specified element at the end of this deque unless it would violate capacity restrictions. // return if the element was added to this deque
[ "OfferLast", "inserts", "the", "specified", "element", "at", "the", "end", "of", "this", "deque", "unless", "it", "would", "violate", "capacity", "restrictions", ".", "return", "if", "the", "element", "was", "added", "to", "this", "deque" ]
5cc5d37d092a27de00a69e4501f50bb4ead1b304
https://github.com/jolestar/go-commons-pool/blob/5cc5d37d092a27de00a69e4501f50bb4ead1b304/collections/queue.go#L227-L235
train
jolestar/go-commons-pool
collections/queue.go
PutFirst
func (q *LinkedBlockingDeque) PutFirst(ctx context.Context, e interface{}) { if e == nil { return } q.lock.Lock() defer q.lock.Unlock() for !q.linkFirst(e) { q.notFull.Wait(ctx) } }
go
func (q *LinkedBlockingDeque) PutFirst(ctx context.Context, e interface{}) { if e == nil { return } q.lock.Lock() defer q.lock.Unlock() for !q.linkFirst(e) { q.notFull.Wait(ctx) } }
[ "func", "(", "q", "*", "LinkedBlockingDeque", ")", "PutFirst", "(", "ctx", "context", ".", "Context", ",", "e", "interface", "{", "}", ")", "{", "if", "e", "==", "nil", "{", "return", "\n", "}", "\n", "q", ".", "lock", ".", "Lock", "(", ")", "\n", "defer", "q", ".", "lock", ".", "Unlock", "(", ")", "\n", "for", "!", "q", ".", "linkFirst", "(", "e", ")", "{", "q", ".", "notFull", ".", "Wait", "(", "ctx", ")", "\n", "}", "\n", "}" ]
// PutFirst link the provided element as the first in the queue, waiting until there // is space to do so if the queue is full.
[ "PutFirst", "link", "the", "provided", "element", "as", "the", "first", "in", "the", "queue", "waiting", "until", "there", "is", "space", "to", "do", "so", "if", "the", "queue", "is", "full", "." ]
5cc5d37d092a27de00a69e4501f50bb4ead1b304
https://github.com/jolestar/go-commons-pool/blob/5cc5d37d092a27de00a69e4501f50bb4ead1b304/collections/queue.go#L239-L248
train
jolestar/go-commons-pool
collections/queue.go
PutLast
func (q *LinkedBlockingDeque) PutLast(ctx context.Context, e interface{}) { if e == nil { return } q.lock.Lock() defer q.lock.Unlock() for !q.linkLast(e) { q.notFull.Wait(ctx) } }
go
func (q *LinkedBlockingDeque) PutLast(ctx context.Context, e interface{}) { if e == nil { return } q.lock.Lock() defer q.lock.Unlock() for !q.linkLast(e) { q.notFull.Wait(ctx) } }
[ "func", "(", "q", "*", "LinkedBlockingDeque", ")", "PutLast", "(", "ctx", "context", ".", "Context", ",", "e", "interface", "{", "}", ")", "{", "if", "e", "==", "nil", "{", "return", "\n", "}", "\n", "q", ".", "lock", ".", "Lock", "(", ")", "\n", "defer", "q", ".", "lock", ".", "Unlock", "(", ")", "\n", "for", "!", "q", ".", "linkLast", "(", "e", ")", "{", "q", ".", "notFull", ".", "Wait", "(", "ctx", ")", "\n", "}", "\n", "}" ]
// PutLast Link the provided element as the last in the queue, waiting until there // is space to do so if the queue is full.
[ "PutLast", "Link", "the", "provided", "element", "as", "the", "last", "in", "the", "queue", "waiting", "until", "there", "is", "space", "to", "do", "so", "if", "the", "queue", "is", "full", "." ]
5cc5d37d092a27de00a69e4501f50bb4ead1b304
https://github.com/jolestar/go-commons-pool/blob/5cc5d37d092a27de00a69e4501f50bb4ead1b304/collections/queue.go#L252-L261
train
jolestar/go-commons-pool
collections/queue.go
PollFirst
func (q *LinkedBlockingDeque) PollFirst() (e interface{}) { q.lock.Lock() result := q.unlinkFirst() q.lock.Unlock() return result }
go
func (q *LinkedBlockingDeque) PollFirst() (e interface{}) { q.lock.Lock() result := q.unlinkFirst() q.lock.Unlock() return result }
[ "func", "(", "q", "*", "LinkedBlockingDeque", ")", "PollFirst", "(", ")", "(", "e", "interface", "{", "}", ")", "{", "q", ".", "lock", ".", "Lock", "(", ")", "\n", "result", ":=", "q", ".", "unlinkFirst", "(", ")", "\n", "q", ".", "lock", ".", "Unlock", "(", ")", "\n", "return", "result", "\n", "}" ]
// PollFirst retrieves and removes the first element of this deque, // or returns nil if this deque is empty.
[ "PollFirst", "retrieves", "and", "removes", "the", "first", "element", "of", "this", "deque", "or", "returns", "nil", "if", "this", "deque", "is", "empty", "." ]
5cc5d37d092a27de00a69e4501f50bb4ead1b304
https://github.com/jolestar/go-commons-pool/blob/5cc5d37d092a27de00a69e4501f50bb4ead1b304/collections/queue.go#L265-L270
train
jolestar/go-commons-pool
collections/queue.go
PollLast
func (q *LinkedBlockingDeque) PollLast() interface{} { q.lock.Lock() result := q.unlinkLast() q.lock.Unlock() return result }
go
func (q *LinkedBlockingDeque) PollLast() interface{} { q.lock.Lock() result := q.unlinkLast() q.lock.Unlock() return result }
[ "func", "(", "q", "*", "LinkedBlockingDeque", ")", "PollLast", "(", ")", "interface", "{", "}", "{", "q", ".", "lock", ".", "Lock", "(", ")", "\n", "result", ":=", "q", ".", "unlinkLast", "(", ")", "\n", "q", ".", "lock", ".", "Unlock", "(", ")", "\n", "return", "result", "\n", "}" ]
// PollLast retrieves and removes the last element of this deque, // or returns nil if this deque is empty.
[ "PollLast", "retrieves", "and", "removes", "the", "last", "element", "of", "this", "deque", "or", "returns", "nil", "if", "this", "deque", "is", "empty", "." ]
5cc5d37d092a27de00a69e4501f50bb4ead1b304
https://github.com/jolestar/go-commons-pool/blob/5cc5d37d092a27de00a69e4501f50bb4ead1b304/collections/queue.go#L296-L301
train
jolestar/go-commons-pool
collections/queue.go
TakeFirst
func (q *LinkedBlockingDeque) TakeFirst(ctx context.Context) (interface{}, error) { q.lock.Lock() defer q.lock.Unlock() var x interface{} interrupt := false for x = q.unlinkFirst(); x == nil; x = q.unlinkFirst() { if interrupt { return nil, NewInterruptedErr() } interrupt = q.notEmpty.Wait(ctx) } return x, nil }
go
func (q *LinkedBlockingDeque) TakeFirst(ctx context.Context) (interface{}, error) { q.lock.Lock() defer q.lock.Unlock() var x interface{} interrupt := false for x = q.unlinkFirst(); x == nil; x = q.unlinkFirst() { if interrupt { return nil, NewInterruptedErr() } interrupt = q.notEmpty.Wait(ctx) } return x, nil }
[ "func", "(", "q", "*", "LinkedBlockingDeque", ")", "TakeFirst", "(", "ctx", "context", ".", "Context", ")", "(", "interface", "{", "}", ",", "error", ")", "{", "q", ".", "lock", ".", "Lock", "(", ")", "\n", "defer", "q", ".", "lock", ".", "Unlock", "(", ")", "\n", "var", "x", "interface", "{", "}", "\n", "interrupt", ":=", "false", "\n", "for", "x", "=", "q", ".", "unlinkFirst", "(", ")", ";", "x", "==", "nil", ";", "x", "=", "q", ".", "unlinkFirst", "(", ")", "{", "if", "interrupt", "{", "return", "nil", ",", "NewInterruptedErr", "(", ")", "\n", "}", "\n", "interrupt", "=", "q", ".", "notEmpty", ".", "Wait", "(", "ctx", ")", "\n", "}", "\n", "return", "x", ",", "nil", "\n", "}" ]
// TakeFirst unlink the first element in the queue, waiting until there is an element // to unlink if the queue is empty. // return NewInterruptedErr if wait condition is interrupted
[ "TakeFirst", "unlink", "the", "first", "element", "in", "the", "queue", "waiting", "until", "there", "is", "an", "element", "to", "unlink", "if", "the", "queue", "is", "empty", ".", "return", "NewInterruptedErr", "if", "wait", "condition", "is", "interrupted" ]
5cc5d37d092a27de00a69e4501f50bb4ead1b304
https://github.com/jolestar/go-commons-pool/blob/5cc5d37d092a27de00a69e4501f50bb4ead1b304/collections/queue.go#L328-L340
train
jolestar/go-commons-pool
collections/queue.go
PeekFirst
func (q *LinkedBlockingDeque) PeekFirst() interface{} { var result interface{} q.lock.Lock() if q.first == nil { result = nil } else { result = q.first.item } q.lock.Unlock() return result }
go
func (q *LinkedBlockingDeque) PeekFirst() interface{} { var result interface{} q.lock.Lock() if q.first == nil { result = nil } else { result = q.first.item } q.lock.Unlock() return result }
[ "func", "(", "q", "*", "LinkedBlockingDeque", ")", "PeekFirst", "(", ")", "interface", "{", "}", "{", "var", "result", "interface", "{", "}", "\n", "q", ".", "lock", ".", "Lock", "(", ")", "\n", "if", "q", ".", "first", "==", "nil", "{", "result", "=", "nil", "\n", "}", "else", "{", "result", "=", "q", ".", "first", ".", "item", "\n", "}", "\n", "q", ".", "lock", ".", "Unlock", "(", ")", "\n", "return", "result", "\n", "}" ]
// PeekFirst retrieves, but does not remove, the first element of this deque, // or returns nil if this deque is empty.
[ "PeekFirst", "retrieves", "but", "does", "not", "remove", "the", "first", "element", "of", "this", "deque", "or", "returns", "nil", "if", "this", "deque", "is", "empty", "." ]
5cc5d37d092a27de00a69e4501f50bb4ead1b304
https://github.com/jolestar/go-commons-pool/blob/5cc5d37d092a27de00a69e4501f50bb4ead1b304/collections/queue.go#L361-L371
train
jolestar/go-commons-pool
collections/queue.go
PeekLast
func (q *LinkedBlockingDeque) PeekLast() interface{} { var result interface{} q.lock.Lock() if q.last == nil { result = nil } else { result = q.last.item } q.lock.Unlock() return result }
go
func (q *LinkedBlockingDeque) PeekLast() interface{} { var result interface{} q.lock.Lock() if q.last == nil { result = nil } else { result = q.last.item } q.lock.Unlock() return result }
[ "func", "(", "q", "*", "LinkedBlockingDeque", ")", "PeekLast", "(", ")", "interface", "{", "}", "{", "var", "result", "interface", "{", "}", "\n", "q", ".", "lock", ".", "Lock", "(", ")", "\n", "if", "q", ".", "last", "==", "nil", "{", "result", "=", "nil", "\n", "}", "else", "{", "result", "=", "q", ".", "last", ".", "item", "\n", "}", "\n", "q", ".", "lock", ".", "Unlock", "(", ")", "\n", "return", "result", "\n", "}" ]
// PeekLast retrieves, but does not remove, the last element of this deque, // or returns nil if this deque is empty.
[ "PeekLast", "retrieves", "but", "does", "not", "remove", "the", "last", "element", "of", "this", "deque", "or", "returns", "nil", "if", "this", "deque", "is", "empty", "." ]
5cc5d37d092a27de00a69e4501f50bb4ead1b304
https://github.com/jolestar/go-commons-pool/blob/5cc5d37d092a27de00a69e4501f50bb4ead1b304/collections/queue.go#L375-L385
train
jolestar/go-commons-pool
collections/queue.go
Size
func (q *LinkedBlockingDeque) Size() int { q.lock.Lock() defer q.lock.Unlock() return q.size() }
go
func (q *LinkedBlockingDeque) Size() int { q.lock.Lock() defer q.lock.Unlock() return q.size() }
[ "func", "(", "q", "*", "LinkedBlockingDeque", ")", "Size", "(", ")", "int", "{", "q", ".", "lock", ".", "Lock", "(", ")", "\n", "defer", "q", ".", "lock", ".", "Unlock", "(", ")", "\n", "return", "q", ".", "size", "(", ")", "\n", "}" ]
// Size return this LinkedBlockingDeque current elements len, is concurrent safe
[ "Size", "return", "this", "LinkedBlockingDeque", "current", "elements", "len", "is", "concurrent", "safe" ]
5cc5d37d092a27de00a69e4501f50bb4ead1b304
https://github.com/jolestar/go-commons-pool/blob/5cc5d37d092a27de00a69e4501f50bb4ead1b304/collections/queue.go#L457-L461
train
jolestar/go-commons-pool
collections/queue.go
Next
func (iterator *LinkedBlockingDequeIterator) Next() interface{} { if iterator.next == nil { //TODO error or nil ? //panic(errors.New("NoSuchElement")) return nil } iterator.lastRet = iterator.next x := iterator.nextItem iterator.advance() return x }
go
func (iterator *LinkedBlockingDequeIterator) Next() interface{} { if iterator.next == nil { //TODO error or nil ? //panic(errors.New("NoSuchElement")) return nil } iterator.lastRet = iterator.next x := iterator.nextItem iterator.advance() return x }
[ "func", "(", "iterator", "*", "LinkedBlockingDequeIterator", ")", "Next", "(", ")", "interface", "{", "}", "{", "if", "iterator", ".", "next", "==", "nil", "{", "//TODO error or nil ?", "//panic(errors.New(\"NoSuchElement\"))", "return", "nil", "\n", "}", "\n", "iterator", ".", "lastRet", "=", "iterator", ".", "next", "\n", "x", ":=", "iterator", ".", "nextItem", "\n", "iterator", ".", "advance", "(", ")", "\n", "return", "x", "\n", "}" ]
// Next return next element, if not exist will return nil
[ "Next", "return", "next", "element", "if", "not", "exist", "will", "return", "nil" ]
5cc5d37d092a27de00a69e4501f50bb4ead1b304
https://github.com/jolestar/go-commons-pool/blob/5cc5d37d092a27de00a69e4501f50bb4ead1b304/collections/queue.go#L519-L529
train
jolestar/go-commons-pool
collections/queue.go
Remove
func (iterator *LinkedBlockingDequeIterator) Remove() { n := iterator.lastRet if n == nil { panic(errors.New("IllegalStateException")) } iterator.lastRet = nil lock := iterator.q.lock lock.Lock() if n.item != nil { iterator.q.unlink(n) } lock.Unlock() }
go
func (iterator *LinkedBlockingDequeIterator) Remove() { n := iterator.lastRet if n == nil { panic(errors.New("IllegalStateException")) } iterator.lastRet = nil lock := iterator.q.lock lock.Lock() if n.item != nil { iterator.q.unlink(n) } lock.Unlock() }
[ "func", "(", "iterator", "*", "LinkedBlockingDequeIterator", ")", "Remove", "(", ")", "{", "n", ":=", "iterator", ".", "lastRet", "\n", "if", "n", "==", "nil", "{", "panic", "(", "errors", ".", "New", "(", "\"", "\"", ")", ")", "\n", "}", "\n", "iterator", ".", "lastRet", "=", "nil", "\n", "lock", ":=", "iterator", ".", "q", ".", "lock", "\n", "lock", ".", "Lock", "(", ")", "\n", "if", "n", ".", "item", "!=", "nil", "{", "iterator", ".", "q", ".", "unlink", "(", "n", ")", "\n", "}", "\n", "lock", ".", "Unlock", "(", ")", "\n", "}" ]
// Remove current element from dequeue
[ "Remove", "current", "element", "from", "dequeue" ]
5cc5d37d092a27de00a69e4501f50bb4ead1b304
https://github.com/jolestar/go-commons-pool/blob/5cc5d37d092a27de00a69e4501f50bb4ead1b304/collections/queue.go#L558-L570
train
jolestar/go-commons-pool
config.go
NewDefaultPoolConfig
func NewDefaultPoolConfig() *ObjectPoolConfig { return &ObjectPoolConfig{ LIFO: DefaultLIFO, MaxTotal: DefaultMaxTotal, MaxIdle: DefaultMaxIdle, MinIdle: DefaultMinIdle, MinEvictableIdleTime: DefaultMinEvictableIdleTime, SoftMinEvictableIdleTime: DefaultSoftMinEvictableIdleTime, NumTestsPerEvictionRun: DefaultNumTestsPerEvictionRun, EvictionPolicyName: DefaultEvictionPolicyName, EvitionContext: context.Background(), TestOnCreate: DefaultTestOnCreate, TestOnBorrow: DefaultTestOnBorrow, TestOnReturn: DefaultTestOnReturn, TestWhileIdle: DefaultTestWhileIdle, TimeBetweenEvictionRuns: DefaultTimeBetweenEvictionRuns, BlockWhenExhausted: DefaultBlockWhenExhausted} }
go
func NewDefaultPoolConfig() *ObjectPoolConfig { return &ObjectPoolConfig{ LIFO: DefaultLIFO, MaxTotal: DefaultMaxTotal, MaxIdle: DefaultMaxIdle, MinIdle: DefaultMinIdle, MinEvictableIdleTime: DefaultMinEvictableIdleTime, SoftMinEvictableIdleTime: DefaultSoftMinEvictableIdleTime, NumTestsPerEvictionRun: DefaultNumTestsPerEvictionRun, EvictionPolicyName: DefaultEvictionPolicyName, EvitionContext: context.Background(), TestOnCreate: DefaultTestOnCreate, TestOnBorrow: DefaultTestOnBorrow, TestOnReturn: DefaultTestOnReturn, TestWhileIdle: DefaultTestWhileIdle, TimeBetweenEvictionRuns: DefaultTimeBetweenEvictionRuns, BlockWhenExhausted: DefaultBlockWhenExhausted} }
[ "func", "NewDefaultPoolConfig", "(", ")", "*", "ObjectPoolConfig", "{", "return", "&", "ObjectPoolConfig", "{", "LIFO", ":", "DefaultLIFO", ",", "MaxTotal", ":", "DefaultMaxTotal", ",", "MaxIdle", ":", "DefaultMaxIdle", ",", "MinIdle", ":", "DefaultMinIdle", ",", "MinEvictableIdleTime", ":", "DefaultMinEvictableIdleTime", ",", "SoftMinEvictableIdleTime", ":", "DefaultSoftMinEvictableIdleTime", ",", "NumTestsPerEvictionRun", ":", "DefaultNumTestsPerEvictionRun", ",", "EvictionPolicyName", ":", "DefaultEvictionPolicyName", ",", "EvitionContext", ":", "context", ".", "Background", "(", ")", ",", "TestOnCreate", ":", "DefaultTestOnCreate", ",", "TestOnBorrow", ":", "DefaultTestOnBorrow", ",", "TestOnReturn", ":", "DefaultTestOnReturn", ",", "TestWhileIdle", ":", "DefaultTestWhileIdle", ",", "TimeBetweenEvictionRuns", ":", "DefaultTimeBetweenEvictionRuns", ",", "BlockWhenExhausted", ":", "DefaultBlockWhenExhausted", "}", "\n", "}" ]
// NewDefaultPoolConfig return a ObjectPoolConfig instance init with default value.
[ "NewDefaultPoolConfig", "return", "a", "ObjectPoolConfig", "instance", "init", "with", "default", "value", "." ]
5cc5d37d092a27de00a69e4501f50bb4ead1b304
https://github.com/jolestar/go-commons-pool/blob/5cc5d37d092a27de00a69e4501f50bb4ead1b304/config.go#L192-L209
train
jolestar/go-commons-pool
config.go
NewDefaultAbandonedConfig
func NewDefaultAbandonedConfig() *AbandonedConfig { return &AbandonedConfig{RemoveAbandonedOnBorrow: false, RemoveAbandonedOnMaintenance: false, RemoveAbandonedTimeout: 5 * time.Minute} }
go
func NewDefaultAbandonedConfig() *AbandonedConfig { return &AbandonedConfig{RemoveAbandonedOnBorrow: false, RemoveAbandonedOnMaintenance: false, RemoveAbandonedTimeout: 5 * time.Minute} }
[ "func", "NewDefaultAbandonedConfig", "(", ")", "*", "AbandonedConfig", "{", "return", "&", "AbandonedConfig", "{", "RemoveAbandonedOnBorrow", ":", "false", ",", "RemoveAbandonedOnMaintenance", ":", "false", ",", "RemoveAbandonedTimeout", ":", "5", "*", "time", ".", "Minute", "}", "\n", "}" ]
// NewDefaultAbandonedConfig return a new AbandonedConfig instance init with default.
[ "NewDefaultAbandonedConfig", "return", "a", "new", "AbandonedConfig", "instance", "init", "with", "default", "." ]
5cc5d37d092a27de00a69e4501f50bb4ead1b304
https://github.com/jolestar/go-commons-pool/blob/5cc5d37d092a27de00a69e4501f50bb4ead1b304/config.go#L220-L222
train
jolestar/go-commons-pool
config.go
Evict
func (p *DefaultEvictionPolicy) Evict(config *EvictionConfig, underTest *PooledObject, idleCount int) bool { idleTime := underTest.GetIdleTime() if (config.IdleSoftEvictTime < idleTime && config.MinIdle < idleCount) || config.IdleEvictTime < idleTime { return true } return false }
go
func (p *DefaultEvictionPolicy) Evict(config *EvictionConfig, underTest *PooledObject, idleCount int) bool { idleTime := underTest.GetIdleTime() if (config.IdleSoftEvictTime < idleTime && config.MinIdle < idleCount) || config.IdleEvictTime < idleTime { return true } return false }
[ "func", "(", "p", "*", "DefaultEvictionPolicy", ")", "Evict", "(", "config", "*", "EvictionConfig", ",", "underTest", "*", "PooledObject", ",", "idleCount", "int", ")", "bool", "{", "idleTime", ":=", "underTest", ".", "GetIdleTime", "(", ")", "\n\n", "if", "(", "config", ".", "IdleSoftEvictTime", "<", "idleTime", "&&", "config", ".", "MinIdle", "<", "idleCount", ")", "||", "config", ".", "IdleEvictTime", "<", "idleTime", "{", "return", "true", "\n", "}", "\n", "return", "false", "\n", "}" ]
// Evict do evict by config
[ "Evict", "do", "evict", "by", "config" ]
5cc5d37d092a27de00a69e4501f50bb4ead1b304
https://github.com/jolestar/go-commons-pool/blob/5cc5d37d092a27de00a69e4501f50bb4ead1b304/config.go#L243-L252
train
jolestar/go-commons-pool
config.go
RegistryEvictionPolicy
func RegistryEvictionPolicy(name string, policy EvictionPolicy) { if name == "" || policy == nil { panic(errors.New("invalid argument")) } policiesMutex.Lock() policies[name] = policy policiesMutex.Unlock() }
go
func RegistryEvictionPolicy(name string, policy EvictionPolicy) { if name == "" || policy == nil { panic(errors.New("invalid argument")) } policiesMutex.Lock() policies[name] = policy policiesMutex.Unlock() }
[ "func", "RegistryEvictionPolicy", "(", "name", "string", ",", "policy", "EvictionPolicy", ")", "{", "if", "name", "==", "\"", "\"", "||", "policy", "==", "nil", "{", "panic", "(", "errors", ".", "New", "(", "\"", "\"", ")", ")", "\n", "}", "\n", "policiesMutex", ".", "Lock", "(", ")", "\n", "policies", "[", "name", "]", "=", "policy", "\n", "policiesMutex", ".", "Unlock", "(", ")", "\n", "}" ]
// RegistryEvictionPolicy registry a custom EvictionPolicy with gaven name.
[ "RegistryEvictionPolicy", "registry", "a", "custom", "EvictionPolicy", "with", "gaven", "name", "." ]
5cc5d37d092a27de00a69e4501f50bb4ead1b304
https://github.com/jolestar/go-commons-pool/blob/5cc5d37d092a27de00a69e4501f50bb4ead1b304/config.go#L260-L267
train
jolestar/go-commons-pool
config.go
GetEvictionPolicy
func GetEvictionPolicy(name string) EvictionPolicy { policiesMutex.Lock() defer policiesMutex.Unlock() return policies[name] }
go
func GetEvictionPolicy(name string) EvictionPolicy { policiesMutex.Lock() defer policiesMutex.Unlock() return policies[name] }
[ "func", "GetEvictionPolicy", "(", "name", "string", ")", "EvictionPolicy", "{", "policiesMutex", ".", "Lock", "(", ")", "\n", "defer", "policiesMutex", ".", "Unlock", "(", ")", "\n", "return", "policies", "[", "name", "]", "\n\n", "}" ]
// GetEvictionPolicy return a EvictionPolicy by gaven name
[ "GetEvictionPolicy", "return", "a", "EvictionPolicy", "by", "gaven", "name" ]
5cc5d37d092a27de00a69e4501f50bb4ead1b304
https://github.com/jolestar/go-commons-pool/blob/5cc5d37d092a27de00a69e4501f50bb4ead1b304/config.go#L270-L275
train
jolestar/go-commons-pool
factory.go
NewPooledObjectFactorySimple
func NewPooledObjectFactorySimple( create func(context.Context) (interface{}, error)) PooledObjectFactory { return NewPooledObjectFactory(create, nil, nil, nil, nil) }
go
func NewPooledObjectFactorySimple( create func(context.Context) (interface{}, error)) PooledObjectFactory { return NewPooledObjectFactory(create, nil, nil, nil, nil) }
[ "func", "NewPooledObjectFactorySimple", "(", "create", "func", "(", "context", ".", "Context", ")", "(", "interface", "{", "}", ",", "error", ")", ")", "PooledObjectFactory", "{", "return", "NewPooledObjectFactory", "(", "create", ",", "nil", ",", "nil", ",", "nil", ",", "nil", ")", "\n", "}" ]
// NewPooledObjectFactorySimple return a DefaultPooledObjectFactory, only custom MakeObject func
[ "NewPooledObjectFactorySimple", "return", "a", "DefaultPooledObjectFactory", "only", "custom", "MakeObject", "func" ]
5cc5d37d092a27de00a69e4501f50bb4ead1b304
https://github.com/jolestar/go-commons-pool/blob/5cc5d37d092a27de00a69e4501f50bb4ead1b304/factory.go#L60-L63
train
jolestar/go-commons-pool
factory.go
NewPooledObjectFactory
func NewPooledObjectFactory( create func(context.Context) (interface{}, error), destroy func(ctx context.Context, object *PooledObject) error, validate func(ctx context.Context, object *PooledObject) bool, activate func(ctx context.Context, object *PooledObject) error, passivate func(ctx context.Context, object *PooledObject) error) PooledObjectFactory { if create == nil { panic(errors.New("make function can not be nil")) } return &DefaultPooledObjectFactory{ make: func(ctx context.Context) (*PooledObject, error) { o, err := create(ctx) if err != nil { return nil, err } return NewPooledObject(o), nil }, destroy: destroy, validate: validate, activate: activate, passivate: passivate} }
go
func NewPooledObjectFactory( create func(context.Context) (interface{}, error), destroy func(ctx context.Context, object *PooledObject) error, validate func(ctx context.Context, object *PooledObject) bool, activate func(ctx context.Context, object *PooledObject) error, passivate func(ctx context.Context, object *PooledObject) error) PooledObjectFactory { if create == nil { panic(errors.New("make function can not be nil")) } return &DefaultPooledObjectFactory{ make: func(ctx context.Context) (*PooledObject, error) { o, err := create(ctx) if err != nil { return nil, err } return NewPooledObject(o), nil }, destroy: destroy, validate: validate, activate: activate, passivate: passivate} }
[ "func", "NewPooledObjectFactory", "(", "create", "func", "(", "context", ".", "Context", ")", "(", "interface", "{", "}", ",", "error", ")", ",", "destroy", "func", "(", "ctx", "context", ".", "Context", ",", "object", "*", "PooledObject", ")", "error", ",", "validate", "func", "(", "ctx", "context", ".", "Context", ",", "object", "*", "PooledObject", ")", "bool", ",", "activate", "func", "(", "ctx", "context", ".", "Context", ",", "object", "*", "PooledObject", ")", "error", ",", "passivate", "func", "(", "ctx", "context", ".", "Context", ",", "object", "*", "PooledObject", ")", "error", ")", "PooledObjectFactory", "{", "if", "create", "==", "nil", "{", "panic", "(", "errors", ".", "New", "(", "\"", "\"", ")", ")", "\n", "}", "\n", "return", "&", "DefaultPooledObjectFactory", "{", "make", ":", "func", "(", "ctx", "context", ".", "Context", ")", "(", "*", "PooledObject", ",", "error", ")", "{", "o", ",", "err", ":=", "create", "(", "ctx", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "return", "NewPooledObject", "(", "o", ")", ",", "nil", "\n", "}", ",", "destroy", ":", "destroy", ",", "validate", ":", "validate", ",", "activate", ":", "activate", ",", "passivate", ":", "passivate", "}", "\n", "}" ]
// NewPooledObjectFactory return a DefaultPooledObjectFactory, init with gaven func.
[ "NewPooledObjectFactory", "return", "a", "DefaultPooledObjectFactory", "init", "with", "gaven", "func", "." ]
5cc5d37d092a27de00a69e4501f50bb4ead1b304
https://github.com/jolestar/go-commons-pool/blob/5cc5d37d092a27de00a69e4501f50bb4ead1b304/factory.go#L66-L87
train
jolestar/go-commons-pool
factory.go
MakeObject
func (f *DefaultPooledObjectFactory) MakeObject(ctx context.Context) (*PooledObject, error) { return f.make(ctx) }
go
func (f *DefaultPooledObjectFactory) MakeObject(ctx context.Context) (*PooledObject, error) { return f.make(ctx) }
[ "func", "(", "f", "*", "DefaultPooledObjectFactory", ")", "MakeObject", "(", "ctx", "context", ".", "Context", ")", "(", "*", "PooledObject", ",", "error", ")", "{", "return", "f", ".", "make", "(", "ctx", ")", "\n", "}" ]
// MakeObject see PooledObjectFactory.MakeObject
[ "MakeObject", "see", "PooledObjectFactory", ".", "MakeObject" ]
5cc5d37d092a27de00a69e4501f50bb4ead1b304
https://github.com/jolestar/go-commons-pool/blob/5cc5d37d092a27de00a69e4501f50bb4ead1b304/factory.go#L90-L92
train
jolestar/go-commons-pool
factory.go
DestroyObject
func (f *DefaultPooledObjectFactory) DestroyObject(ctx context.Context, object *PooledObject) error { if f.destroy != nil { return f.destroy(ctx, object) } return nil }
go
func (f *DefaultPooledObjectFactory) DestroyObject(ctx context.Context, object *PooledObject) error { if f.destroy != nil { return f.destroy(ctx, object) } return nil }
[ "func", "(", "f", "*", "DefaultPooledObjectFactory", ")", "DestroyObject", "(", "ctx", "context", ".", "Context", ",", "object", "*", "PooledObject", ")", "error", "{", "if", "f", ".", "destroy", "!=", "nil", "{", "return", "f", ".", "destroy", "(", "ctx", ",", "object", ")", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// DestroyObject see PooledObjectFactory.DestroyObject
[ "DestroyObject", "see", "PooledObjectFactory", ".", "DestroyObject" ]
5cc5d37d092a27de00a69e4501f50bb4ead1b304
https://github.com/jolestar/go-commons-pool/blob/5cc5d37d092a27de00a69e4501f50bb4ead1b304/factory.go#L95-L100
train
jolestar/go-commons-pool
factory.go
ValidateObject
func (f *DefaultPooledObjectFactory) ValidateObject(ctx context.Context, object *PooledObject) bool { if f.validate != nil { return f.validate(ctx, object) } return true }
go
func (f *DefaultPooledObjectFactory) ValidateObject(ctx context.Context, object *PooledObject) bool { if f.validate != nil { return f.validate(ctx, object) } return true }
[ "func", "(", "f", "*", "DefaultPooledObjectFactory", ")", "ValidateObject", "(", "ctx", "context", ".", "Context", ",", "object", "*", "PooledObject", ")", "bool", "{", "if", "f", ".", "validate", "!=", "nil", "{", "return", "f", ".", "validate", "(", "ctx", ",", "object", ")", "\n", "}", "\n", "return", "true", "\n", "}" ]
// ValidateObject see PooledObjectFactory.ValidateObject
[ "ValidateObject", "see", "PooledObjectFactory", ".", "ValidateObject" ]
5cc5d37d092a27de00a69e4501f50bb4ead1b304
https://github.com/jolestar/go-commons-pool/blob/5cc5d37d092a27de00a69e4501f50bb4ead1b304/factory.go#L103-L108
train
jolestar/go-commons-pool
factory.go
ActivateObject
func (f *DefaultPooledObjectFactory) ActivateObject(ctx context.Context, object *PooledObject) error { if f.activate != nil { return f.activate(ctx, object) } return nil }
go
func (f *DefaultPooledObjectFactory) ActivateObject(ctx context.Context, object *PooledObject) error { if f.activate != nil { return f.activate(ctx, object) } return nil }
[ "func", "(", "f", "*", "DefaultPooledObjectFactory", ")", "ActivateObject", "(", "ctx", "context", ".", "Context", ",", "object", "*", "PooledObject", ")", "error", "{", "if", "f", ".", "activate", "!=", "nil", "{", "return", "f", ".", "activate", "(", "ctx", ",", "object", ")", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// ActivateObject see PooledObjectFactory.ActivateObject
[ "ActivateObject", "see", "PooledObjectFactory", ".", "ActivateObject" ]
5cc5d37d092a27de00a69e4501f50bb4ead1b304
https://github.com/jolestar/go-commons-pool/blob/5cc5d37d092a27de00a69e4501f50bb4ead1b304/factory.go#L111-L116
train
jolestar/go-commons-pool
factory.go
PassivateObject
func (f *DefaultPooledObjectFactory) PassivateObject(ctx context.Context, object *PooledObject) error { if f.passivate != nil { return f.passivate(ctx, object) } return nil }
go
func (f *DefaultPooledObjectFactory) PassivateObject(ctx context.Context, object *PooledObject) error { if f.passivate != nil { return f.passivate(ctx, object) } return nil }
[ "func", "(", "f", "*", "DefaultPooledObjectFactory", ")", "PassivateObject", "(", "ctx", "context", ".", "Context", ",", "object", "*", "PooledObject", ")", "error", "{", "if", "f", ".", "passivate", "!=", "nil", "{", "return", "f", ".", "passivate", "(", "ctx", ",", "object", ")", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// PassivateObject see PooledObjectFactory.PassivateObject
[ "PassivateObject", "see", "PooledObjectFactory", ".", "PassivateObject" ]
5cc5d37d092a27de00a69e4501f50bb4ead1b304
https://github.com/jolestar/go-commons-pool/blob/5cc5d37d092a27de00a69e4501f50bb4ead1b304/factory.go#L119-L124
train
dgraph-io/dgo
x/error.go
Check
func Check(err error) { if err != nil { log.Fatalf("%+v", errors.WithStack(err)) } }
go
func Check(err error) { if err != nil { log.Fatalf("%+v", errors.WithStack(err)) } }
[ "func", "Check", "(", "err", "error", ")", "{", "if", "err", "!=", "nil", "{", "log", ".", "Fatalf", "(", "\"", "\"", ",", "errors", ".", "WithStack", "(", "err", ")", ")", "\n", "}", "\n", "}" ]
// Check logs fatal if err != nil.
[ "Check", "logs", "fatal", "if", "err", "!", "=", "nil", "." ]
7517ac021e22457b8b14c151a3476aa8c1e22a64
https://github.com/dgraph-io/dgo/blob/7517ac021e22457b8b14c151a3476aa8c1e22a64/x/error.go#L26-L30
train
dgraph-io/dgo
x/error.go
Checkf
func Checkf(err error, format string, args ...interface{}) { if err != nil { log.Fatalf("%+v", errors.Wrapf(err, format, args...)) } }
go
func Checkf(err error, format string, args ...interface{}) { if err != nil { log.Fatalf("%+v", errors.Wrapf(err, format, args...)) } }
[ "func", "Checkf", "(", "err", "error", ",", "format", "string", ",", "args", "...", "interface", "{", "}", ")", "{", "if", "err", "!=", "nil", "{", "log", ".", "Fatalf", "(", "\"", "\"", ",", "errors", ".", "Wrapf", "(", "err", ",", "format", ",", "args", "...", ")", ")", "\n", "}", "\n", "}" ]
// Checkf is Check with extra info.
[ "Checkf", "is", "Check", "with", "extra", "info", "." ]
7517ac021e22457b8b14c151a3476aa8c1e22a64
https://github.com/dgraph-io/dgo/blob/7517ac021e22457b8b14c151a3476aa8c1e22a64/x/error.go#L33-L37
train
dgraph-io/dgo
txn.go
BestEffort
func (txn *Txn) BestEffort() *Txn { if !txn.readOnly { panic("Best effort only works for read-only queries.") } txn.bestEffort = true return txn }
go
func (txn *Txn) BestEffort() *Txn { if !txn.readOnly { panic("Best effort only works for read-only queries.") } txn.bestEffort = true return txn }
[ "func", "(", "txn", "*", "Txn", ")", "BestEffort", "(", ")", "*", "Txn", "{", "if", "!", "txn", ".", "readOnly", "{", "panic", "(", "\"", "\"", ")", "\n", "}", "\n", "txn", ".", "bestEffort", "=", "true", "\n", "return", "txn", "\n", "}" ]
// BestEffort enables best effort in read-only queries. Using this flag will ask the // Dgraph Alpha to try to get timestamps from memory in a best effort to reduce the number of // outbound requests to Zero. This may yield improved latencies in read-bound datasets. // // This method will panic if the transaction is not read-only. // Returns the transaction itself.
[ "BestEffort", "enables", "best", "effort", "in", "read", "-", "only", "queries", ".", "Using", "this", "flag", "will", "ask", "the", "Dgraph", "Alpha", "to", "try", "to", "get", "timestamps", "from", "memory", "in", "a", "best", "effort", "to", "reduce", "the", "number", "of", "outbound", "requests", "to", "Zero", ".", "This", "may", "yield", "improved", "latencies", "in", "read", "-", "bound", "datasets", ".", "This", "method", "will", "panic", "if", "the", "transaction", "is", "not", "read", "-", "only", ".", "Returns", "the", "transaction", "itself", "." ]
7517ac021e22457b8b14c151a3476aa8c1e22a64
https://github.com/dgraph-io/dgo/blob/7517ac021e22457b8b14c151a3476aa8c1e22a64/txn.go#L68-L74
train
dgraph-io/dgo
txn.go
NewTxn
func (d *Dgraph) NewTxn() *Txn { return &Txn{ dg: d, dc: d.anyClient(), context: &api.TxnContext{}, } }
go
func (d *Dgraph) NewTxn() *Txn { return &Txn{ dg: d, dc: d.anyClient(), context: &api.TxnContext{}, } }
[ "func", "(", "d", "*", "Dgraph", ")", "NewTxn", "(", ")", "*", "Txn", "{", "return", "&", "Txn", "{", "dg", ":", "d", ",", "dc", ":", "d", ".", "anyClient", "(", ")", ",", "context", ":", "&", "api", ".", "TxnContext", "{", "}", ",", "}", "\n", "}" ]
// NewTxn creates a new transaction.
[ "NewTxn", "creates", "a", "new", "transaction", "." ]
7517ac021e22457b8b14c151a3476aa8c1e22a64
https://github.com/dgraph-io/dgo/blob/7517ac021e22457b8b14c151a3476aa8c1e22a64/txn.go#L77-L83
train
dgraph-io/dgo
txn.go
QueryWithVars
func (txn *Txn) QueryWithVars(ctx context.Context, q string, vars map[string]string) (*api.Response, error) { if txn.finished { return nil, ErrFinished } req := &api.Request{ Query: q, Vars: vars, StartTs: txn.context.StartTs, ReadOnly: txn.readOnly, BestEffort: txn.bestEffort, } ctx = txn.dg.getContext(ctx) resp, err := txn.dc.Query(ctx, req) if isJwtExpired(err) { err = txn.dg.retryLogin(ctx) if err != nil { return nil, err } ctx = txn.dg.getContext(ctx) resp, err = txn.dc.Query(ctx, req) } if err == nil { if err := txn.mergeContext(resp.GetTxn()); err != nil { return nil, err } } return resp, err }
go
func (txn *Txn) QueryWithVars(ctx context.Context, q string, vars map[string]string) (*api.Response, error) { if txn.finished { return nil, ErrFinished } req := &api.Request{ Query: q, Vars: vars, StartTs: txn.context.StartTs, ReadOnly: txn.readOnly, BestEffort: txn.bestEffort, } ctx = txn.dg.getContext(ctx) resp, err := txn.dc.Query(ctx, req) if isJwtExpired(err) { err = txn.dg.retryLogin(ctx) if err != nil { return nil, err } ctx = txn.dg.getContext(ctx) resp, err = txn.dc.Query(ctx, req) } if err == nil { if err := txn.mergeContext(resp.GetTxn()); err != nil { return nil, err } } return resp, err }
[ "func", "(", "txn", "*", "Txn", ")", "QueryWithVars", "(", "ctx", "context", ".", "Context", ",", "q", "string", ",", "vars", "map", "[", "string", "]", "string", ")", "(", "*", "api", ".", "Response", ",", "error", ")", "{", "if", "txn", ".", "finished", "{", "return", "nil", ",", "ErrFinished", "\n", "}", "\n", "req", ":=", "&", "api", ".", "Request", "{", "Query", ":", "q", ",", "Vars", ":", "vars", ",", "StartTs", ":", "txn", ".", "context", ".", "StartTs", ",", "ReadOnly", ":", "txn", ".", "readOnly", ",", "BestEffort", ":", "txn", ".", "bestEffort", ",", "}", "\n", "ctx", "=", "txn", ".", "dg", ".", "getContext", "(", "ctx", ")", "\n", "resp", ",", "err", ":=", "txn", ".", "dc", ".", "Query", "(", "ctx", ",", "req", ")", "\n", "if", "isJwtExpired", "(", "err", ")", "{", "err", "=", "txn", ".", "dg", ".", "retryLogin", "(", "ctx", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "ctx", "=", "txn", ".", "dg", ".", "getContext", "(", "ctx", ")", "\n", "resp", ",", "err", "=", "txn", ".", "dc", ".", "Query", "(", "ctx", ",", "req", ")", "\n", "}", "\n\n", "if", "err", "==", "nil", "{", "if", "err", ":=", "txn", ".", "mergeContext", "(", "resp", ".", "GetTxn", "(", ")", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "}", "\n", "return", "resp", ",", "err", "\n", "}" ]
// QueryWithVars is like Query, but allows a variable map to be used. This can // provide safety against injection attacks.
[ "QueryWithVars", "is", "like", "Query", "but", "allows", "a", "variable", "map", "to", "be", "used", ".", "This", "can", "provide", "safety", "against", "injection", "attacks", "." ]
7517ac021e22457b8b14c151a3476aa8c1e22a64
https://github.com/dgraph-io/dgo/blob/7517ac021e22457b8b14c151a3476aa8c1e22a64/txn.go#L100-L129
train
dgraph-io/dgo
txn.go
Mutate
func (txn *Txn) Mutate(ctx context.Context, mu *api.Mutation) (*api.Assigned, error) { switch { case txn.readOnly: return nil, ErrReadOnly case txn.finished: return nil, ErrFinished } txn.mutated = true mu.StartTs = txn.context.StartTs ctx = txn.dg.getContext(ctx) ag, err := txn.dc.Mutate(ctx, mu) if isJwtExpired(err) { err = txn.dg.retryLogin(ctx) if err != nil { return nil, err } ctx = txn.dg.getContext(ctx) ag, err = txn.dc.Mutate(ctx, mu) } if err != nil { _ = txn.Discard(ctx) // Ignore error - user should see the original error. return nil, err } if mu.CommitNow { txn.finished = true } err = txn.mergeContext(ag.Context) return ag, err }
go
func (txn *Txn) Mutate(ctx context.Context, mu *api.Mutation) (*api.Assigned, error) { switch { case txn.readOnly: return nil, ErrReadOnly case txn.finished: return nil, ErrFinished } txn.mutated = true mu.StartTs = txn.context.StartTs ctx = txn.dg.getContext(ctx) ag, err := txn.dc.Mutate(ctx, mu) if isJwtExpired(err) { err = txn.dg.retryLogin(ctx) if err != nil { return nil, err } ctx = txn.dg.getContext(ctx) ag, err = txn.dc.Mutate(ctx, mu) } if err != nil { _ = txn.Discard(ctx) // Ignore error - user should see the original error. return nil, err } if mu.CommitNow { txn.finished = true } err = txn.mergeContext(ag.Context) return ag, err }
[ "func", "(", "txn", "*", "Txn", ")", "Mutate", "(", "ctx", "context", ".", "Context", ",", "mu", "*", "api", ".", "Mutation", ")", "(", "*", "api", ".", "Assigned", ",", "error", ")", "{", "switch", "{", "case", "txn", ".", "readOnly", ":", "return", "nil", ",", "ErrReadOnly", "\n", "case", "txn", ".", "finished", ":", "return", "nil", ",", "ErrFinished", "\n", "}", "\n\n", "txn", ".", "mutated", "=", "true", "\n", "mu", ".", "StartTs", "=", "txn", ".", "context", ".", "StartTs", "\n", "ctx", "=", "txn", ".", "dg", ".", "getContext", "(", "ctx", ")", "\n", "ag", ",", "err", ":=", "txn", ".", "dc", ".", "Mutate", "(", "ctx", ",", "mu", ")", "\n", "if", "isJwtExpired", "(", "err", ")", "{", "err", "=", "txn", ".", "dg", ".", "retryLogin", "(", "ctx", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "ctx", "=", "txn", ".", "dg", ".", "getContext", "(", "ctx", ")", "\n", "ag", ",", "err", "=", "txn", ".", "dc", ".", "Mutate", "(", "ctx", ",", "mu", ")", "\n", "}", "\n\n", "if", "err", "!=", "nil", "{", "_", "=", "txn", ".", "Discard", "(", "ctx", ")", "// Ignore error - user should see the original error.", "\n", "return", "nil", ",", "err", "\n", "}", "\n\n", "if", "mu", ".", "CommitNow", "{", "txn", ".", "finished", "=", "true", "\n", "}", "\n", "err", "=", "txn", ".", "mergeContext", "(", "ag", ".", "Context", ")", "\n", "return", "ag", ",", "err", "\n", "}" ]
// Mutate allows data stored on dgraph instances to be modified. The fields in // api.Mutation come in pairs, set and delete. Mutations can either be // encoded as JSON or as RDFs. // // If CommitNow is set, then this call will result in the transaction // being committed. In this case, an explicit call to Commit doesn't need to // subsequently be made. // // If the mutation fails, then the transaction is discarded and all future // operations on it will fail.
[ "Mutate", "allows", "data", "stored", "on", "dgraph", "instances", "to", "be", "modified", ".", "The", "fields", "in", "api", ".", "Mutation", "come", "in", "pairs", "set", "and", "delete", ".", "Mutations", "can", "either", "be", "encoded", "as", "JSON", "or", "as", "RDFs", ".", "If", "CommitNow", "is", "set", "then", "this", "call", "will", "result", "in", "the", "transaction", "being", "committed", ".", "In", "this", "case", "an", "explicit", "call", "to", "Commit", "doesn", "t", "need", "to", "subsequently", "be", "made", ".", "If", "the", "mutation", "fails", "then", "the", "transaction", "is", "discarded", "and", "all", "future", "operations", "on", "it", "will", "fail", "." ]
7517ac021e22457b8b14c151a3476aa8c1e22a64
https://github.com/dgraph-io/dgo/blob/7517ac021e22457b8b14c151a3476aa8c1e22a64/txn.go#L157-L188
train
dgraph-io/dgo
txn.go
Commit
func (txn *Txn) Commit(ctx context.Context) error { switch { case txn.readOnly: return ErrReadOnly case txn.finished: return ErrFinished } err := txn.commitOrAbort(ctx) if s, ok := status.FromError(err); ok && s.Code() == codes.Aborted { err = y.ErrAborted } return err }
go
func (txn *Txn) Commit(ctx context.Context) error { switch { case txn.readOnly: return ErrReadOnly case txn.finished: return ErrFinished } err := txn.commitOrAbort(ctx) if s, ok := status.FromError(err); ok && s.Code() == codes.Aborted { err = y.ErrAborted } return err }
[ "func", "(", "txn", "*", "Txn", ")", "Commit", "(", "ctx", "context", ".", "Context", ")", "error", "{", "switch", "{", "case", "txn", ".", "readOnly", ":", "return", "ErrReadOnly", "\n", "case", "txn", ".", "finished", ":", "return", "ErrFinished", "\n", "}", "\n\n", "err", ":=", "txn", ".", "commitOrAbort", "(", "ctx", ")", "\n", "if", "s", ",", "ok", ":=", "status", ".", "FromError", "(", "err", ")", ";", "ok", "&&", "s", ".", "Code", "(", ")", "==", "codes", ".", "Aborted", "{", "err", "=", "y", ".", "ErrAborted", "\n", "}", "\n", "return", "err", "\n", "}" ]
// Commit commits any mutations that have been made in the transaction. Once // Commit has been called, the lifespan of the transaction is complete. // // Errors could be returned for various reasons. Notably, ErrAborted could be // returned if transactions that modify the same data are being run // concurrently. It's up to the user to decide if they wish to retry. In this // case, the user should create a new transaction.
[ "Commit", "commits", "any", "mutations", "that", "have", "been", "made", "in", "the", "transaction", ".", "Once", "Commit", "has", "been", "called", "the", "lifespan", "of", "the", "transaction", "is", "complete", ".", "Errors", "could", "be", "returned", "for", "various", "reasons", ".", "Notably", "ErrAborted", "could", "be", "returned", "if", "transactions", "that", "modify", "the", "same", "data", "are", "being", "run", "concurrently", ".", "It", "s", "up", "to", "the", "user", "to", "decide", "if", "they", "wish", "to", "retry", ".", "In", "this", "case", "the", "user", "should", "create", "a", "new", "transaction", "." ]
7517ac021e22457b8b14c151a3476aa8c1e22a64
https://github.com/dgraph-io/dgo/blob/7517ac021e22457b8b14c151a3476aa8c1e22a64/txn.go#L197-L210
train
dgraph-io/dgo
client.go
isJwtExpired
func isJwtExpired(err error) bool { if err == nil { return false } st, ok := status.FromError(err) return ok && st.Code() == codes.Unauthenticated && strings.Contains(err.Error(), "Token is expired") }
go
func isJwtExpired(err error) bool { if err == nil { return false } st, ok := status.FromError(err) return ok && st.Code() == codes.Unauthenticated && strings.Contains(err.Error(), "Token is expired") }
[ "func", "isJwtExpired", "(", "err", "error", ")", "bool", "{", "if", "err", "==", "nil", "{", "return", "false", "\n", "}", "\n\n", "st", ",", "ok", ":=", "status", ".", "FromError", "(", "err", ")", "\n", "return", "ok", "&&", "st", ".", "Code", "(", ")", "==", "codes", ".", "Unauthenticated", "&&", "strings", ".", "Contains", "(", "err", ".", "Error", "(", ")", ",", "\"", "\"", ")", "\n", "}" ]
// isJwtExpired returns true if the error indicates that the jwt has expired
[ "isJwtExpired", "returns", "true", "if", "the", "error", "indicates", "that", "the", "jwt", "has", "expired" ]
7517ac021e22457b8b14c151a3476aa8c1e22a64
https://github.com/dgraph-io/dgo/blob/7517ac021e22457b8b14c151a3476aa8c1e22a64/client.go#L132-L140
train
dgraph-io/dgo
client.go
DeleteEdges
func DeleteEdges(mu *api.Mutation, uid string, predicates ...string) { for _, predicate := range predicates { mu.Del = append(mu.Del, &api.NQuad{ Subject: uid, Predicate: predicate, // _STAR_ALL is defined as x.Star in x package. ObjectValue: &api.Value{Val: &api.Value_DefaultVal{"_STAR_ALL"}}, }) } }
go
func DeleteEdges(mu *api.Mutation, uid string, predicates ...string) { for _, predicate := range predicates { mu.Del = append(mu.Del, &api.NQuad{ Subject: uid, Predicate: predicate, // _STAR_ALL is defined as x.Star in x package. ObjectValue: &api.Value{Val: &api.Value_DefaultVal{"_STAR_ALL"}}, }) } }
[ "func", "DeleteEdges", "(", "mu", "*", "api", ".", "Mutation", ",", "uid", "string", ",", "predicates", "...", "string", ")", "{", "for", "_", ",", "predicate", ":=", "range", "predicates", "{", "mu", ".", "Del", "=", "append", "(", "mu", ".", "Del", ",", "&", "api", ".", "NQuad", "{", "Subject", ":", "uid", ",", "Predicate", ":", "predicate", ",", "// _STAR_ALL is defined as x.Star in x package.", "ObjectValue", ":", "&", "api", ".", "Value", "{", "Val", ":", "&", "api", ".", "Value_DefaultVal", "{", "\"", "\"", "}", "}", ",", "}", ")", "\n", "}", "\n", "}" ]
// DeleteEdges sets the edges corresponding to predicates on the node with the given uid // for deletion. // This helper function doesn't run the mutation on the server. It must be done by the user // after the function returns.
[ "DeleteEdges", "sets", "the", "edges", "corresponding", "to", "predicates", "on", "the", "node", "with", "the", "given", "uid", "for", "deletion", ".", "This", "helper", "function", "doesn", "t", "run", "the", "mutation", "on", "the", "server", ".", "It", "must", "be", "done", "by", "the", "user", "after", "the", "function", "returns", "." ]
7517ac021e22457b8b14c151a3476aa8c1e22a64
https://github.com/dgraph-io/dgo/blob/7517ac021e22457b8b14c151a3476aa8c1e22a64/client.go#L150-L159
train