id
int32
0
167k
repo
stringlengths
5
54
path
stringlengths
4
155
func_name
stringlengths
1
118
original_string
stringlengths
52
85.5k
language
stringclasses
1 value
code
stringlengths
52
85.5k
code_tokens
sequence
docstring
stringlengths
6
2.61k
docstring_tokens
sequence
sha
stringlengths
40
40
url
stringlengths
85
252
1,300
lox/httpcache
handler.go
passUpstream
func (h *Handler) passUpstream(w http.ResponseWriter, r *cacheRequest) { rw := newResponseStreamer(w) rdr, err := rw.Stream.NextReader() if err != nil { debugf("error creating next stream reader: %v", err) w.Header().Set(CacheHeader, "SKIP") h.upstream.ServeHTTP(w, r.Request) return } t := Clock() debugf("passing request upstream") rw.Header().Set(CacheHeader, "MISS") go func() { h.upstream.ServeHTTP(rw, r.Request) rw.Stream.Close() }() rw.WaitHeaders() debugf("upstream responded headers in %s", Clock().Sub(t).String()) // just the headers! res := NewResourceBytes(rw.StatusCode, nil, rw.Header()) if !h.isCacheable(res, r) { rdr.Close() debugf("resource is uncacheable") rw.Header().Set(CacheHeader, "SKIP") return } b, err := ioutil.ReadAll(rdr) rdr.Close() if err != nil { debugf("error reading stream: %v", err) rw.Header().Set(CacheHeader, "SKIP") return } debugf("full upstream response took %s", Clock().Sub(t).String()) res.ReadSeekCloser = &byteReadSeekCloser{bytes.NewReader(b)} if age, err := correctedAge(res.Header(), t, Clock()); err == nil { res.Header().Set("Age", strconv.Itoa(int(math.Ceil(age.Seconds())))) } else { debugf("error calculating corrected age: %s", err.Error()) } rw.Header().Set(ProxyDateHeader, Clock().Format(http.TimeFormat)) h.storeResource(res, r) }
go
func (h *Handler) passUpstream(w http.ResponseWriter, r *cacheRequest) { rw := newResponseStreamer(w) rdr, err := rw.Stream.NextReader() if err != nil { debugf("error creating next stream reader: %v", err) w.Header().Set(CacheHeader, "SKIP") h.upstream.ServeHTTP(w, r.Request) return } t := Clock() debugf("passing request upstream") rw.Header().Set(CacheHeader, "MISS") go func() { h.upstream.ServeHTTP(rw, r.Request) rw.Stream.Close() }() rw.WaitHeaders() debugf("upstream responded headers in %s", Clock().Sub(t).String()) // just the headers! res := NewResourceBytes(rw.StatusCode, nil, rw.Header()) if !h.isCacheable(res, r) { rdr.Close() debugf("resource is uncacheable") rw.Header().Set(CacheHeader, "SKIP") return } b, err := ioutil.ReadAll(rdr) rdr.Close() if err != nil { debugf("error reading stream: %v", err) rw.Header().Set(CacheHeader, "SKIP") return } debugf("full upstream response took %s", Clock().Sub(t).String()) res.ReadSeekCloser = &byteReadSeekCloser{bytes.NewReader(b)} if age, err := correctedAge(res.Header(), t, Clock()); err == nil { res.Header().Set("Age", strconv.Itoa(int(math.Ceil(age.Seconds())))) } else { debugf("error calculating corrected age: %s", err.Error()) } rw.Header().Set(ProxyDateHeader, Clock().Format(http.TimeFormat)) h.storeResource(res, r) }
[ "func", "(", "h", "*", "Handler", ")", "passUpstream", "(", "w", "http", ".", "ResponseWriter", ",", "r", "*", "cacheRequest", ")", "{", "rw", ":=", "newResponseStreamer", "(", "w", ")", "\n", "rdr", ",", "err", ":=", "rw", ".", "Stream", ".", "NextReader", "(", ")", "\n", "if", "err", "!=", "nil", "{", "debugf", "(", "\"", "\"", ",", "err", ")", "\n", "w", ".", "Header", "(", ")", ".", "Set", "(", "CacheHeader", ",", "\"", "\"", ")", "\n", "h", ".", "upstream", ".", "ServeHTTP", "(", "w", ",", "r", ".", "Request", ")", "\n", "return", "\n", "}", "\n\n", "t", ":=", "Clock", "(", ")", "\n", "debugf", "(", "\"", "\"", ")", "\n", "rw", ".", "Header", "(", ")", ".", "Set", "(", "CacheHeader", ",", "\"", "\"", ")", "\n\n", "go", "func", "(", ")", "{", "h", ".", "upstream", ".", "ServeHTTP", "(", "rw", ",", "r", ".", "Request", ")", "\n", "rw", ".", "Stream", ".", "Close", "(", ")", "\n", "}", "(", ")", "\n", "rw", ".", "WaitHeaders", "(", ")", "\n", "debugf", "(", "\"", "\"", ",", "Clock", "(", ")", ".", "Sub", "(", "t", ")", ".", "String", "(", ")", ")", "\n\n", "// just the headers!", "res", ":=", "NewResourceBytes", "(", "rw", ".", "StatusCode", ",", "nil", ",", "rw", ".", "Header", "(", ")", ")", "\n", "if", "!", "h", ".", "isCacheable", "(", "res", ",", "r", ")", "{", "rdr", ".", "Close", "(", ")", "\n", "debugf", "(", "\"", "\"", ")", "\n", "rw", ".", "Header", "(", ")", ".", "Set", "(", "CacheHeader", ",", "\"", "\"", ")", "\n", "return", "\n", "}", "\n", "b", ",", "err", ":=", "ioutil", ".", "ReadAll", "(", "rdr", ")", "\n", "rdr", ".", "Close", "(", ")", "\n", "if", "err", "!=", "nil", "{", "debugf", "(", "\"", "\"", ",", "err", ")", "\n", "rw", ".", "Header", "(", ")", ".", "Set", "(", "CacheHeader", ",", "\"", "\"", ")", "\n", "return", "\n", "}", "\n", "debugf", "(", "\"", "\"", ",", "Clock", "(", ")", ".", "Sub", "(", "t", ")", ".", "String", "(", ")", ")", "\n", "res", ".", "ReadSeekCloser", "=", "&", "byteReadSeekCloser", "{", "bytes", ".", "NewReader", "(", "b", ")", "}", "\n\n", "if", "age", ",", "err", ":=", "correctedAge", "(", "res", ".", "Header", "(", ")", ",", "t", ",", "Clock", "(", ")", ")", ";", "err", "==", "nil", "{", "res", ".", "Header", "(", ")", ".", "Set", "(", "\"", "\"", ",", "strconv", ".", "Itoa", "(", "int", "(", "math", ".", "Ceil", "(", "age", ".", "Seconds", "(", ")", ")", ")", ")", ")", "\n", "}", "else", "{", "debugf", "(", "\"", "\"", ",", "err", ".", "Error", "(", ")", ")", "\n", "}", "\n\n", "rw", ".", "Header", "(", ")", ".", "Set", "(", "ProxyDateHeader", ",", "Clock", "(", ")", ".", "Format", "(", "http", ".", "TimeFormat", ")", ")", "\n", "h", ".", "storeResource", "(", "res", ",", "r", ")", "\n", "}" ]
// passUpstream makes the request via the upstream handler and stores the result
[ "passUpstream", "makes", "the", "request", "via", "the", "upstream", "handler", "and", "stores", "the", "result" ]
2de7d84cb2513697e071961c5a5a81060c4382b5
https://github.com/lox/httpcache/blob/2de7d84cb2513697e071961c5a5a81060c4382b5/handler.go#L239-L286
1,301
lox/httpcache
handler.go
lookup
func (h *Handler) lookup(req *cacheRequest) (*Resource, error) { res, err := h.cache.Retrieve(req.Key.String()) // HEAD requests can possibly be served from GET if err == ErrNotFoundInCache && req.Method == "HEAD" { res, err = h.cache.Retrieve(req.Key.ForMethod("GET").String()) if err != nil { return nil, err } if res.HasExplicitExpiration() && req.isCacheable() { debugf("using cached GET request for serving HEAD") return res, nil } else { return nil, ErrNotFoundInCache } } else if err != nil { return res, err } // Secondary lookup for Vary if vary := res.Header().Get("Vary"); vary != "" { res, err = h.cache.Retrieve(req.Key.Vary(vary, req.Request).String()) if err != nil { return res, err } } return res, nil }
go
func (h *Handler) lookup(req *cacheRequest) (*Resource, error) { res, err := h.cache.Retrieve(req.Key.String()) // HEAD requests can possibly be served from GET if err == ErrNotFoundInCache && req.Method == "HEAD" { res, err = h.cache.Retrieve(req.Key.ForMethod("GET").String()) if err != nil { return nil, err } if res.HasExplicitExpiration() && req.isCacheable() { debugf("using cached GET request for serving HEAD") return res, nil } else { return nil, ErrNotFoundInCache } } else if err != nil { return res, err } // Secondary lookup for Vary if vary := res.Header().Get("Vary"); vary != "" { res, err = h.cache.Retrieve(req.Key.Vary(vary, req.Request).String()) if err != nil { return res, err } } return res, nil }
[ "func", "(", "h", "*", "Handler", ")", "lookup", "(", "req", "*", "cacheRequest", ")", "(", "*", "Resource", ",", "error", ")", "{", "res", ",", "err", ":=", "h", ".", "cache", ".", "Retrieve", "(", "req", ".", "Key", ".", "String", "(", ")", ")", "\n\n", "// HEAD requests can possibly be served from GET", "if", "err", "==", "ErrNotFoundInCache", "&&", "req", ".", "Method", "==", "\"", "\"", "{", "res", ",", "err", "=", "h", ".", "cache", ".", "Retrieve", "(", "req", ".", "Key", ".", "ForMethod", "(", "\"", "\"", ")", ".", "String", "(", ")", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "if", "res", ".", "HasExplicitExpiration", "(", ")", "&&", "req", ".", "isCacheable", "(", ")", "{", "debugf", "(", "\"", "\"", ")", "\n", "return", "res", ",", "nil", "\n", "}", "else", "{", "return", "nil", ",", "ErrNotFoundInCache", "\n", "}", "\n", "}", "else", "if", "err", "!=", "nil", "{", "return", "res", ",", "err", "\n", "}", "\n\n", "// Secondary lookup for Vary", "if", "vary", ":=", "res", ".", "Header", "(", ")", ".", "Get", "(", "\"", "\"", ")", ";", "vary", "!=", "\"", "\"", "{", "res", ",", "err", "=", "h", ".", "cache", ".", "Retrieve", "(", "req", ".", "Key", ".", "Vary", "(", "vary", ",", "req", ".", "Request", ")", ".", "String", "(", ")", ")", "\n", "if", "err", "!=", "nil", "{", "return", "res", ",", "err", "\n", "}", "\n", "}", "\n\n", "return", "res", ",", "nil", "\n", "}" ]
// lookupResource finds the best matching Resource for the // request, or nil and ErrNotFoundInCache if none is found
[ "lookupResource", "finds", "the", "best", "matching", "Resource", "for", "the", "request", "or", "nil", "and", "ErrNotFoundInCache", "if", "none", "is", "found" ]
2de7d84cb2513697e071961c5a5a81060c4382b5
https://github.com/lox/httpcache/blob/2de7d84cb2513697e071961c5a5a81060c4382b5/handler.go#L438-L467
1,302
lox/httpcache
handler.go
Resource
func (rw *responseStreamer) Resource() *Resource { r, err := rw.Stream.NextReader() if err == nil { b, err := ioutil.ReadAll(r) r.Close() if err == nil { return NewResourceBytes(rw.StatusCode, b, rw.Header()) } } return &Resource{ header: rw.Header(), statusCode: rw.StatusCode, ReadSeekCloser: errReadSeekCloser{err}, } }
go
func (rw *responseStreamer) Resource() *Resource { r, err := rw.Stream.NextReader() if err == nil { b, err := ioutil.ReadAll(r) r.Close() if err == nil { return NewResourceBytes(rw.StatusCode, b, rw.Header()) } } return &Resource{ header: rw.Header(), statusCode: rw.StatusCode, ReadSeekCloser: errReadSeekCloser{err}, } }
[ "func", "(", "rw", "*", "responseStreamer", ")", "Resource", "(", ")", "*", "Resource", "{", "r", ",", "err", ":=", "rw", ".", "Stream", ".", "NextReader", "(", ")", "\n", "if", "err", "==", "nil", "{", "b", ",", "err", ":=", "ioutil", ".", "ReadAll", "(", "r", ")", "\n", "r", ".", "Close", "(", ")", "\n", "if", "err", "==", "nil", "{", "return", "NewResourceBytes", "(", "rw", ".", "StatusCode", ",", "b", ",", "rw", ".", "Header", "(", ")", ")", "\n", "}", "\n", "}", "\n", "return", "&", "Resource", "{", "header", ":", "rw", ".", "Header", "(", ")", ",", "statusCode", ":", "rw", ".", "StatusCode", ",", "ReadSeekCloser", ":", "errReadSeekCloser", "{", "err", "}", ",", "}", "\n", "}" ]
// Resource returns a copy of the responseStreamer as a Resource object
[ "Resource", "returns", "a", "copy", "of", "the", "responseStreamer", "as", "a", "Resource", "object" ]
2de7d84cb2513697e071961c5a5a81060c4382b5
https://github.com/lox/httpcache/blob/2de7d84cb2513697e071961c5a5a81060c4382b5/handler.go#L565-L579
1,303
lox/httpcache
resource.go
Age
func (r *Resource) Age() (time.Duration, error) { var age time.Duration if ageInt, err := intHeader("Age", r.header); err == nil { age = time.Second * time.Duration(ageInt) } if proxyDate, err := timeHeader(ProxyDateHeader, r.header); err == nil { return Clock().Sub(proxyDate) + age, nil } if date, err := timeHeader("Date", r.header); err == nil { return Clock().Sub(date) + age, nil } return time.Duration(0), errors.New("Unable to calculate age") }
go
func (r *Resource) Age() (time.Duration, error) { var age time.Duration if ageInt, err := intHeader("Age", r.header); err == nil { age = time.Second * time.Duration(ageInt) } if proxyDate, err := timeHeader(ProxyDateHeader, r.header); err == nil { return Clock().Sub(proxyDate) + age, nil } if date, err := timeHeader("Date", r.header); err == nil { return Clock().Sub(date) + age, nil } return time.Duration(0), errors.New("Unable to calculate age") }
[ "func", "(", "r", "*", "Resource", ")", "Age", "(", ")", "(", "time", ".", "Duration", ",", "error", ")", "{", "var", "age", "time", ".", "Duration", "\n\n", "if", "ageInt", ",", "err", ":=", "intHeader", "(", "\"", "\"", ",", "r", ".", "header", ")", ";", "err", "==", "nil", "{", "age", "=", "time", ".", "Second", "*", "time", ".", "Duration", "(", "ageInt", ")", "\n", "}", "\n\n", "if", "proxyDate", ",", "err", ":=", "timeHeader", "(", "ProxyDateHeader", ",", "r", ".", "header", ")", ";", "err", "==", "nil", "{", "return", "Clock", "(", ")", ".", "Sub", "(", "proxyDate", ")", "+", "age", ",", "nil", "\n", "}", "\n\n", "if", "date", ",", "err", ":=", "timeHeader", "(", "\"", "\"", ",", "r", ".", "header", ")", ";", "err", "==", "nil", "{", "return", "Clock", "(", ")", ".", "Sub", "(", "date", ")", "+", "age", ",", "nil", "\n", "}", "\n\n", "return", "time", ".", "Duration", "(", "0", ")", ",", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "}" ]
// Calculate the age of the resource
[ "Calculate", "the", "age", "of", "the", "resource" ]
2de7d84cb2513697e071961c5a5a81060c4382b5
https://github.com/lox/httpcache/blob/2de7d84cb2513697e071961c5a5a81060c4382b5/resource.go#L144-L160
1,304
lox/httpcache
key.go
NewKey
func NewKey(method string, u *url.URL, h http.Header) Key { return Key{method: method, header: h, u: *u, vary: []string{}} }
go
func NewKey(method string, u *url.URL, h http.Header) Key { return Key{method: method, header: h, u: *u, vary: []string{}} }
[ "func", "NewKey", "(", "method", "string", ",", "u", "*", "url", ".", "URL", ",", "h", "http", ".", "Header", ")", "Key", "{", "return", "Key", "{", "method", ":", "method", ",", "header", ":", "h", ",", "u", ":", "*", "u", ",", "vary", ":", "[", "]", "string", "{", "}", "}", "\n", "}" ]
// NewKey returns a new Key instance
[ "NewKey", "returns", "a", "new", "Key", "instance" ]
2de7d84cb2513697e071961c5a5a81060c4382b5
https://github.com/lox/httpcache/blob/2de7d84cb2513697e071961c5a5a81060c4382b5/key.go#L20-L22
1,305
lox/httpcache
key.go
NewRequestKey
func NewRequestKey(r *http.Request) Key { URL := r.URL if location := r.Header.Get("Content-Location"); location != "" { u, err := url.Parse(location) if err == nil { if !u.IsAbs() { u = r.URL.ResolveReference(u) } if u.Host != r.Host { debugf("illegal host %q in Content-Location", u.Host) } else { debugf("using Content-Location: %q", u.String()) URL = u } } else { debugf("failed to parse Content-Location %q", location) } } return NewKey(r.Method, URL, r.Header) }
go
func NewRequestKey(r *http.Request) Key { URL := r.URL if location := r.Header.Get("Content-Location"); location != "" { u, err := url.Parse(location) if err == nil { if !u.IsAbs() { u = r.URL.ResolveReference(u) } if u.Host != r.Host { debugf("illegal host %q in Content-Location", u.Host) } else { debugf("using Content-Location: %q", u.String()) URL = u } } else { debugf("failed to parse Content-Location %q", location) } } return NewKey(r.Method, URL, r.Header) }
[ "func", "NewRequestKey", "(", "r", "*", "http", ".", "Request", ")", "Key", "{", "URL", ":=", "r", ".", "URL", "\n\n", "if", "location", ":=", "r", ".", "Header", ".", "Get", "(", "\"", "\"", ")", ";", "location", "!=", "\"", "\"", "{", "u", ",", "err", ":=", "url", ".", "Parse", "(", "location", ")", "\n", "if", "err", "==", "nil", "{", "if", "!", "u", ".", "IsAbs", "(", ")", "{", "u", "=", "r", ".", "URL", ".", "ResolveReference", "(", "u", ")", "\n", "}", "\n", "if", "u", ".", "Host", "!=", "r", ".", "Host", "{", "debugf", "(", "\"", "\"", ",", "u", ".", "Host", ")", "\n", "}", "else", "{", "debugf", "(", "\"", "\"", ",", "u", ".", "String", "(", ")", ")", "\n", "URL", "=", "u", "\n", "}", "\n", "}", "else", "{", "debugf", "(", "\"", "\"", ",", "location", ")", "\n", "}", "\n", "}", "\n\n", "return", "NewKey", "(", "r", ".", "Method", ",", "URL", ",", "r", ".", "Header", ")", "\n", "}" ]
// NewRequestKey generates a Key for a request
[ "NewRequestKey", "generates", "a", "Key", "for", "a", "request" ]
2de7d84cb2513697e071961c5a5a81060c4382b5
https://github.com/lox/httpcache/blob/2de7d84cb2513697e071961c5a5a81060c4382b5/key.go#L25-L46
1,306
lox/httpcache
key.go
ForMethod
func (k Key) ForMethod(method string) Key { k2 := k k2.method = method return k2 }
go
func (k Key) ForMethod(method string) Key { k2 := k k2.method = method return k2 }
[ "func", "(", "k", "Key", ")", "ForMethod", "(", "method", "string", ")", "Key", "{", "k2", ":=", "k", "\n", "k2", ".", "method", "=", "method", "\n", "return", "k2", "\n", "}" ]
// ForMethod returns a new Key with a given method
[ "ForMethod", "returns", "a", "new", "Key", "with", "a", "given", "method" ]
2de7d84cb2513697e071961c5a5a81060c4382b5
https://github.com/lox/httpcache/blob/2de7d84cb2513697e071961c5a5a81060c4382b5/key.go#L49-L53
1,307
lox/httpcache
key.go
Vary
func (k Key) Vary(varyHeader string, r *http.Request) Key { k2 := k for _, header := range strings.Split(varyHeader, ", ") { k2.vary = append(k2.vary, header+"="+r.Header.Get(header)) } return k2 }
go
func (k Key) Vary(varyHeader string, r *http.Request) Key { k2 := k for _, header := range strings.Split(varyHeader, ", ") { k2.vary = append(k2.vary, header+"="+r.Header.Get(header)) } return k2 }
[ "func", "(", "k", "Key", ")", "Vary", "(", "varyHeader", "string", ",", "r", "*", "http", ".", "Request", ")", "Key", "{", "k2", ":=", "k", "\n\n", "for", "_", ",", "header", ":=", "range", "strings", ".", "Split", "(", "varyHeader", ",", "\"", "\"", ")", "{", "k2", ".", "vary", "=", "append", "(", "k2", ".", "vary", ",", "header", "+", "\"", "\"", "+", "r", ".", "Header", ".", "Get", "(", "header", ")", ")", "\n", "}", "\n\n", "return", "k2", "\n", "}" ]
// Vary returns a Key that is varied on particular headers in a http.Request
[ "Vary", "returns", "a", "Key", "that", "is", "varied", "on", "particular", "headers", "in", "a", "http", ".", "Request" ]
2de7d84cb2513697e071961c5a5a81060c4382b5
https://github.com/lox/httpcache/blob/2de7d84cb2513697e071961c5a5a81060c4382b5/key.go#L56-L64
1,308
tmc/grpc-websocket-proxy
wsproxy/websocket_proxy.go
WithForwardedHeaders
func WithForwardedHeaders(fn func(header string) bool) Option { return func(p *Proxy) { p.headerForwarder = fn } }
go
func WithForwardedHeaders(fn func(header string) bool) Option { return func(p *Proxy) { p.headerForwarder = fn } }
[ "func", "WithForwardedHeaders", "(", "fn", "func", "(", "header", "string", ")", "bool", ")", "Option", "{", "return", "func", "(", "p", "*", "Proxy", ")", "{", "p", ".", "headerForwarder", "=", "fn", "\n", "}", "\n", "}" ]
// WithForwardedHeaders allows controlling which headers are forwarded.
[ "WithForwardedHeaders", "allows", "controlling", "which", "headers", "are", "forwarded", "." ]
0ad062ec5ee553a48f6dbd280b7a1b5638e8a113
https://github.com/tmc/grpc-websocket-proxy/blob/0ad062ec5ee553a48f6dbd280b7a1b5638e8a113/wsproxy/websocket_proxy.go#L77-L81
1,309
tmc/grpc-websocket-proxy
wsproxy/websocket_proxy.go
transformSubProtocolHeader
func transformSubProtocolHeader(header string) string { tokens := strings.SplitN(header, "Bearer,", 2) if len(tokens) < 2 { return "" } return fmt.Sprintf("Bearer %v", strings.Trim(tokens[1], " ")) }
go
func transformSubProtocolHeader(header string) string { tokens := strings.SplitN(header, "Bearer,", 2) if len(tokens) < 2 { return "" } return fmt.Sprintf("Bearer %v", strings.Trim(tokens[1], " ")) }
[ "func", "transformSubProtocolHeader", "(", "header", "string", ")", "string", "{", "tokens", ":=", "strings", ".", "SplitN", "(", "header", ",", "\"", "\"", ",", "2", ")", "\n\n", "if", "len", "(", "tokens", ")", "<", "2", "{", "return", "\"", "\"", "\n", "}", "\n\n", "return", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "strings", ".", "Trim", "(", "tokens", "[", "1", "]", ",", "\"", "\"", ")", ")", "\n", "}" ]
// IE and Edge do not delimit Sec-WebSocket-Protocol strings with spaces
[ "IE", "and", "Edge", "do", "not", "delimit", "Sec", "-", "WebSocket", "-", "Protocol", "strings", "with", "spaces" ]
0ad062ec5ee553a48f6dbd280b7a1b5638e8a113
https://github.com/tmc/grpc-websocket-proxy/blob/0ad062ec5ee553a48f6dbd280b7a1b5638e8a113/wsproxy/websocket_proxy.go#L269-L277
1,310
albrow/jobs
worker.go
start
func (w *worker) start() { go func() { for job := range w.jobs { w.doJob(job) } w.wg.Done() }() }
go
func (w *worker) start() { go func() { for job := range w.jobs { w.doJob(job) } w.wg.Done() }() }
[ "func", "(", "w", "*", "worker", ")", "start", "(", ")", "{", "go", "func", "(", ")", "{", "for", "job", ":=", "range", "w", ".", "jobs", "{", "w", ".", "doJob", "(", "job", ")", "\n", "}", "\n", "w", ".", "wg", ".", "Done", "(", ")", "\n", "}", "(", ")", "\n", "}" ]
// start starts a goroutine in which the worker will continuously // execute jobs until the jobs channel is closed.
[ "start", "starts", "a", "goroutine", "in", "which", "the", "worker", "will", "continuously", "execute", "jobs", "until", "the", "jobs", "channel", "is", "closed", "." ]
2580c613deb47dce29730c128a5dee775f552a1d
https://github.com/albrow/jobs/blob/2580c613deb47dce29730c128a5dee775f552a1d/worker.go#L25-L32
1,311
albrow/jobs
worker.go
doJob
func (w *worker) doJob(job *Job) { if w.afterFunc != nil { defer w.afterFunc(job) } defer func() { if r := recover(); r != nil { // Get a reasonable error message from the panic msg := "" if err, ok := r.(error); ok { msg = err.Error() } else { msg = fmt.Sprint(r) } if err := setJobError(job, msg); err != nil { // Nothing left to do but panic panic(err) } } }() // Set the started field and save the job job.started = time.Now().UTC().UnixNano() t0 := newTransaction() t0.setJobField(job, "started", job.started) if err := t0.exec(); err != nil { if err := setJobError(job, err.Error()); err != nil { // NOTE: panics will be caught by the recover statment above panic(err) } return } // Use reflection to instantiate arguments for the handler handlerArgs := []reflect.Value{} if job.typ.dataType != nil { // Instantiate a new variable to hold this argument dataVal := reflect.New(job.typ.dataType) if err := decode(job.data, dataVal.Interface()); err != nil { if err := setJobError(job, err.Error()); err != nil { // NOTE: panics will be caught by the recover statment above panic(err) } return } handlerArgs = append(handlerArgs, dataVal.Elem()) } // Call the handler using the arguments we just instantiated handlerVal := reflect.ValueOf(job.typ.handler) returnVals := handlerVal.Call(handlerArgs) // Set the finished timestamp job.finished = time.Now().UTC().UnixNano() // Check if the error return value was nil if !returnVals[0].IsNil() { err := returnVals[0].Interface().(error) if err := setJobError(job, err.Error()); err != nil { // NOTE: panics will be caught by the recover statment above panic(err) } return } t1 := newTransaction() t1.setJobField(job, "finished", job.finished) if job.IsRecurring() { // If the job is recurring, reschedule and set status to queued job.time = job.NextTime() t1.setJobField(job, "time", job.time) t1.addJobToTimeIndex(job) t1.setStatus(job, StatusQueued) } else { // Otherwise, set status to finished t1.setStatus(job, StatusFinished) } if err := t1.exec(); err != nil { if err := setJobError(job, err.Error()); err != nil { // NOTE: panics will be caught by the recover statment above panic(err) } return } }
go
func (w *worker) doJob(job *Job) { if w.afterFunc != nil { defer w.afterFunc(job) } defer func() { if r := recover(); r != nil { // Get a reasonable error message from the panic msg := "" if err, ok := r.(error); ok { msg = err.Error() } else { msg = fmt.Sprint(r) } if err := setJobError(job, msg); err != nil { // Nothing left to do but panic panic(err) } } }() // Set the started field and save the job job.started = time.Now().UTC().UnixNano() t0 := newTransaction() t0.setJobField(job, "started", job.started) if err := t0.exec(); err != nil { if err := setJobError(job, err.Error()); err != nil { // NOTE: panics will be caught by the recover statment above panic(err) } return } // Use reflection to instantiate arguments for the handler handlerArgs := []reflect.Value{} if job.typ.dataType != nil { // Instantiate a new variable to hold this argument dataVal := reflect.New(job.typ.dataType) if err := decode(job.data, dataVal.Interface()); err != nil { if err := setJobError(job, err.Error()); err != nil { // NOTE: panics will be caught by the recover statment above panic(err) } return } handlerArgs = append(handlerArgs, dataVal.Elem()) } // Call the handler using the arguments we just instantiated handlerVal := reflect.ValueOf(job.typ.handler) returnVals := handlerVal.Call(handlerArgs) // Set the finished timestamp job.finished = time.Now().UTC().UnixNano() // Check if the error return value was nil if !returnVals[0].IsNil() { err := returnVals[0].Interface().(error) if err := setJobError(job, err.Error()); err != nil { // NOTE: panics will be caught by the recover statment above panic(err) } return } t1 := newTransaction() t1.setJobField(job, "finished", job.finished) if job.IsRecurring() { // If the job is recurring, reschedule and set status to queued job.time = job.NextTime() t1.setJobField(job, "time", job.time) t1.addJobToTimeIndex(job) t1.setStatus(job, StatusQueued) } else { // Otherwise, set status to finished t1.setStatus(job, StatusFinished) } if err := t1.exec(); err != nil { if err := setJobError(job, err.Error()); err != nil { // NOTE: panics will be caught by the recover statment above panic(err) } return } }
[ "func", "(", "w", "*", "worker", ")", "doJob", "(", "job", "*", "Job", ")", "{", "if", "w", ".", "afterFunc", "!=", "nil", "{", "defer", "w", ".", "afterFunc", "(", "job", ")", "\n", "}", "\n\n", "defer", "func", "(", ")", "{", "if", "r", ":=", "recover", "(", ")", ";", "r", "!=", "nil", "{", "// Get a reasonable error message from the panic", "msg", ":=", "\"", "\"", "\n", "if", "err", ",", "ok", ":=", "r", ".", "(", "error", ")", ";", "ok", "{", "msg", "=", "err", ".", "Error", "(", ")", "\n", "}", "else", "{", "msg", "=", "fmt", ".", "Sprint", "(", "r", ")", "\n", "}", "\n", "if", "err", ":=", "setJobError", "(", "job", ",", "msg", ")", ";", "err", "!=", "nil", "{", "// Nothing left to do but panic", "panic", "(", "err", ")", "\n", "}", "\n", "}", "\n", "}", "(", ")", "\n", "// Set the started field and save the job", "job", ".", "started", "=", "time", ".", "Now", "(", ")", ".", "UTC", "(", ")", ".", "UnixNano", "(", ")", "\n", "t0", ":=", "newTransaction", "(", ")", "\n", "t0", ".", "setJobField", "(", "job", ",", "\"", "\"", ",", "job", ".", "started", ")", "\n", "if", "err", ":=", "t0", ".", "exec", "(", ")", ";", "err", "!=", "nil", "{", "if", "err", ":=", "setJobError", "(", "job", ",", "err", ".", "Error", "(", ")", ")", ";", "err", "!=", "nil", "{", "// NOTE: panics will be caught by the recover statment above", "panic", "(", "err", ")", "\n", "}", "\n", "return", "\n", "}", "\n", "// Use reflection to instantiate arguments for the handler", "handlerArgs", ":=", "[", "]", "reflect", ".", "Value", "{", "}", "\n", "if", "job", ".", "typ", ".", "dataType", "!=", "nil", "{", "// Instantiate a new variable to hold this argument", "dataVal", ":=", "reflect", ".", "New", "(", "job", ".", "typ", ".", "dataType", ")", "\n", "if", "err", ":=", "decode", "(", "job", ".", "data", ",", "dataVal", ".", "Interface", "(", ")", ")", ";", "err", "!=", "nil", "{", "if", "err", ":=", "setJobError", "(", "job", ",", "err", ".", "Error", "(", ")", ")", ";", "err", "!=", "nil", "{", "// NOTE: panics will be caught by the recover statment above", "panic", "(", "err", ")", "\n", "}", "\n", "return", "\n", "}", "\n", "handlerArgs", "=", "append", "(", "handlerArgs", ",", "dataVal", ".", "Elem", "(", ")", ")", "\n", "}", "\n", "// Call the handler using the arguments we just instantiated", "handlerVal", ":=", "reflect", ".", "ValueOf", "(", "job", ".", "typ", ".", "handler", ")", "\n", "returnVals", ":=", "handlerVal", ".", "Call", "(", "handlerArgs", ")", "\n", "// Set the finished timestamp", "job", ".", "finished", "=", "time", ".", "Now", "(", ")", ".", "UTC", "(", ")", ".", "UnixNano", "(", ")", "\n\n", "// Check if the error return value was nil", "if", "!", "returnVals", "[", "0", "]", ".", "IsNil", "(", ")", "{", "err", ":=", "returnVals", "[", "0", "]", ".", "Interface", "(", ")", ".", "(", "error", ")", "\n", "if", "err", ":=", "setJobError", "(", "job", ",", "err", ".", "Error", "(", ")", ")", ";", "err", "!=", "nil", "{", "// NOTE: panics will be caught by the recover statment above", "panic", "(", "err", ")", "\n", "}", "\n", "return", "\n", "}", "\n", "t1", ":=", "newTransaction", "(", ")", "\n", "t1", ".", "setJobField", "(", "job", ",", "\"", "\"", ",", "job", ".", "finished", ")", "\n", "if", "job", ".", "IsRecurring", "(", ")", "{", "// If the job is recurring, reschedule and set status to queued", "job", ".", "time", "=", "job", ".", "NextTime", "(", ")", "\n", "t1", ".", "setJobField", "(", "job", ",", "\"", "\"", ",", "job", ".", "time", ")", "\n", "t1", ".", "addJobToTimeIndex", "(", "job", ")", "\n", "t1", ".", "setStatus", "(", "job", ",", "StatusQueued", ")", "\n", "}", "else", "{", "// Otherwise, set status to finished", "t1", ".", "setStatus", "(", "job", ",", "StatusFinished", ")", "\n", "}", "\n", "if", "err", ":=", "t1", ".", "exec", "(", ")", ";", "err", "!=", "nil", "{", "if", "err", ":=", "setJobError", "(", "job", ",", "err", ".", "Error", "(", ")", ")", ";", "err", "!=", "nil", "{", "// NOTE: panics will be caught by the recover statment above", "panic", "(", "err", ")", "\n", "}", "\n", "return", "\n", "}", "\n", "}" ]
// doJob executes the given job. It also sets the status and timestamps for // the job appropriately depending on the outcome of the execution.
[ "doJob", "executes", "the", "given", "job", ".", "It", "also", "sets", "the", "status", "and", "timestamps", "for", "the", "job", "appropriately", "depending", "on", "the", "outcome", "of", "the", "execution", "." ]
2580c613deb47dce29730c128a5dee775f552a1d
https://github.com/albrow/jobs/blob/2580c613deb47dce29730c128a5dee775f552a1d/worker.go#L36-L115
1,312
albrow/jobs
utils.go
generateRandomId
func generateRandomId() string { timeInt := time.Now().UnixNano() timeString := strconv.FormatInt(timeInt, 36) randomString := uniuri.NewLen(16) return randomString + timeString }
go
func generateRandomId() string { timeInt := time.Now().UnixNano() timeString := strconv.FormatInt(timeInt, 36) randomString := uniuri.NewLen(16) return randomString + timeString }
[ "func", "generateRandomId", "(", ")", "string", "{", "timeInt", ":=", "time", ".", "Now", "(", ")", ".", "UnixNano", "(", ")", "\n", "timeString", ":=", "strconv", ".", "FormatInt", "(", "timeInt", ",", "36", ")", "\n", "randomString", ":=", "uniuri", ".", "NewLen", "(", "16", ")", "\n", "return", "randomString", "+", "timeString", "\n", "}" ]
// generateRandomId generates a random string that is more or less // garunteed to be unique.
[ "generateRandomId", "generates", "a", "random", "string", "that", "is", "more", "or", "less", "garunteed", "to", "be", "unique", "." ]
2580c613deb47dce29730c128a5dee775f552a1d
https://github.com/albrow/jobs/blob/2580c613deb47dce29730c128a5dee775f552a1d/utils.go#L15-L20
1,313
albrow/jobs
job.go
save
func (j *Job) save() error { t := newTransaction() t.saveJob(j) if err := t.exec(); err != nil { return err } return nil }
go
func (j *Job) save() error { t := newTransaction() t.saveJob(j) if err := t.exec(); err != nil { return err } return nil }
[ "func", "(", "j", "*", "Job", ")", "save", "(", ")", "error", "{", "t", ":=", "newTransaction", "(", ")", "\n", "t", ".", "saveJob", "(", "j", ")", "\n", "if", "err", ":=", "t", ".", "exec", "(", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// save writes the job to the database and adds it to the appropriate indexes and status // sets, but does not enqueue it. If you want to add it to the queue, use the enqueue method // after save.
[ "save", "writes", "the", "job", "to", "the", "database", "and", "adds", "it", "to", "the", "appropriate", "indexes", "and", "status", "sets", "but", "does", "not", "enqueue", "it", ".", "If", "you", "want", "to", "add", "it", "to", "the", "queue", "use", "the", "enqueue", "method", "after", "save", "." ]
2580c613deb47dce29730c128a5dee775f552a1d
https://github.com/albrow/jobs/blob/2580c613deb47dce29730c128a5dee775f552a1d/job.go#L145-L152
1,314
albrow/jobs
job.go
saveJob
func (t *transaction) saveJob(job *Job) { // Generate id if needed if job.id == "" { job.id = generateRandomId() } // Set status to saved if needed if job.status == "" { job.status = StatusSaved } // Add the job attributes to a hash t.command("HMSET", job.mainHashArgs(), nil) // Add the job to the appropriate status set t.setStatus(job, job.status) // Add the job to the time index t.addJobToTimeIndex(job) }
go
func (t *transaction) saveJob(job *Job) { // Generate id if needed if job.id == "" { job.id = generateRandomId() } // Set status to saved if needed if job.status == "" { job.status = StatusSaved } // Add the job attributes to a hash t.command("HMSET", job.mainHashArgs(), nil) // Add the job to the appropriate status set t.setStatus(job, job.status) // Add the job to the time index t.addJobToTimeIndex(job) }
[ "func", "(", "t", "*", "transaction", ")", "saveJob", "(", "job", "*", "Job", ")", "{", "// Generate id if needed", "if", "job", ".", "id", "==", "\"", "\"", "{", "job", ".", "id", "=", "generateRandomId", "(", ")", "\n", "}", "\n", "// Set status to saved if needed", "if", "job", ".", "status", "==", "\"", "\"", "{", "job", ".", "status", "=", "StatusSaved", "\n", "}", "\n", "// Add the job attributes to a hash", "t", ".", "command", "(", "\"", "\"", ",", "job", ".", "mainHashArgs", "(", ")", ",", "nil", ")", "\n", "// Add the job to the appropriate status set", "t", ".", "setStatus", "(", "job", ",", "job", ".", "status", ")", "\n", "// Add the job to the time index", "t", ".", "addJobToTimeIndex", "(", "job", ")", "\n", "}" ]
// saveJob adds commands to the transaction to set all the fields for the main hash for the job, // add the job to the time index, move the job to the appropriate status set. It will // also mutate the job by 1) generating an id if the id is empty and 2) setting the status to // StatusSaved if the status is empty.
[ "saveJob", "adds", "commands", "to", "the", "transaction", "to", "set", "all", "the", "fields", "for", "the", "main", "hash", "for", "the", "job", "add", "the", "job", "to", "the", "time", "index", "move", "the", "job", "to", "the", "appropriate", "status", "set", ".", "It", "will", "also", "mutate", "the", "job", "by", "1", ")", "generating", "an", "id", "if", "the", "id", "is", "empty", "and", "2", ")", "setting", "the", "status", "to", "StatusSaved", "if", "the", "status", "is", "empty", "." ]
2580c613deb47dce29730c128a5dee775f552a1d
https://github.com/albrow/jobs/blob/2580c613deb47dce29730c128a5dee775f552a1d/job.go#L158-L173
1,315
albrow/jobs
job.go
addJobToTimeIndex
func (t *transaction) addJobToTimeIndex(job *Job) { t.addJobToSet(job, Keys.JobsTimeIndex, float64(job.time)) }
go
func (t *transaction) addJobToTimeIndex(job *Job) { t.addJobToSet(job, Keys.JobsTimeIndex, float64(job.time)) }
[ "func", "(", "t", "*", "transaction", ")", "addJobToTimeIndex", "(", "job", "*", "Job", ")", "{", "t", ".", "addJobToSet", "(", "job", ",", "Keys", ".", "JobsTimeIndex", ",", "float64", "(", "job", ".", "time", ")", ")", "\n", "}" ]
// addJobToTimeIndex adds commands to the transaction which will, when executed, // add the job id to the time index with a score equal to the job's time field. // If the job has been destroyed, addJobToTimeIndex will have no effect.
[ "addJobToTimeIndex", "adds", "commands", "to", "the", "transaction", "which", "will", "when", "executed", "add", "the", "job", "id", "to", "the", "time", "index", "with", "a", "score", "equal", "to", "the", "job", "s", "time", "field", ".", "If", "the", "job", "has", "been", "destroyed", "addJobToTimeIndex", "will", "have", "no", "effect", "." ]
2580c613deb47dce29730c128a5dee775f552a1d
https://github.com/albrow/jobs/blob/2580c613deb47dce29730c128a5dee775f552a1d/job.go#L178-L180
1,316
albrow/jobs
job.go
Refresh
func (j *Job) Refresh() error { t := newTransaction() t.scanJobById(j.id, j) if err := t.exec(); err != nil { return err } return nil }
go
func (j *Job) Refresh() error { t := newTransaction() t.scanJobById(j.id, j) if err := t.exec(); err != nil { return err } return nil }
[ "func", "(", "j", "*", "Job", ")", "Refresh", "(", ")", "error", "{", "t", ":=", "newTransaction", "(", ")", "\n", "t", ".", "scanJobById", "(", "j", ".", "id", ",", "j", ")", "\n", "if", "err", ":=", "t", ".", "exec", "(", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// Refresh mutates the job by setting its fields to the most recent data // found in the database. It returns an error if there was a problem connecting // to the database or if the job was destroyed.
[ "Refresh", "mutates", "the", "job", "by", "setting", "its", "fields", "to", "the", "most", "recent", "data", "found", "in", "the", "database", ".", "It", "returns", "an", "error", "if", "there", "was", "a", "problem", "connecting", "to", "the", "database", "or", "if", "the", "job", "was", "destroyed", "." ]
2580c613deb47dce29730c128a5dee775f552a1d
https://github.com/albrow/jobs/blob/2580c613deb47dce29730c128a5dee775f552a1d/job.go#L185-L192
1,317
albrow/jobs
job.go
enqueue
func (j *Job) enqueue() error { if err := j.setStatus(StatusQueued); err != nil { return err } return nil }
go
func (j *Job) enqueue() error { if err := j.setStatus(StatusQueued); err != nil { return err } return nil }
[ "func", "(", "j", "*", "Job", ")", "enqueue", "(", ")", "error", "{", "if", "err", ":=", "j", ".", "setStatus", "(", "StatusQueued", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// enqueue adds the job to the queue and sets its status to StatusQueued. Queued jobs will // be completed by workers in order of priority. Attempting to enqueue a destroyed job // will have no effect.
[ "enqueue", "adds", "the", "job", "to", "the", "queue", "and", "sets", "its", "status", "to", "StatusQueued", ".", "Queued", "jobs", "will", "be", "completed", "by", "workers", "in", "order", "of", "priority", ".", "Attempting", "to", "enqueue", "a", "destroyed", "job", "will", "have", "no", "effect", "." ]
2580c613deb47dce29730c128a5dee775f552a1d
https://github.com/albrow/jobs/blob/2580c613deb47dce29730c128a5dee775f552a1d/job.go#L197-L202
1,318
albrow/jobs
job.go
Reschedule
func (j *Job) Reschedule(time time.Time) error { t := newTransaction() unixNanoTime := time.UTC().UnixNano() t.setJobField(j, "time", unixNanoTime) t.setStatus(j, StatusQueued) j.time = unixNanoTime t.addJobToTimeIndex(j) if err := t.exec(); err != nil { return err } j.status = StatusQueued return nil }
go
func (j *Job) Reschedule(time time.Time) error { t := newTransaction() unixNanoTime := time.UTC().UnixNano() t.setJobField(j, "time", unixNanoTime) t.setStatus(j, StatusQueued) j.time = unixNanoTime t.addJobToTimeIndex(j) if err := t.exec(); err != nil { return err } j.status = StatusQueued return nil }
[ "func", "(", "j", "*", "Job", ")", "Reschedule", "(", "time", "time", ".", "Time", ")", "error", "{", "t", ":=", "newTransaction", "(", ")", "\n", "unixNanoTime", ":=", "time", ".", "UTC", "(", ")", ".", "UnixNano", "(", ")", "\n", "t", ".", "setJobField", "(", "j", ",", "\"", "\"", ",", "unixNanoTime", ")", "\n", "t", ".", "setStatus", "(", "j", ",", "StatusQueued", ")", "\n", "j", ".", "time", "=", "unixNanoTime", "\n", "t", ".", "addJobToTimeIndex", "(", "j", ")", "\n", "if", "err", ":=", "t", ".", "exec", "(", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "j", ".", "status", "=", "StatusQueued", "\n", "return", "nil", "\n", "}" ]
// Reschedule reschedules the job with the given time. It can be used to reschedule // cancelled jobs. It may also be used to reschedule finished or failed jobs, however, // in most cases if you want to reschedule finished jobs you should use the ScheduleRecurring // method and if you want to reschedule failed jobs, you should set the number of retries > 0 // when registering the job type. Attempting to reschedule a destroyed job will have no effect. // Reschedule returns an error if there was a problem connecting to the database.
[ "Reschedule", "reschedules", "the", "job", "with", "the", "given", "time", ".", "It", "can", "be", "used", "to", "reschedule", "cancelled", "jobs", ".", "It", "may", "also", "be", "used", "to", "reschedule", "finished", "or", "failed", "jobs", "however", "in", "most", "cases", "if", "you", "want", "to", "reschedule", "finished", "jobs", "you", "should", "use", "the", "ScheduleRecurring", "method", "and", "if", "you", "want", "to", "reschedule", "failed", "jobs", "you", "should", "set", "the", "number", "of", "retries", ">", "0", "when", "registering", "the", "job", "type", ".", "Attempting", "to", "reschedule", "a", "destroyed", "job", "will", "have", "no", "effect", ".", "Reschedule", "returns", "an", "error", "if", "there", "was", "a", "problem", "connecting", "to", "the", "database", "." ]
2580c613deb47dce29730c128a5dee775f552a1d
https://github.com/albrow/jobs/blob/2580c613deb47dce29730c128a5dee775f552a1d/job.go#L210-L222
1,319
albrow/jobs
job.go
Cancel
func (j *Job) Cancel() error { if err := j.setStatus(StatusCancelled); err != nil { return err } return nil }
go
func (j *Job) Cancel() error { if err := j.setStatus(StatusCancelled); err != nil { return err } return nil }
[ "func", "(", "j", "*", "Job", ")", "Cancel", "(", ")", "error", "{", "if", "err", ":=", "j", ".", "setStatus", "(", "StatusCancelled", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// Cancel cancels the job, but does not remove it from the database. It will be // added to a list of cancelled jobs. If you wish to remove it from the database, // use the Destroy method. Attempting to cancel a destroyed job will have no effect.
[ "Cancel", "cancels", "the", "job", "but", "does", "not", "remove", "it", "from", "the", "database", ".", "It", "will", "be", "added", "to", "a", "list", "of", "cancelled", "jobs", ".", "If", "you", "wish", "to", "remove", "it", "from", "the", "database", "use", "the", "Destroy", "method", ".", "Attempting", "to", "cancel", "a", "destroyed", "job", "will", "have", "no", "effect", "." ]
2580c613deb47dce29730c128a5dee775f552a1d
https://github.com/albrow/jobs/blob/2580c613deb47dce29730c128a5dee775f552a1d/job.go#L227-L232
1,320
albrow/jobs
job.go
setError
func (j *Job) setError(err error) error { j.err = err t := newTransaction() t.setJobField(j, "error", j.err.Error()) if err := t.exec(); err != nil { return err } return nil }
go
func (j *Job) setError(err error) error { j.err = err t := newTransaction() t.setJobField(j, "error", j.err.Error()) if err := t.exec(); err != nil { return err } return nil }
[ "func", "(", "j", "*", "Job", ")", "setError", "(", "err", "error", ")", "error", "{", "j", ".", "err", "=", "err", "\n", "t", ":=", "newTransaction", "(", ")", "\n", "t", ".", "setJobField", "(", "j", ",", "\"", "\"", ",", "j", ".", "err", ".", "Error", "(", ")", ")", "\n", "if", "err", ":=", "t", ".", "exec", "(", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// setError sets the err property of j and adds it to the set of jobs which had errors. // If the job has been destroyed, setError will have no effect.
[ "setError", "sets", "the", "err", "property", "of", "j", "and", "adds", "it", "to", "the", "set", "of", "jobs", "which", "had", "errors", ".", "If", "the", "job", "has", "been", "destroyed", "setError", "will", "have", "no", "effect", "." ]
2580c613deb47dce29730c128a5dee775f552a1d
https://github.com/albrow/jobs/blob/2580c613deb47dce29730c128a5dee775f552a1d/job.go#L236-L244
1,321
albrow/jobs
job.go
Destroy
func (j *Job) Destroy() error { if j.id == "" { return fmt.Errorf("jobs: Cannot destroy job that doesn't have an id.") } // Start a new transaction t := newTransaction() // Call the script to destroy the job t.destroyJob(j) // Execute the transaction if err := t.exec(); err != nil { return err } j.status = StatusDestroyed return nil }
go
func (j *Job) Destroy() error { if j.id == "" { return fmt.Errorf("jobs: Cannot destroy job that doesn't have an id.") } // Start a new transaction t := newTransaction() // Call the script to destroy the job t.destroyJob(j) // Execute the transaction if err := t.exec(); err != nil { return err } j.status = StatusDestroyed return nil }
[ "func", "(", "j", "*", "Job", ")", "Destroy", "(", ")", "error", "{", "if", "j", ".", "id", "==", "\"", "\"", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ")", "\n", "}", "\n", "// Start a new transaction", "t", ":=", "newTransaction", "(", ")", "\n", "// Call the script to destroy the job", "t", ".", "destroyJob", "(", "j", ")", "\n", "// Execute the transaction", "if", "err", ":=", "t", ".", "exec", "(", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "j", ".", "status", "=", "StatusDestroyed", "\n", "return", "nil", "\n", "}" ]
// Destroy removes all traces of the job from the database. If the job is currently // being executed by a worker, the worker may still finish the job. Attempting to // destroy a job that has already been destroyed will have no effect, so it is safe // to call Destroy multiple times.
[ "Destroy", "removes", "all", "traces", "of", "the", "job", "from", "the", "database", ".", "If", "the", "job", "is", "currently", "being", "executed", "by", "a", "worker", "the", "worker", "may", "still", "finish", "the", "job", ".", "Attempting", "to", "destroy", "a", "job", "that", "has", "already", "been", "destroyed", "will", "have", "no", "effect", "so", "it", "is", "safe", "to", "call", "Destroy", "multiple", "times", "." ]
2580c613deb47dce29730c128a5dee775f552a1d
https://github.com/albrow/jobs/blob/2580c613deb47dce29730c128a5dee775f552a1d/job.go#L250-L264
1,322
albrow/jobs
job.go
setStatus
func (j *Job) setStatus(status Status) error { if j.id == "" { return fmt.Errorf("jobs: Cannot set status to %s because job doesn't have an id.", status) } if j.status == StatusDestroyed { return fmt.Errorf("jobs: Cannot set job:%s status to %s because it was destroyed.", j.id, status) } // Use a transaction to move the job to the appropriate status set and set its status t := newTransaction() t.setStatus(j, status) if err := t.exec(); err != nil { return err } j.status = status return nil }
go
func (j *Job) setStatus(status Status) error { if j.id == "" { return fmt.Errorf("jobs: Cannot set status to %s because job doesn't have an id.", status) } if j.status == StatusDestroyed { return fmt.Errorf("jobs: Cannot set job:%s status to %s because it was destroyed.", j.id, status) } // Use a transaction to move the job to the appropriate status set and set its status t := newTransaction() t.setStatus(j, status) if err := t.exec(); err != nil { return err } j.status = status return nil }
[ "func", "(", "j", "*", "Job", ")", "setStatus", "(", "status", "Status", ")", "error", "{", "if", "j", ".", "id", "==", "\"", "\"", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "status", ")", "\n", "}", "\n", "if", "j", ".", "status", "==", "StatusDestroyed", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "j", ".", "id", ",", "status", ")", "\n", "}", "\n", "// Use a transaction to move the job to the appropriate status set and set its status", "t", ":=", "newTransaction", "(", ")", "\n", "t", ".", "setStatus", "(", "j", ",", "status", ")", "\n", "if", "err", ":=", "t", ".", "exec", "(", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "j", ".", "status", "=", "status", "\n", "return", "nil", "\n", "}" ]
// setStatus updates the job's status in the database and moves it to the appropriate // status set. Attempting to set the status of a job which has been destroyed will have // no effect.
[ "setStatus", "updates", "the", "job", "s", "status", "in", "the", "database", "and", "moves", "it", "to", "the", "appropriate", "status", "set", ".", "Attempting", "to", "set", "the", "status", "of", "a", "job", "which", "has", "been", "destroyed", "will", "have", "no", "effect", "." ]
2580c613deb47dce29730c128a5dee775f552a1d
https://github.com/albrow/jobs/blob/2580c613deb47dce29730c128a5dee775f552a1d/job.go#L269-L284
1,323
albrow/jobs
job.go
mainHashArgs
func (j *Job) mainHashArgs() []interface{} { hashArgs := []interface{}{j.Key(), "data", string(j.data), "type", j.typ.name, "time", j.time, "freq", j.freq, "priority", j.priority, "retries", j.retries, "status", j.status, "started", j.started, "finished", j.finished, "poolId", j.poolId, } if j.err != nil { hashArgs = append(hashArgs, "error", j.err.Error()) } return hashArgs }
go
func (j *Job) mainHashArgs() []interface{} { hashArgs := []interface{}{j.Key(), "data", string(j.data), "type", j.typ.name, "time", j.time, "freq", j.freq, "priority", j.priority, "retries", j.retries, "status", j.status, "started", j.started, "finished", j.finished, "poolId", j.poolId, } if j.err != nil { hashArgs = append(hashArgs, "error", j.err.Error()) } return hashArgs }
[ "func", "(", "j", "*", "Job", ")", "mainHashArgs", "(", ")", "[", "]", "interface", "{", "}", "{", "hashArgs", ":=", "[", "]", "interface", "{", "}", "{", "j", ".", "Key", "(", ")", ",", "\"", "\"", ",", "string", "(", "j", ".", "data", ")", ",", "\"", "\"", ",", "j", ".", "typ", ".", "name", ",", "\"", "\"", ",", "j", ".", "time", ",", "\"", "\"", ",", "j", ".", "freq", ",", "\"", "\"", ",", "j", ".", "priority", ",", "\"", "\"", ",", "j", ".", "retries", ",", "\"", "\"", ",", "j", ".", "status", ",", "\"", "\"", ",", "j", ".", "started", ",", "\"", "\"", ",", "j", ".", "finished", ",", "\"", "\"", ",", "j", ".", "poolId", ",", "}", "\n", "if", "j", ".", "err", "!=", "nil", "{", "hashArgs", "=", "append", "(", "hashArgs", ",", "\"", "\"", ",", "j", ".", "err", ".", "Error", "(", ")", ")", "\n", "}", "\n", "return", "hashArgs", "\n", "}" ]
// mainHashArgs returns the args for the hash which will store the job data
[ "mainHashArgs", "returns", "the", "args", "for", "the", "hash", "which", "will", "store", "the", "job", "data" ]
2580c613deb47dce29730c128a5dee775f552a1d
https://github.com/albrow/jobs/blob/2580c613deb47dce29730c128a5dee775f552a1d/job.go#L287-L304
1,324
albrow/jobs
job.go
scanJob
func scanJob(reply interface{}, job *Job) error { fields, err := redis.Values(reply, nil) if err != nil { return err } else if len(fields) == 0 { return ErrorJobNotFound{} } else if len(fields)%2 != 0 { return fmt.Errorf("jobs: In scanJob: Expected length of fields to be even but got: %d", len(fields)) } for i := 0; i < len(fields)-1; i += 2 { fieldName, err := redis.String(fields[i], nil) if err != nil { return fmt.Errorf("jobs: In scanJob: Could not convert fieldName (fields[%d] = %v) of type %T to string.", i, fields[i], fields[i]) } fieldValue := fields[i+1] switch fieldName { case "id": if err := scanString(fieldValue, &(job.id)); err != nil { return err } case "data": if err := scanBytes(fieldValue, &(job.data)); err != nil { return err } case "type": typeName := "" if err := scanString(fieldValue, &typeName); err != nil { return err } Type, found := Types[typeName] if !found { return fmt.Errorf("jobs: In scanJob: Could not find Type with name = %s", typeName) } job.typ = Type case "time": if err := scanInt64(fieldValue, &(job.time)); err != nil { return err } case "freq": if err := scanInt64(fieldValue, &(job.freq)); err != nil { return err } case "priority": if err := scanInt(fieldValue, &(job.priority)); err != nil { return err } case "retries": if err := scanUint(fieldValue, &(job.retries)); err != nil { return err } case "status": status := "" if err := scanString(fieldValue, &status); err != nil { return err } job.status = Status(status) case "started": if err := scanInt64(fieldValue, &(job.started)); err != nil { return err } case "finished": if err := scanInt64(fieldValue, &(job.finished)); err != nil { return err } case "poolId": if err := scanString(fieldValue, &(job.poolId)); err != nil { return err } } } return nil }
go
func scanJob(reply interface{}, job *Job) error { fields, err := redis.Values(reply, nil) if err != nil { return err } else if len(fields) == 0 { return ErrorJobNotFound{} } else if len(fields)%2 != 0 { return fmt.Errorf("jobs: In scanJob: Expected length of fields to be even but got: %d", len(fields)) } for i := 0; i < len(fields)-1; i += 2 { fieldName, err := redis.String(fields[i], nil) if err != nil { return fmt.Errorf("jobs: In scanJob: Could not convert fieldName (fields[%d] = %v) of type %T to string.", i, fields[i], fields[i]) } fieldValue := fields[i+1] switch fieldName { case "id": if err := scanString(fieldValue, &(job.id)); err != nil { return err } case "data": if err := scanBytes(fieldValue, &(job.data)); err != nil { return err } case "type": typeName := "" if err := scanString(fieldValue, &typeName); err != nil { return err } Type, found := Types[typeName] if !found { return fmt.Errorf("jobs: In scanJob: Could not find Type with name = %s", typeName) } job.typ = Type case "time": if err := scanInt64(fieldValue, &(job.time)); err != nil { return err } case "freq": if err := scanInt64(fieldValue, &(job.freq)); err != nil { return err } case "priority": if err := scanInt(fieldValue, &(job.priority)); err != nil { return err } case "retries": if err := scanUint(fieldValue, &(job.retries)); err != nil { return err } case "status": status := "" if err := scanString(fieldValue, &status); err != nil { return err } job.status = Status(status) case "started": if err := scanInt64(fieldValue, &(job.started)); err != nil { return err } case "finished": if err := scanInt64(fieldValue, &(job.finished)); err != nil { return err } case "poolId": if err := scanString(fieldValue, &(job.poolId)); err != nil { return err } } } return nil }
[ "func", "scanJob", "(", "reply", "interface", "{", "}", ",", "job", "*", "Job", ")", "error", "{", "fields", ",", "err", ":=", "redis", ".", "Values", "(", "reply", ",", "nil", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "else", "if", "len", "(", "fields", ")", "==", "0", "{", "return", "ErrorJobNotFound", "{", "}", "\n", "}", "else", "if", "len", "(", "fields", ")", "%", "2", "!=", "0", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "len", "(", "fields", ")", ")", "\n", "}", "\n", "for", "i", ":=", "0", ";", "i", "<", "len", "(", "fields", ")", "-", "1", ";", "i", "+=", "2", "{", "fieldName", ",", "err", ":=", "redis", ".", "String", "(", "fields", "[", "i", "]", ",", "nil", ")", "\n", "if", "err", "!=", "nil", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "i", ",", "fields", "[", "i", "]", ",", "fields", "[", "i", "]", ")", "\n", "}", "\n", "fieldValue", ":=", "fields", "[", "i", "+", "1", "]", "\n", "switch", "fieldName", "{", "case", "\"", "\"", ":", "if", "err", ":=", "scanString", "(", "fieldValue", ",", "&", "(", "job", ".", "id", ")", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "case", "\"", "\"", ":", "if", "err", ":=", "scanBytes", "(", "fieldValue", ",", "&", "(", "job", ".", "data", ")", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "case", "\"", "\"", ":", "typeName", ":=", "\"", "\"", "\n", "if", "err", ":=", "scanString", "(", "fieldValue", ",", "&", "typeName", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "Type", ",", "found", ":=", "Types", "[", "typeName", "]", "\n", "if", "!", "found", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "typeName", ")", "\n", "}", "\n", "job", ".", "typ", "=", "Type", "\n", "case", "\"", "\"", ":", "if", "err", ":=", "scanInt64", "(", "fieldValue", ",", "&", "(", "job", ".", "time", ")", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "case", "\"", "\"", ":", "if", "err", ":=", "scanInt64", "(", "fieldValue", ",", "&", "(", "job", ".", "freq", ")", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "case", "\"", "\"", ":", "if", "err", ":=", "scanInt", "(", "fieldValue", ",", "&", "(", "job", ".", "priority", ")", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "case", "\"", "\"", ":", "if", "err", ":=", "scanUint", "(", "fieldValue", ",", "&", "(", "job", ".", "retries", ")", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "case", "\"", "\"", ":", "status", ":=", "\"", "\"", "\n", "if", "err", ":=", "scanString", "(", "fieldValue", ",", "&", "status", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "job", ".", "status", "=", "Status", "(", "status", ")", "\n", "case", "\"", "\"", ":", "if", "err", ":=", "scanInt64", "(", "fieldValue", ",", "&", "(", "job", ".", "started", ")", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "case", "\"", "\"", ":", "if", "err", ":=", "scanInt64", "(", "fieldValue", ",", "&", "(", "job", ".", "finished", ")", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "case", "\"", "\"", ":", "if", "err", ":=", "scanString", "(", "fieldValue", ",", "&", "(", "job", ".", "poolId", ")", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "}", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// scanJob scans the values of reply into job. reply should be the // response of an HMGET or HGETALL query.
[ "scanJob", "scans", "the", "values", "of", "reply", "into", "job", ".", "reply", "should", "be", "the", "response", "of", "an", "HMGET", "or", "HGETALL", "query", "." ]
2580c613deb47dce29730c128a5dee775f552a1d
https://github.com/albrow/jobs/blob/2580c613deb47dce29730c128a5dee775f552a1d/job.go#L308-L379
1,325
albrow/jobs
job.go
scanInt
func scanInt(reply interface{}, v *int) error { if v == nil { return fmt.Errorf("jobs: In scanInt: argument v was nil") } val, err := redis.Int(reply, nil) if err != nil { return fmt.Errorf("jobs: In scanInt: Could not convert %v of type %T to int.", reply, reply) } (*v) = val return nil }
go
func scanInt(reply interface{}, v *int) error { if v == nil { return fmt.Errorf("jobs: In scanInt: argument v was nil") } val, err := redis.Int(reply, nil) if err != nil { return fmt.Errorf("jobs: In scanInt: Could not convert %v of type %T to int.", reply, reply) } (*v) = val return nil }
[ "func", "scanInt", "(", "reply", "interface", "{", "}", ",", "v", "*", "int", ")", "error", "{", "if", "v", "==", "nil", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ")", "\n", "}", "\n", "val", ",", "err", ":=", "redis", ".", "Int", "(", "reply", ",", "nil", ")", "\n", "if", "err", "!=", "nil", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "reply", ",", "reply", ")", "\n", "}", "\n", "(", "*", "v", ")", "=", "val", "\n", "return", "nil", "\n", "}" ]
// scanInt converts a reply from redis into an int and scans the value into v.
[ "scanInt", "converts", "a", "reply", "from", "redis", "into", "an", "int", "and", "scans", "the", "value", "into", "v", "." ]
2580c613deb47dce29730c128a5dee775f552a1d
https://github.com/albrow/jobs/blob/2580c613deb47dce29730c128a5dee775f552a1d/job.go#L382-L392
1,326
albrow/jobs
job.go
scanUint
func scanUint(reply interface{}, v *uint) error { if v == nil { return fmt.Errorf("jobs: In scanUint: argument v was nil") } val, err := redis.Uint64(reply, nil) if err != nil { return fmt.Errorf("jobs: In scanUint: Could not convert %v of type %T to uint.", reply, reply) } (*v) = uint(val) return nil }
go
func scanUint(reply interface{}, v *uint) error { if v == nil { return fmt.Errorf("jobs: In scanUint: argument v was nil") } val, err := redis.Uint64(reply, nil) if err != nil { return fmt.Errorf("jobs: In scanUint: Could not convert %v of type %T to uint.", reply, reply) } (*v) = uint(val) return nil }
[ "func", "scanUint", "(", "reply", "interface", "{", "}", ",", "v", "*", "uint", ")", "error", "{", "if", "v", "==", "nil", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ")", "\n", "}", "\n", "val", ",", "err", ":=", "redis", ".", "Uint64", "(", "reply", ",", "nil", ")", "\n", "if", "err", "!=", "nil", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "reply", ",", "reply", ")", "\n", "}", "\n", "(", "*", "v", ")", "=", "uint", "(", "val", ")", "\n", "return", "nil", "\n", "}" ]
// scanUint converts a reply from redis into a uint and scans the value into v.
[ "scanUint", "converts", "a", "reply", "from", "redis", "into", "a", "uint", "and", "scans", "the", "value", "into", "v", "." ]
2580c613deb47dce29730c128a5dee775f552a1d
https://github.com/albrow/jobs/blob/2580c613deb47dce29730c128a5dee775f552a1d/job.go#L395-L405
1,327
albrow/jobs
job.go
scanInt64
func scanInt64(reply interface{}, v *int64) error { if v == nil { return fmt.Errorf("jobs: In scanInt64: argument v was nil") } val, err := redis.Int64(reply, nil) if err != nil { return fmt.Errorf("jobs: In scanInt64: Could not convert %v of type %T to int64.", reply, reply) } (*v) = val return nil }
go
func scanInt64(reply interface{}, v *int64) error { if v == nil { return fmt.Errorf("jobs: In scanInt64: argument v was nil") } val, err := redis.Int64(reply, nil) if err != nil { return fmt.Errorf("jobs: In scanInt64: Could not convert %v of type %T to int64.", reply, reply) } (*v) = val return nil }
[ "func", "scanInt64", "(", "reply", "interface", "{", "}", ",", "v", "*", "int64", ")", "error", "{", "if", "v", "==", "nil", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ")", "\n", "}", "\n", "val", ",", "err", ":=", "redis", ".", "Int64", "(", "reply", ",", "nil", ")", "\n", "if", "err", "!=", "nil", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "reply", ",", "reply", ")", "\n", "}", "\n", "(", "*", "v", ")", "=", "val", "\n", "return", "nil", "\n", "}" ]
// scanInt64 converts a reply from redis into an int64 and scans the value into v.
[ "scanInt64", "converts", "a", "reply", "from", "redis", "into", "an", "int64", "and", "scans", "the", "value", "into", "v", "." ]
2580c613deb47dce29730c128a5dee775f552a1d
https://github.com/albrow/jobs/blob/2580c613deb47dce29730c128a5dee775f552a1d/job.go#L408-L418
1,328
albrow/jobs
job.go
scanString
func scanString(reply interface{}, v *string) error { if v == nil { return fmt.Errorf("jobs: In String: argument v was nil") } val, err := redis.String(reply, nil) if err != nil { return fmt.Errorf("jobs: In String: Could not convert %v of type %T to string.", reply, reply) } (*v) = val return nil }
go
func scanString(reply interface{}, v *string) error { if v == nil { return fmt.Errorf("jobs: In String: argument v was nil") } val, err := redis.String(reply, nil) if err != nil { return fmt.Errorf("jobs: In String: Could not convert %v of type %T to string.", reply, reply) } (*v) = val return nil }
[ "func", "scanString", "(", "reply", "interface", "{", "}", ",", "v", "*", "string", ")", "error", "{", "if", "v", "==", "nil", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ")", "\n", "}", "\n", "val", ",", "err", ":=", "redis", ".", "String", "(", "reply", ",", "nil", ")", "\n", "if", "err", "!=", "nil", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "reply", ",", "reply", ")", "\n", "}", "\n", "(", "*", "v", ")", "=", "val", "\n", "return", "nil", "\n", "}" ]
// scanString converts a reply from redis into a string and scans the value into v.
[ "scanString", "converts", "a", "reply", "from", "redis", "into", "a", "string", "and", "scans", "the", "value", "into", "v", "." ]
2580c613deb47dce29730c128a5dee775f552a1d
https://github.com/albrow/jobs/blob/2580c613deb47dce29730c128a5dee775f552a1d/job.go#L421-L431
1,329
albrow/jobs
job.go
scanBytes
func scanBytes(reply interface{}, v *[]byte) error { if v == nil { return fmt.Errorf("jobs: In scanBytes: argument v was nil") } val, err := redis.Bytes(reply, nil) if err != nil { return fmt.Errorf("jobs: In scanBytes: Could not convert %v of type %T to []byte.", reply, reply) } (*v) = val return nil }
go
func scanBytes(reply interface{}, v *[]byte) error { if v == nil { return fmt.Errorf("jobs: In scanBytes: argument v was nil") } val, err := redis.Bytes(reply, nil) if err != nil { return fmt.Errorf("jobs: In scanBytes: Could not convert %v of type %T to []byte.", reply, reply) } (*v) = val return nil }
[ "func", "scanBytes", "(", "reply", "interface", "{", "}", ",", "v", "*", "[", "]", "byte", ")", "error", "{", "if", "v", "==", "nil", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ")", "\n", "}", "\n", "val", ",", "err", ":=", "redis", ".", "Bytes", "(", "reply", ",", "nil", ")", "\n", "if", "err", "!=", "nil", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "reply", ",", "reply", ")", "\n", "}", "\n", "(", "*", "v", ")", "=", "val", "\n", "return", "nil", "\n", "}" ]
// scanBytes converts a reply from redis into a slice of bytes and scans the value into v.
[ "scanBytes", "converts", "a", "reply", "from", "redis", "into", "a", "slice", "of", "bytes", "and", "scans", "the", "value", "into", "v", "." ]
2580c613deb47dce29730c128a5dee775f552a1d
https://github.com/albrow/jobs/blob/2580c613deb47dce29730c128a5dee775f552a1d/job.go#L434-L444
1,330
albrow/jobs
job.go
scanJobById
func (t *transaction) scanJobById(id string, job *Job) { job.id = id t.command("HGETALL", redis.Args{job.Key()}, newScanJobHandler(job)) }
go
func (t *transaction) scanJobById(id string, job *Job) { job.id = id t.command("HGETALL", redis.Args{job.Key()}, newScanJobHandler(job)) }
[ "func", "(", "t", "*", "transaction", ")", "scanJobById", "(", "id", "string", ",", "job", "*", "Job", ")", "{", "job", ".", "id", "=", "id", "\n", "t", ".", "command", "(", "\"", "\"", ",", "redis", ".", "Args", "{", "job", ".", "Key", "(", ")", "}", ",", "newScanJobHandler", "(", "job", ")", ")", "\n", "}" ]
// scanJobById adds commands and a reply handler to the transaction which, when run, // will scan the values of the job corresponding to id into job. It does not execute // the transaction.
[ "scanJobById", "adds", "commands", "and", "a", "reply", "handler", "to", "the", "transaction", "which", "when", "run", "will", "scan", "the", "values", "of", "the", "job", "corresponding", "to", "id", "into", "job", ".", "It", "does", "not", "execute", "the", "transaction", "." ]
2580c613deb47dce29730c128a5dee775f552a1d
https://github.com/albrow/jobs/blob/2580c613deb47dce29730c128a5dee775f552a1d/job.go#L449-L452
1,331
albrow/jobs
job_status.go
Count
func (status Status) Count() (int, error) { conn := redisPool.Get() defer conn.Close() return redis.Int(conn.Do("ZCARD", status.Key())) }
go
func (status Status) Count() (int, error) { conn := redisPool.Get() defer conn.Close() return redis.Int(conn.Do("ZCARD", status.Key())) }
[ "func", "(", "status", "Status", ")", "Count", "(", ")", "(", "int", ",", "error", ")", "{", "conn", ":=", "redisPool", ".", "Get", "(", ")", "\n", "defer", "conn", ".", "Close", "(", ")", "\n", "return", "redis", ".", "Int", "(", "conn", ".", "Do", "(", "\"", "\"", ",", "status", ".", "Key", "(", ")", ")", ")", "\n", "}" ]
// Count returns the number of jobs that currently have the given status // or an error if there was a problem connecting to the database.
[ "Count", "returns", "the", "number", "of", "jobs", "that", "currently", "have", "the", "given", "status", "or", "an", "error", "if", "there", "was", "a", "problem", "connecting", "to", "the", "database", "." ]
2580c613deb47dce29730c128a5dee775f552a1d
https://github.com/albrow/jobs/blob/2580c613deb47dce29730c128a5dee775f552a1d/job_status.go#L41-L45
1,332
albrow/jobs
job_status.go
JobIds
func (status Status) JobIds() ([]string, error) { conn := redisPool.Get() defer conn.Close() return redis.Strings(conn.Do("ZREVRANGE", status.Key(), 0, -1)) }
go
func (status Status) JobIds() ([]string, error) { conn := redisPool.Get() defer conn.Close() return redis.Strings(conn.Do("ZREVRANGE", status.Key(), 0, -1)) }
[ "func", "(", "status", "Status", ")", "JobIds", "(", ")", "(", "[", "]", "string", ",", "error", ")", "{", "conn", ":=", "redisPool", ".", "Get", "(", ")", "\n", "defer", "conn", ".", "Close", "(", ")", "\n", "return", "redis", ".", "Strings", "(", "conn", ".", "Do", "(", "\"", "\"", ",", "status", ".", "Key", "(", ")", ",", "0", ",", "-", "1", ")", ")", "\n", "}" ]
// JobIds returns the ids of all jobs that have the given status, ordered by // priority or an error if there was a problem connecting to the database.
[ "JobIds", "returns", "the", "ids", "of", "all", "jobs", "that", "have", "the", "given", "status", "ordered", "by", "priority", "or", "an", "error", "if", "there", "was", "a", "problem", "connecting", "to", "the", "database", "." ]
2580c613deb47dce29730c128a5dee775f552a1d
https://github.com/albrow/jobs/blob/2580c613deb47dce29730c128a5dee775f552a1d/job_status.go#L49-L53
1,333
albrow/jobs
job_status.go
Jobs
func (status Status) Jobs() ([]*Job, error) { t := newTransaction() jobs := []*Job{} t.getJobsByIds(status.Key(), newScanJobsHandler(&jobs)) if err := t.exec(); err != nil { return nil, err } return jobs, nil }
go
func (status Status) Jobs() ([]*Job, error) { t := newTransaction() jobs := []*Job{} t.getJobsByIds(status.Key(), newScanJobsHandler(&jobs)) if err := t.exec(); err != nil { return nil, err } return jobs, nil }
[ "func", "(", "status", "Status", ")", "Jobs", "(", ")", "(", "[", "]", "*", "Job", ",", "error", ")", "{", "t", ":=", "newTransaction", "(", ")", "\n", "jobs", ":=", "[", "]", "*", "Job", "{", "}", "\n", "t", ".", "getJobsByIds", "(", "status", ".", "Key", "(", ")", ",", "newScanJobsHandler", "(", "&", "jobs", ")", ")", "\n", "if", "err", ":=", "t", ".", "exec", "(", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "return", "jobs", ",", "nil", "\n", "}" ]
// Jobs returns all jobs that have the given status, ordered by priority or // an error if there was a problem connecting to the database.
[ "Jobs", "returns", "all", "jobs", "that", "have", "the", "given", "status", "ordered", "by", "priority", "or", "an", "error", "if", "there", "was", "a", "problem", "connecting", "to", "the", "database", "." ]
2580c613deb47dce29730c128a5dee775f552a1d
https://github.com/albrow/jobs/blob/2580c613deb47dce29730c128a5dee775f552a1d/job_status.go#L57-L65
1,334
albrow/jobs
job_type.go
RegisterType
func RegisterType(name string, retries uint, handler HandlerFunc) (*Type, error) { // Make sure name is unique if _, found := Types[name]; found { return Types[name], newErrorNameAlreadyRegistered(name) } // Make sure handler is a function handlerType := reflect.TypeOf(handler) if handlerType.Kind() != reflect.Func { return nil, fmt.Errorf("jobs: in RegisterNewType, handler must be a function. Got %T", handler) } if handlerType.NumIn() > 1 { return nil, fmt.Errorf("jobs: in RegisterNewType, handler must accept 0 or 1 arguments. Got %d.", handlerType.NumIn()) } if handlerType.NumOut() != 1 { return nil, fmt.Errorf("jobs: in RegisterNewType, handler must have exactly one return value. Got %d.", handlerType.NumOut()) } if !typeIsError(handlerType.Out(0)) { return nil, fmt.Errorf("jobs: in RegisterNewType, handler must return an error. Got return value of type %s.", handlerType.Out(0).String()) } Type := &Type{ name: name, handler: handler, retries: retries, } if handlerType.NumIn() == 1 { Type.dataType = handlerType.In(0) } Types[name] = Type return Type, nil }
go
func RegisterType(name string, retries uint, handler HandlerFunc) (*Type, error) { // Make sure name is unique if _, found := Types[name]; found { return Types[name], newErrorNameAlreadyRegistered(name) } // Make sure handler is a function handlerType := reflect.TypeOf(handler) if handlerType.Kind() != reflect.Func { return nil, fmt.Errorf("jobs: in RegisterNewType, handler must be a function. Got %T", handler) } if handlerType.NumIn() > 1 { return nil, fmt.Errorf("jobs: in RegisterNewType, handler must accept 0 or 1 arguments. Got %d.", handlerType.NumIn()) } if handlerType.NumOut() != 1 { return nil, fmt.Errorf("jobs: in RegisterNewType, handler must have exactly one return value. Got %d.", handlerType.NumOut()) } if !typeIsError(handlerType.Out(0)) { return nil, fmt.Errorf("jobs: in RegisterNewType, handler must return an error. Got return value of type %s.", handlerType.Out(0).String()) } Type := &Type{ name: name, handler: handler, retries: retries, } if handlerType.NumIn() == 1 { Type.dataType = handlerType.In(0) } Types[name] = Type return Type, nil }
[ "func", "RegisterType", "(", "name", "string", ",", "retries", "uint", ",", "handler", "HandlerFunc", ")", "(", "*", "Type", ",", "error", ")", "{", "// Make sure name is unique", "if", "_", ",", "found", ":=", "Types", "[", "name", "]", ";", "found", "{", "return", "Types", "[", "name", "]", ",", "newErrorNameAlreadyRegistered", "(", "name", ")", "\n", "}", "\n", "// Make sure handler is a function", "handlerType", ":=", "reflect", ".", "TypeOf", "(", "handler", ")", "\n", "if", "handlerType", ".", "Kind", "(", ")", "!=", "reflect", ".", "Func", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "handler", ")", "\n", "}", "\n", "if", "handlerType", ".", "NumIn", "(", ")", ">", "1", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "handlerType", ".", "NumIn", "(", ")", ")", "\n", "}", "\n", "if", "handlerType", ".", "NumOut", "(", ")", "!=", "1", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "handlerType", ".", "NumOut", "(", ")", ")", "\n", "}", "\n", "if", "!", "typeIsError", "(", "handlerType", ".", "Out", "(", "0", ")", ")", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "handlerType", ".", "Out", "(", "0", ")", ".", "String", "(", ")", ")", "\n", "}", "\n", "Type", ":=", "&", "Type", "{", "name", ":", "name", ",", "handler", ":", "handler", ",", "retries", ":", "retries", ",", "}", "\n", "if", "handlerType", ".", "NumIn", "(", ")", "==", "1", "{", "Type", ".", "dataType", "=", "handlerType", ".", "In", "(", "0", ")", "\n", "}", "\n", "Types", "[", "name", "]", "=", "Type", "\n", "return", "Type", ",", "nil", "\n", "}" ]
// RegisterType registers a new type of job that can be executed by workers. // name should be a unique string identifier for the job. // retries is the number of times this type of job should be retried if it fails. // handler is a function that a worker will call in order to execute the job. // handler should be a function which accepts either 0 or 1 arguments of any type, // corresponding to the data for a job of this type. All jobs of this type must have // data with the same type as the first argument to handler, or nil if the handler // accepts no arguments.
[ "RegisterType", "registers", "a", "new", "type", "of", "job", "that", "can", "be", "executed", "by", "workers", ".", "name", "should", "be", "a", "unique", "string", "identifier", "for", "the", "job", ".", "retries", "is", "the", "number", "of", "times", "this", "type", "of", "job", "should", "be", "retried", "if", "it", "fails", ".", "handler", "is", "a", "function", "that", "a", "worker", "will", "call", "in", "order", "to", "execute", "the", "job", ".", "handler", "should", "be", "a", "function", "which", "accepts", "either", "0", "or", "1", "arguments", "of", "any", "type", "corresponding", "to", "the", "data", "for", "a", "job", "of", "this", "type", ".", "All", "jobs", "of", "this", "type", "must", "have", "data", "with", "the", "same", "type", "as", "the", "first", "argument", "to", "handler", "or", "nil", "if", "the", "handler", "accepts", "no", "arguments", "." ]
2580c613deb47dce29730c128a5dee775f552a1d
https://github.com/albrow/jobs/blob/2580c613deb47dce29730c128a5dee775f552a1d/job_type.go#L54-L83
1,335
albrow/jobs
job_type.go
Schedule
func (jt *Type) Schedule(priority int, time time.Time, data interface{}) (*Job, error) { // Encode the data encodedData, err := jt.encodeData(data) if err != nil { return nil, err } // Create and save the job job := &Job{ data: encodedData, typ: jt, time: time.UTC().UnixNano(), retries: jt.retries, priority: priority, } // Set the job's status to queued and save it in the database job.status = StatusQueued if err := job.save(); err != nil { return nil, err } return job, nil }
go
func (jt *Type) Schedule(priority int, time time.Time, data interface{}) (*Job, error) { // Encode the data encodedData, err := jt.encodeData(data) if err != nil { return nil, err } // Create and save the job job := &Job{ data: encodedData, typ: jt, time: time.UTC().UnixNano(), retries: jt.retries, priority: priority, } // Set the job's status to queued and save it in the database job.status = StatusQueued if err := job.save(); err != nil { return nil, err } return job, nil }
[ "func", "(", "jt", "*", "Type", ")", "Schedule", "(", "priority", "int", ",", "time", "time", ".", "Time", ",", "data", "interface", "{", "}", ")", "(", "*", "Job", ",", "error", ")", "{", "// Encode the data", "encodedData", ",", "err", ":=", "jt", ".", "encodeData", "(", "data", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "// Create and save the job", "job", ":=", "&", "Job", "{", "data", ":", "encodedData", ",", "typ", ":", "jt", ",", "time", ":", "time", ".", "UTC", "(", ")", ".", "UnixNano", "(", ")", ",", "retries", ":", "jt", ".", "retries", ",", "priority", ":", "priority", ",", "}", "\n", "// Set the job's status to queued and save it in the database", "job", ".", "status", "=", "StatusQueued", "\n", "if", "err", ":=", "job", ".", "save", "(", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "return", "job", ",", "nil", "\n", "}" ]
// Schedule schedules a on-off job of the given type with the given parameters. // Jobs with a higher priority will be executed first. The job will not be // executed until after time. data is the data associated with this particular // job and should have the same type as the first argument to the handler for this // Type.
[ "Schedule", "schedules", "a", "on", "-", "off", "job", "of", "the", "given", "type", "with", "the", "given", "parameters", ".", "Jobs", "with", "a", "higher", "priority", "will", "be", "executed", "first", ".", "The", "job", "will", "not", "be", "executed", "until", "after", "time", ".", "data", "is", "the", "data", "associated", "with", "this", "particular", "job", "and", "should", "have", "the", "same", "type", "as", "the", "first", "argument", "to", "the", "handler", "for", "this", "Type", "." ]
2580c613deb47dce29730c128a5dee775f552a1d
https://github.com/albrow/jobs/blob/2580c613deb47dce29730c128a5dee775f552a1d/job_type.go#L101-L121
1,336
albrow/jobs
job_type.go
encodeData
func (jt *Type) encodeData(data interface{}) ([]byte, error) { // Check the type of data dataType := reflect.TypeOf(data) if dataType != jt.dataType { return nil, fmt.Errorf("jobs: provided data was not of the correct type.\nExpected %s for Type %s, but got %s", jt.dataType, jt, dataType) } // Encode the data encodedData, err := encode(data) if err != nil { return nil, fmt.Errorf("jobs: error encoding data: %s", err.Error()) } return encodedData, nil }
go
func (jt *Type) encodeData(data interface{}) ([]byte, error) { // Check the type of data dataType := reflect.TypeOf(data) if dataType != jt.dataType { return nil, fmt.Errorf("jobs: provided data was not of the correct type.\nExpected %s for Type %s, but got %s", jt.dataType, jt, dataType) } // Encode the data encodedData, err := encode(data) if err != nil { return nil, fmt.Errorf("jobs: error encoding data: %s", err.Error()) } return encodedData, nil }
[ "func", "(", "jt", "*", "Type", ")", "encodeData", "(", "data", "interface", "{", "}", ")", "(", "[", "]", "byte", ",", "error", ")", "{", "// Check the type of data", "dataType", ":=", "reflect", ".", "TypeOf", "(", "data", ")", "\n", "if", "dataType", "!=", "jt", ".", "dataType", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\\n", "\"", ",", "jt", ".", "dataType", ",", "jt", ",", "dataType", ")", "\n", "}", "\n", "// Encode the data", "encodedData", ",", "err", ":=", "encode", "(", "data", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "err", ".", "Error", "(", ")", ")", "\n", "}", "\n", "return", "encodedData", ",", "nil", "\n", "}" ]
// encodeData checks that the type of data is what we expect based on the handler for the Type. // If it is, it encodes the data into a slice of bytes.
[ "encodeData", "checks", "that", "the", "type", "of", "data", "is", "what", "we", "expect", "based", "on", "the", "handler", "for", "the", "Type", ".", "If", "it", "is", "it", "encodes", "the", "data", "into", "a", "slice", "of", "bytes", "." ]
2580c613deb47dce29730c128a5dee775f552a1d
https://github.com/albrow/jobs/blob/2580c613deb47dce29730c128a5dee775f552a1d/job_type.go#L154-L166
1,337
albrow/jobs
pool.go
NewPool
func NewPool(config *PoolConfig) (*Pool, error) { finalConfig := getPoolConfig(config) hardwareId, err := getHardwareId() if err != nil { return nil, err } return &Pool{ config: finalConfig, id: hardwareId, wg: &sync.WaitGroup{}, exit: make(chan bool), workers: make([]*worker, finalConfig.NumWorkers), jobs: make(chan *Job, finalConfig.BatchSize), }, nil }
go
func NewPool(config *PoolConfig) (*Pool, error) { finalConfig := getPoolConfig(config) hardwareId, err := getHardwareId() if err != nil { return nil, err } return &Pool{ config: finalConfig, id: hardwareId, wg: &sync.WaitGroup{}, exit: make(chan bool), workers: make([]*worker, finalConfig.NumWorkers), jobs: make(chan *Job, finalConfig.BatchSize), }, nil }
[ "func", "NewPool", "(", "config", "*", "PoolConfig", ")", "(", "*", "Pool", ",", "error", ")", "{", "finalConfig", ":=", "getPoolConfig", "(", "config", ")", "\n", "hardwareId", ",", "err", ":=", "getHardwareId", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "return", "&", "Pool", "{", "config", ":", "finalConfig", ",", "id", ":", "hardwareId", ",", "wg", ":", "&", "sync", ".", "WaitGroup", "{", "}", ",", "exit", ":", "make", "(", "chan", "bool", ")", ",", "workers", ":", "make", "(", "[", "]", "*", "worker", ",", "finalConfig", ".", "NumWorkers", ")", ",", "jobs", ":", "make", "(", "chan", "*", "Job", ",", "finalConfig", ".", "BatchSize", ")", ",", "}", ",", "nil", "\n", "}" ]
// NewPool creates and returns a new pool with the given configuration. You can // pass in nil to use the default values. Otherwise, any zero values in config will // be interpreted as the default value.
[ "NewPool", "creates", "and", "returns", "a", "new", "pool", "with", "the", "given", "configuration", ".", "You", "can", "pass", "in", "nil", "to", "use", "the", "default", "values", ".", "Otherwise", "any", "zero", "values", "in", "config", "will", "be", "interpreted", "as", "the", "default", "value", "." ]
2580c613deb47dce29730c128a5dee775f552a1d
https://github.com/albrow/jobs/blob/2580c613deb47dce29730c128a5dee775f552a1d/pool.go#L92-L106
1,338
albrow/jobs
pool.go
getPoolConfig
func getPoolConfig(passedConfig *PoolConfig) *PoolConfig { if passedConfig == nil { return DefaultPoolConfig } finalConfig := &PoolConfig{} (*finalConfig) = (*passedConfig) if passedConfig.NumWorkers == 0 { finalConfig.NumWorkers = DefaultPoolConfig.NumWorkers } if passedConfig.BatchSize == 0 { finalConfig.BatchSize = DefaultPoolConfig.BatchSize } if passedConfig.MinWait == 0 { finalConfig.MinWait = DefaultPoolConfig.MinWait } if passedConfig.StaleTimeout == 0 { finalConfig.StaleTimeout = DefaultPoolConfig.StaleTimeout } return finalConfig }
go
func getPoolConfig(passedConfig *PoolConfig) *PoolConfig { if passedConfig == nil { return DefaultPoolConfig } finalConfig := &PoolConfig{} (*finalConfig) = (*passedConfig) if passedConfig.NumWorkers == 0 { finalConfig.NumWorkers = DefaultPoolConfig.NumWorkers } if passedConfig.BatchSize == 0 { finalConfig.BatchSize = DefaultPoolConfig.BatchSize } if passedConfig.MinWait == 0 { finalConfig.MinWait = DefaultPoolConfig.MinWait } if passedConfig.StaleTimeout == 0 { finalConfig.StaleTimeout = DefaultPoolConfig.StaleTimeout } return finalConfig }
[ "func", "getPoolConfig", "(", "passedConfig", "*", "PoolConfig", ")", "*", "PoolConfig", "{", "if", "passedConfig", "==", "nil", "{", "return", "DefaultPoolConfig", "\n", "}", "\n", "finalConfig", ":=", "&", "PoolConfig", "{", "}", "\n", "(", "*", "finalConfig", ")", "=", "(", "*", "passedConfig", ")", "\n", "if", "passedConfig", ".", "NumWorkers", "==", "0", "{", "finalConfig", ".", "NumWorkers", "=", "DefaultPoolConfig", ".", "NumWorkers", "\n", "}", "\n", "if", "passedConfig", ".", "BatchSize", "==", "0", "{", "finalConfig", ".", "BatchSize", "=", "DefaultPoolConfig", ".", "BatchSize", "\n", "}", "\n", "if", "passedConfig", ".", "MinWait", "==", "0", "{", "finalConfig", ".", "MinWait", "=", "DefaultPoolConfig", ".", "MinWait", "\n", "}", "\n", "if", "passedConfig", ".", "StaleTimeout", "==", "0", "{", "finalConfig", ".", "StaleTimeout", "=", "DefaultPoolConfig", ".", "StaleTimeout", "\n", "}", "\n", "return", "finalConfig", "\n", "}" ]
// getPoolConfig replaces any zero values in passedConfig with the default values. // If passedConfig is nil, every value will be set to the default.
[ "getPoolConfig", "replaces", "any", "zero", "values", "in", "passedConfig", "with", "the", "default", "values", ".", "If", "passedConfig", "is", "nil", "every", "value", "will", "be", "set", "to", "the", "default", "." ]
2580c613deb47dce29730c128a5dee775f552a1d
https://github.com/albrow/jobs/blob/2580c613deb47dce29730c128a5dee775f552a1d/pool.go#L110-L129
1,339
albrow/jobs
pool.go
addToPoolSet
func (p *Pool) addToPoolSet() error { conn := redisPool.Get() defer conn.Close() p.RLock() thisId := p.id p.RUnlock() if _, err := conn.Do("SADD", Keys.ActivePools, thisId); err != nil { return err } return nil }
go
func (p *Pool) addToPoolSet() error { conn := redisPool.Get() defer conn.Close() p.RLock() thisId := p.id p.RUnlock() if _, err := conn.Do("SADD", Keys.ActivePools, thisId); err != nil { return err } return nil }
[ "func", "(", "p", "*", "Pool", ")", "addToPoolSet", "(", ")", "error", "{", "conn", ":=", "redisPool", ".", "Get", "(", ")", "\n", "defer", "conn", ".", "Close", "(", ")", "\n", "p", ".", "RLock", "(", ")", "\n", "thisId", ":=", "p", ".", "id", "\n", "p", ".", "RUnlock", "(", ")", "\n", "if", "_", ",", "err", ":=", "conn", ".", "Do", "(", "\"", "\"", ",", "Keys", ".", "ActivePools", ",", "thisId", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// addToPoolSet adds the id of the worker pool to a set of active pools // in the database.
[ "addToPoolSet", "adds", "the", "id", "of", "the", "worker", "pool", "to", "a", "set", "of", "active", "pools", "in", "the", "database", "." ]
2580c613deb47dce29730c128a5dee775f552a1d
https://github.com/albrow/jobs/blob/2580c613deb47dce29730c128a5dee775f552a1d/pool.go#L133-L143
1,340
albrow/jobs
pool.go
pingAndPurgeIfNeeded
func (p *Pool) pingAndPurgeIfNeeded(other *Pool) error { ping := redisPool.Get() pong := redis.PubSubConn{redisPool.Get()} // Listen for pongs by subscribing to the other pool's pong key pong.Subscribe(other.pongKey()) // Ping the other pool by publishing to its ping key ping.Do("PUBLISH", other.pingKey(), 1) // Use a select statement to either receive the pong or timeout pongChan := make(chan interface{}) errChan := make(chan error) go func() { defer func() { pong.Close() ping.Close() }() select { case <-p.exit: return default: } for { reply := pong.Receive() switch reply.(type) { case redis.Message: // The pong was received pongChan <- reply return case error: // There was some unexpected error err := reply.(error) errChan <- err return } } }() timeout := time.After(p.config.StaleTimeout) select { case <-pongChan: // The other pool responded with a pong return nil case err := <-errChan: // Received an error from the pubsub conn return err case <-timeout: // The pool is considered stale and should be purged t := newTransaction() other.RLock() otherId := other.id other.RUnlock() t.purgeStalePool(otherId) if err := t.exec(); err != nil { return err } } return nil }
go
func (p *Pool) pingAndPurgeIfNeeded(other *Pool) error { ping := redisPool.Get() pong := redis.PubSubConn{redisPool.Get()} // Listen for pongs by subscribing to the other pool's pong key pong.Subscribe(other.pongKey()) // Ping the other pool by publishing to its ping key ping.Do("PUBLISH", other.pingKey(), 1) // Use a select statement to either receive the pong or timeout pongChan := make(chan interface{}) errChan := make(chan error) go func() { defer func() { pong.Close() ping.Close() }() select { case <-p.exit: return default: } for { reply := pong.Receive() switch reply.(type) { case redis.Message: // The pong was received pongChan <- reply return case error: // There was some unexpected error err := reply.(error) errChan <- err return } } }() timeout := time.After(p.config.StaleTimeout) select { case <-pongChan: // The other pool responded with a pong return nil case err := <-errChan: // Received an error from the pubsub conn return err case <-timeout: // The pool is considered stale and should be purged t := newTransaction() other.RLock() otherId := other.id other.RUnlock() t.purgeStalePool(otherId) if err := t.exec(); err != nil { return err } } return nil }
[ "func", "(", "p", "*", "Pool", ")", "pingAndPurgeIfNeeded", "(", "other", "*", "Pool", ")", "error", "{", "ping", ":=", "redisPool", ".", "Get", "(", ")", "\n", "pong", ":=", "redis", ".", "PubSubConn", "{", "redisPool", ".", "Get", "(", ")", "}", "\n", "// Listen for pongs by subscribing to the other pool's pong key", "pong", ".", "Subscribe", "(", "other", ".", "pongKey", "(", ")", ")", "\n", "// Ping the other pool by publishing to its ping key", "ping", ".", "Do", "(", "\"", "\"", ",", "other", ".", "pingKey", "(", ")", ",", "1", ")", "\n", "// Use a select statement to either receive the pong or timeout", "pongChan", ":=", "make", "(", "chan", "interface", "{", "}", ")", "\n", "errChan", ":=", "make", "(", "chan", "error", ")", "\n", "go", "func", "(", ")", "{", "defer", "func", "(", ")", "{", "pong", ".", "Close", "(", ")", "\n", "ping", ".", "Close", "(", ")", "\n", "}", "(", ")", "\n", "select", "{", "case", "<-", "p", ".", "exit", ":", "return", "\n", "default", ":", "}", "\n", "for", "{", "reply", ":=", "pong", ".", "Receive", "(", ")", "\n", "switch", "reply", ".", "(", "type", ")", "{", "case", "redis", ".", "Message", ":", "// The pong was received", "pongChan", "<-", "reply", "\n", "return", "\n", "case", "error", ":", "// There was some unexpected error", "err", ":=", "reply", ".", "(", "error", ")", "\n", "errChan", "<-", "err", "\n", "return", "\n", "}", "\n", "}", "\n", "}", "(", ")", "\n", "timeout", ":=", "time", ".", "After", "(", "p", ".", "config", ".", "StaleTimeout", ")", "\n", "select", "{", "case", "<-", "pongChan", ":", "// The other pool responded with a pong", "return", "nil", "\n", "case", "err", ":=", "<-", "errChan", ":", "// Received an error from the pubsub conn", "return", "err", "\n", "case", "<-", "timeout", ":", "// The pool is considered stale and should be purged", "t", ":=", "newTransaction", "(", ")", "\n", "other", ".", "RLock", "(", ")", "\n", "otherId", ":=", "other", ".", "id", "\n", "other", ".", "RUnlock", "(", ")", "\n", "t", ".", "purgeStalePool", "(", "otherId", ")", "\n", "if", "err", ":=", "t", ".", "exec", "(", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// pingAndPurgeIfNeeded pings other by publishing to others ping key. If it // does not receive a pong reply within some amount of time, it will // assume the pool is stale and purge it.
[ "pingAndPurgeIfNeeded", "pings", "other", "by", "publishing", "to", "others", "ping", "key", ".", "If", "it", "does", "not", "receive", "a", "pong", "reply", "within", "some", "amount", "of", "time", "it", "will", "assume", "the", "pool", "is", "stale", "and", "purge", "it", "." ]
2580c613deb47dce29730c128a5dee775f552a1d
https://github.com/albrow/jobs/blob/2580c613deb47dce29730c128a5dee775f552a1d/pool.go#L239-L294
1,341
albrow/jobs
pool.go
respondToPings
func (p *Pool) respondToPings() error { pong := redisPool.Get() ping := redis.PubSubConn{redisPool.Get()} defer func() { pong.Close() ping.Close() }() // Subscribe to the ping key for this pool to receive pings. if err := ping.Subscribe(p.pingKey()); err != nil { return err } for { // Whenever we recieve a ping, reply immediately with a pong by // publishing to the pong key for this pool. switch reply := ping.Receive().(type) { case redis.Message: if _, err := pong.Do("PUBLISH", p.pongKey(), 0); err != nil { return err } case error: err := reply.(error) return err } time.Sleep(1 * time.Millisecond) } }
go
func (p *Pool) respondToPings() error { pong := redisPool.Get() ping := redis.PubSubConn{redisPool.Get()} defer func() { pong.Close() ping.Close() }() // Subscribe to the ping key for this pool to receive pings. if err := ping.Subscribe(p.pingKey()); err != nil { return err } for { // Whenever we recieve a ping, reply immediately with a pong by // publishing to the pong key for this pool. switch reply := ping.Receive().(type) { case redis.Message: if _, err := pong.Do("PUBLISH", p.pongKey(), 0); err != nil { return err } case error: err := reply.(error) return err } time.Sleep(1 * time.Millisecond) } }
[ "func", "(", "p", "*", "Pool", ")", "respondToPings", "(", ")", "error", "{", "pong", ":=", "redisPool", ".", "Get", "(", ")", "\n", "ping", ":=", "redis", ".", "PubSubConn", "{", "redisPool", ".", "Get", "(", ")", "}", "\n", "defer", "func", "(", ")", "{", "pong", ".", "Close", "(", ")", "\n", "ping", ".", "Close", "(", ")", "\n", "}", "(", ")", "\n", "// Subscribe to the ping key for this pool to receive pings.", "if", "err", ":=", "ping", ".", "Subscribe", "(", "p", ".", "pingKey", "(", ")", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "for", "{", "// Whenever we recieve a ping, reply immediately with a pong by", "// publishing to the pong key for this pool.", "switch", "reply", ":=", "ping", ".", "Receive", "(", ")", ".", "(", "type", ")", "{", "case", "redis", ".", "Message", ":", "if", "_", ",", "err", ":=", "pong", ".", "Do", "(", "\"", "\"", ",", "p", ".", "pongKey", "(", ")", ",", "0", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "case", "error", ":", "err", ":=", "reply", ".", "(", "error", ")", "\n", "return", "err", "\n", "}", "\n", "time", ".", "Sleep", "(", "1", "*", "time", ".", "Millisecond", ")", "\n", "}", "\n", "}" ]
// respondToPings continuously listens for pings from other worker pools and // immediately responds with a pong. It will only return if there is an error.
[ "respondToPings", "continuously", "listens", "for", "pings", "from", "other", "worker", "pools", "and", "immediately", "responds", "with", "a", "pong", ".", "It", "will", "only", "return", "if", "there", "is", "an", "error", "." ]
2580c613deb47dce29730c128a5dee775f552a1d
https://github.com/albrow/jobs/blob/2580c613deb47dce29730c128a5dee775f552a1d/pool.go#L298-L323
1,342
albrow/jobs
pool.go
Start
func (p *Pool) Start() error { // Purge stale jobs belonging to this pool if there was a recent // hard failure if err := p.removeStaleSelf(); err != nil { return err } // Check on the status of other worker pools by pinging them and // start the process to repond to pings from other pools if err := p.addToPoolSet(); err != nil { return err } go func() { select { case <-p.exit: return default: } if err := p.respondToPings(); err != nil { // TODO: send the err accross a channel instead of panicking panic(err) } }() if err := p.purgeStalePools(); err != nil { return err } // Initialize workers for i := range p.workers { p.wg.Add(1) worker := &worker{ wg: p.wg, jobs: p.jobs, afterFunc: p.afterFunc, } p.workers[i] = worker worker.start() } go func() { if err := p.queryLoop(); err != nil { // TODO: send the err accross a channel instead of panicking panic(err) } }() return nil }
go
func (p *Pool) Start() error { // Purge stale jobs belonging to this pool if there was a recent // hard failure if err := p.removeStaleSelf(); err != nil { return err } // Check on the status of other worker pools by pinging them and // start the process to repond to pings from other pools if err := p.addToPoolSet(); err != nil { return err } go func() { select { case <-p.exit: return default: } if err := p.respondToPings(); err != nil { // TODO: send the err accross a channel instead of panicking panic(err) } }() if err := p.purgeStalePools(); err != nil { return err } // Initialize workers for i := range p.workers { p.wg.Add(1) worker := &worker{ wg: p.wg, jobs: p.jobs, afterFunc: p.afterFunc, } p.workers[i] = worker worker.start() } go func() { if err := p.queryLoop(); err != nil { // TODO: send the err accross a channel instead of panicking panic(err) } }() return nil }
[ "func", "(", "p", "*", "Pool", ")", "Start", "(", ")", "error", "{", "// Purge stale jobs belonging to this pool if there was a recent", "// hard failure", "if", "err", ":=", "p", ".", "removeStaleSelf", "(", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "// Check on the status of other worker pools by pinging them and", "// start the process to repond to pings from other pools", "if", "err", ":=", "p", ".", "addToPoolSet", "(", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "go", "func", "(", ")", "{", "select", "{", "case", "<-", "p", ".", "exit", ":", "return", "\n", "default", ":", "}", "\n", "if", "err", ":=", "p", ".", "respondToPings", "(", ")", ";", "err", "!=", "nil", "{", "// TODO: send the err accross a channel instead of panicking", "panic", "(", "err", ")", "\n", "}", "\n", "}", "(", ")", "\n", "if", "err", ":=", "p", ".", "purgeStalePools", "(", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "// Initialize workers", "for", "i", ":=", "range", "p", ".", "workers", "{", "p", ".", "wg", ".", "Add", "(", "1", ")", "\n", "worker", ":=", "&", "worker", "{", "wg", ":", "p", ".", "wg", ",", "jobs", ":", "p", ".", "jobs", ",", "afterFunc", ":", "p", ".", "afterFunc", ",", "}", "\n", "p", ".", "workers", "[", "i", "]", "=", "worker", "\n", "worker", ".", "start", "(", ")", "\n", "}", "\n", "go", "func", "(", ")", "{", "if", "err", ":=", "p", ".", "queryLoop", "(", ")", ";", "err", "!=", "nil", "{", "// TODO: send the err accross a channel instead of panicking", "panic", "(", "err", ")", "\n", "}", "\n", "}", "(", ")", "\n", "return", "nil", "\n", "}" ]
// Start starts the worker pool. This means the pool will initialize workers, // continuously query the database for queued jobs, and delegate those jobs // to the workers.
[ "Start", "starts", "the", "worker", "pool", ".", "This", "means", "the", "pool", "will", "initialize", "workers", "continuously", "query", "the", "database", "for", "queued", "jobs", "and", "delegate", "those", "jobs", "to", "the", "workers", "." ]
2580c613deb47dce29730c128a5dee775f552a1d
https://github.com/albrow/jobs/blob/2580c613deb47dce29730c128a5dee775f552a1d/pool.go#L348-L393
1,343
albrow/jobs
pool.go
queryLoop
func (p *Pool) queryLoop() error { if err := p.sendNextJobs(p.config.BatchSize); err != nil { return err } for { minWait := time.After(p.config.MinWait) select { case <-p.exit: // Close the channel to tell workers to stop executing new jobs close(p.jobs) return nil case <-minWait: if err := p.sendNextJobs(p.config.BatchSize); err != nil { return err } } } return nil }
go
func (p *Pool) queryLoop() error { if err := p.sendNextJobs(p.config.BatchSize); err != nil { return err } for { minWait := time.After(p.config.MinWait) select { case <-p.exit: // Close the channel to tell workers to stop executing new jobs close(p.jobs) return nil case <-minWait: if err := p.sendNextJobs(p.config.BatchSize); err != nil { return err } } } return nil }
[ "func", "(", "p", "*", "Pool", ")", "queryLoop", "(", ")", "error", "{", "if", "err", ":=", "p", ".", "sendNextJobs", "(", "p", ".", "config", ".", "BatchSize", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "for", "{", "minWait", ":=", "time", ".", "After", "(", "p", ".", "config", ".", "MinWait", ")", "\n", "select", "{", "case", "<-", "p", ".", "exit", ":", "// Close the channel to tell workers to stop executing new jobs", "close", "(", "p", ".", "jobs", ")", "\n", "return", "nil", "\n", "case", "<-", "minWait", ":", "if", "err", ":=", "p", ".", "sendNextJobs", "(", "p", ".", "config", ".", "BatchSize", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "}", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// queryLoop continuously queries the database for new jobs and, if // it finds any, sends them through the jobs channel for execution // by some worker.
[ "queryLoop", "continuously", "queries", "the", "database", "for", "new", "jobs", "and", "if", "it", "finds", "any", "sends", "them", "through", "the", "jobs", "channel", "for", "execution", "by", "some", "worker", "." ]
2580c613deb47dce29730c128a5dee775f552a1d
https://github.com/albrow/jobs/blob/2580c613deb47dce29730c128a5dee775f552a1d/pool.go#L423-L441
1,344
albrow/jobs
pool.go
sendNextJobs
func (p *Pool) sendNextJobs(n int) error { jobs, err := p.getNextJobs(p.config.BatchSize) if err != nil { return err } // Send the jobs across the channel, where they will be picked up // by exactly one worker for _, job := range jobs { p.jobs <- job } return nil }
go
func (p *Pool) sendNextJobs(n int) error { jobs, err := p.getNextJobs(p.config.BatchSize) if err != nil { return err } // Send the jobs across the channel, where they will be picked up // by exactly one worker for _, job := range jobs { p.jobs <- job } return nil }
[ "func", "(", "p", "*", "Pool", ")", "sendNextJobs", "(", "n", "int", ")", "error", "{", "jobs", ",", "err", ":=", "p", ".", "getNextJobs", "(", "p", ".", "config", ".", "BatchSize", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "// Send the jobs across the channel, where they will be picked up", "// by exactly one worker", "for", "_", ",", "job", ":=", "range", "jobs", "{", "p", ".", "jobs", "<-", "job", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// sendNextJobs queries the database to find the next n ready jobs, then // sends those jobs to the jobs channel, effectively delegating them to // a worker.
[ "sendNextJobs", "queries", "the", "database", "to", "find", "the", "next", "n", "ready", "jobs", "then", "sends", "those", "jobs", "to", "the", "jobs", "channel", "effectively", "delegating", "them", "to", "a", "worker", "." ]
2580c613deb47dce29730c128a5dee775f552a1d
https://github.com/albrow/jobs/blob/2580c613deb47dce29730c128a5dee775f552a1d/pool.go#L446-L457
1,345
albrow/jobs
transaction.go
command
func (t *transaction) command(name string, args redis.Args, handler replyHandler) { t.actions = append(t.actions, &action{ kind: actionCommand, name: name, args: args, handler: handler, }) }
go
func (t *transaction) command(name string, args redis.Args, handler replyHandler) { t.actions = append(t.actions, &action{ kind: actionCommand, name: name, args: args, handler: handler, }) }
[ "func", "(", "t", "*", "transaction", ")", "command", "(", "name", "string", ",", "args", "redis", ".", "Args", ",", "handler", "replyHandler", ")", "{", "t", ".", "actions", "=", "append", "(", "t", ".", "actions", ",", "&", "action", "{", "kind", ":", "actionCommand", ",", "name", ":", "name", ",", "args", ":", "args", ",", "handler", ":", "handler", ",", "}", ")", "\n", "}" ]
// command adds a command action to the transaction with the given args. // handler will be called with the reply from this specific command when // the transaction is executed.
[ "command", "adds", "a", "command", "action", "to", "the", "transaction", "with", "the", "given", "args", ".", "handler", "will", "be", "called", "with", "the", "reply", "from", "this", "specific", "command", "when", "the", "transaction", "is", "executed", "." ]
2580c613deb47dce29730c128a5dee775f552a1d
https://github.com/albrow/jobs/blob/2580c613deb47dce29730c128a5dee775f552a1d/transaction.go#L54-L61
1,346
albrow/jobs
transaction.go
script
func (t *transaction) script(script *redis.Script, args redis.Args, handler replyHandler) { t.actions = append(t.actions, &action{ kind: actionScript, script: script, args: args, handler: handler, }) }
go
func (t *transaction) script(script *redis.Script, args redis.Args, handler replyHandler) { t.actions = append(t.actions, &action{ kind: actionScript, script: script, args: args, handler: handler, }) }
[ "func", "(", "t", "*", "transaction", ")", "script", "(", "script", "*", "redis", ".", "Script", ",", "args", "redis", ".", "Args", ",", "handler", "replyHandler", ")", "{", "t", ".", "actions", "=", "append", "(", "t", ".", "actions", ",", "&", "action", "{", "kind", ":", "actionScript", ",", "script", ":", "script", ",", "args", ":", "args", ",", "handler", ":", "handler", ",", "}", ")", "\n", "}" ]
// command adds a script action to the transaction with the given args. // handler will be called with the reply from this specific script when // the transaction is executed.
[ "command", "adds", "a", "script", "action", "to", "the", "transaction", "with", "the", "given", "args", ".", "handler", "will", "be", "called", "with", "the", "reply", "from", "this", "specific", "script", "when", "the", "transaction", "is", "executed", "." ]
2580c613deb47dce29730c128a5dee775f552a1d
https://github.com/albrow/jobs/blob/2580c613deb47dce29730c128a5dee775f552a1d/transaction.go#L66-L73
1,347
albrow/jobs
transaction.go
exec
func (t *transaction) exec() error { // Return the connection to the pool when we are done defer t.conn.Close() if len(t.actions) == 1 { // If there is only one command, no need to use MULTI/EXEC a := t.actions[0] reply, err := t.doAction(a) if err != nil { return err } if a.handler != nil { if err := a.handler(reply); err != nil { return err } } } else { // Send all the commands and scripts at once using MULTI/EXEC t.conn.Send("MULTI") for _, a := range t.actions { if err := t.sendAction(a); err != nil { return err } } // Invoke redis driver to execute the transaction replies, err := redis.Values(t.conn.Do("EXEC")) if err != nil { return err } // Iterate through the replies, calling the corresponding handler functions for i, reply := range replies { a := t.actions[i] if a.handler != nil { if err := a.handler(reply); err != nil { return err } } } } return nil }
go
func (t *transaction) exec() error { // Return the connection to the pool when we are done defer t.conn.Close() if len(t.actions) == 1 { // If there is only one command, no need to use MULTI/EXEC a := t.actions[0] reply, err := t.doAction(a) if err != nil { return err } if a.handler != nil { if err := a.handler(reply); err != nil { return err } } } else { // Send all the commands and scripts at once using MULTI/EXEC t.conn.Send("MULTI") for _, a := range t.actions { if err := t.sendAction(a); err != nil { return err } } // Invoke redis driver to execute the transaction replies, err := redis.Values(t.conn.Do("EXEC")) if err != nil { return err } // Iterate through the replies, calling the corresponding handler functions for i, reply := range replies { a := t.actions[i] if a.handler != nil { if err := a.handler(reply); err != nil { return err } } } } return nil }
[ "func", "(", "t", "*", "transaction", ")", "exec", "(", ")", "error", "{", "// Return the connection to the pool when we are done", "defer", "t", ".", "conn", ".", "Close", "(", ")", "\n\n", "if", "len", "(", "t", ".", "actions", ")", "==", "1", "{", "// If there is only one command, no need to use MULTI/EXEC", "a", ":=", "t", ".", "actions", "[", "0", "]", "\n", "reply", ",", "err", ":=", "t", ".", "doAction", "(", "a", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "if", "a", ".", "handler", "!=", "nil", "{", "if", "err", ":=", "a", ".", "handler", "(", "reply", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "}", "\n", "}", "else", "{", "// Send all the commands and scripts at once using MULTI/EXEC", "t", ".", "conn", ".", "Send", "(", "\"", "\"", ")", "\n", "for", "_", ",", "a", ":=", "range", "t", ".", "actions", "{", "if", "err", ":=", "t", ".", "sendAction", "(", "a", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "}", "\n\n", "// Invoke redis driver to execute the transaction", "replies", ",", "err", ":=", "redis", ".", "Values", "(", "t", ".", "conn", ".", "Do", "(", "\"", "\"", ")", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "// Iterate through the replies, calling the corresponding handler functions", "for", "i", ",", "reply", ":=", "range", "replies", "{", "a", ":=", "t", ".", "actions", "[", "i", "]", "\n", "if", "a", ".", "handler", "!=", "nil", "{", "if", "err", ":=", "a", ".", "handler", "(", "reply", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "}", "\n", "}", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// exec executes the transaction, sequentially sending each action and // calling all the action handlers with the corresponding replies.
[ "exec", "executes", "the", "transaction", "sequentially", "sending", "each", "action", "and", "calling", "all", "the", "action", "handlers", "with", "the", "corresponding", "replies", "." ]
2580c613deb47dce29730c128a5dee775f552a1d
https://github.com/albrow/jobs/blob/2580c613deb47dce29730c128a5dee775f552a1d/transaction.go#L100-L142
1,348
albrow/jobs
transaction.go
newScanJobsHandler
func newScanJobsHandler(jobs *[]*Job) replyHandler { return func(reply interface{}) error { values, err := redis.Values(reply, nil) if err != nil { return nil } for _, fields := range values { job := &Job{} if err := scanJob(fields, job); err != nil { return err } (*jobs) = append((*jobs), job) } return nil } }
go
func newScanJobsHandler(jobs *[]*Job) replyHandler { return func(reply interface{}) error { values, err := redis.Values(reply, nil) if err != nil { return nil } for _, fields := range values { job := &Job{} if err := scanJob(fields, job); err != nil { return err } (*jobs) = append((*jobs), job) } return nil } }
[ "func", "newScanJobsHandler", "(", "jobs", "*", "[", "]", "*", "Job", ")", "replyHandler", "{", "return", "func", "(", "reply", "interface", "{", "}", ")", "error", "{", "values", ",", "err", ":=", "redis", ".", "Values", "(", "reply", ",", "nil", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", "\n", "}", "\n", "for", "_", ",", "fields", ":=", "range", "values", "{", "job", ":=", "&", "Job", "{", "}", "\n", "if", "err", ":=", "scanJob", "(", "fields", ",", "job", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "(", "*", "jobs", ")", "=", "append", "(", "(", "*", "jobs", ")", ",", "job", ")", "\n", "}", "\n", "return", "nil", "\n", "}", "\n", "}" ]
// newScanJobsHandler returns a replyHandler which, when run, will scan the values // of reply into jobs.
[ "newScanJobsHandler", "returns", "a", "replyHandler", "which", "when", "run", "will", "scan", "the", "values", "of", "reply", "into", "jobs", "." ]
2580c613deb47dce29730c128a5dee775f552a1d
https://github.com/albrow/jobs/blob/2580c613deb47dce29730c128a5dee775f552a1d/transaction.go#L154-L169
1,349
albrow/jobs
transaction.go
debugSet
func (t *transaction) debugSet(setName string) { t.command("ZRANGE", redis.Args{setName, 0, -1, "WITHSCORES"}, func(reply interface{}) error { vals, err := redis.Strings(reply, nil) if err != nil { return err } fmt.Printf("%s: %v\n", setName, vals) return nil }) }
go
func (t *transaction) debugSet(setName string) { t.command("ZRANGE", redis.Args{setName, 0, -1, "WITHSCORES"}, func(reply interface{}) error { vals, err := redis.Strings(reply, nil) if err != nil { return err } fmt.Printf("%s: %v\n", setName, vals) return nil }) }
[ "func", "(", "t", "*", "transaction", ")", "debugSet", "(", "setName", "string", ")", "{", "t", ".", "command", "(", "\"", "\"", ",", "redis", ".", "Args", "{", "setName", ",", "0", ",", "-", "1", ",", "\"", "\"", "}", ",", "func", "(", "reply", "interface", "{", "}", ")", "error", "{", "vals", ",", "err", ":=", "redis", ".", "Strings", "(", "reply", ",", "nil", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "fmt", ".", "Printf", "(", "\"", "\\n", "\"", ",", "setName", ",", "vals", ")", "\n", "return", "nil", "\n", "}", ")", "\n", "}" ]
// debugSet simply prints out the value of the given set
[ "debugSet", "simply", "prints", "out", "the", "value", "of", "the", "given", "set" ]
2580c613deb47dce29730c128a5dee775f552a1d
https://github.com/albrow/jobs/blob/2580c613deb47dce29730c128a5dee775f552a1d/transaction.go#L172-L181
1,350
albrow/jobs
transaction.go
newScanStringsHandler
func newScanStringsHandler(strings *[]string) replyHandler { return func(reply interface{}) error { if strings == nil { return fmt.Errorf("jobs: Error in newScanStringsHandler: expected strings arg to be a pointer to a slice of strings but it was nil") } var err error (*strings), err = redis.Strings(reply, nil) if err != nil { return fmt.Errorf("jobs: Error in newScanStringsHandler: %s", err.Error()) } return nil } }
go
func newScanStringsHandler(strings *[]string) replyHandler { return func(reply interface{}) error { if strings == nil { return fmt.Errorf("jobs: Error in newScanStringsHandler: expected strings arg to be a pointer to a slice of strings but it was nil") } var err error (*strings), err = redis.Strings(reply, nil) if err != nil { return fmt.Errorf("jobs: Error in newScanStringsHandler: %s", err.Error()) } return nil } }
[ "func", "newScanStringsHandler", "(", "strings", "*", "[", "]", "string", ")", "replyHandler", "{", "return", "func", "(", "reply", "interface", "{", "}", ")", "error", "{", "if", "strings", "==", "nil", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ")", "\n", "}", "\n", "var", "err", "error", "\n", "(", "*", "strings", ")", ",", "err", "=", "redis", ".", "Strings", "(", "reply", ",", "nil", ")", "\n", "if", "err", "!=", "nil", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "err", ".", "Error", "(", ")", ")", "\n", "}", "\n", "return", "nil", "\n", "}", "\n", "}" ]
// newScanStringsHandler returns a replyHandler which, when run, will scan the values // of reply into strings.
[ "newScanStringsHandler", "returns", "a", "replyHandler", "which", "when", "run", "will", "scan", "the", "values", "of", "reply", "into", "strings", "." ]
2580c613deb47dce29730c128a5dee775f552a1d
https://github.com/albrow/jobs/blob/2580c613deb47dce29730c128a5dee775f552a1d/transaction.go#L185-L197
1,351
albrow/jobs
transaction.go
newScanStringHandler
func newScanStringHandler(s *string) replyHandler { return func(reply interface{}) error { if s == nil { return fmt.Errorf("jobs: Error in newScanStringHandler: expected arg s to be a pointer to a string but it was nil") } var err error (*s), err = redis.String(reply, nil) if err != nil { return fmt.Errorf("jobs: Error in newScanStringHandler: %s", err.Error()) } return nil } }
go
func newScanStringHandler(s *string) replyHandler { return func(reply interface{}) error { if s == nil { return fmt.Errorf("jobs: Error in newScanStringHandler: expected arg s to be a pointer to a string but it was nil") } var err error (*s), err = redis.String(reply, nil) if err != nil { return fmt.Errorf("jobs: Error in newScanStringHandler: %s", err.Error()) } return nil } }
[ "func", "newScanStringHandler", "(", "s", "*", "string", ")", "replyHandler", "{", "return", "func", "(", "reply", "interface", "{", "}", ")", "error", "{", "if", "s", "==", "nil", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ")", "\n", "}", "\n", "var", "err", "error", "\n", "(", "*", "s", ")", ",", "err", "=", "redis", ".", "String", "(", "reply", ",", "nil", ")", "\n", "if", "err", "!=", "nil", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "err", ".", "Error", "(", ")", ")", "\n", "}", "\n", "return", "nil", "\n", "}", "\n", "}" ]
// newScanStringHandler returns a replyHandler which, when run, will convert reply to a // string and scan it into s.
[ "newScanStringHandler", "returns", "a", "replyHandler", "which", "when", "run", "will", "convert", "reply", "to", "a", "string", "and", "scan", "it", "into", "s", "." ]
2580c613deb47dce29730c128a5dee775f552a1d
https://github.com/albrow/jobs/blob/2580c613deb47dce29730c128a5dee775f552a1d/transaction.go#L201-L213
1,352
albrow/jobs
transaction.go
newScanIntHandler
func newScanIntHandler(i *int) replyHandler { return func(reply interface{}) error { if i == nil { return fmt.Errorf("jobs: Error in newScanIntHandler: expected arg s to be a pointer to a string but it was nil") } var err error (*i), err = redis.Int(reply, nil) if err != nil { return fmt.Errorf("jobs: Error in newScanIntHandler: %s", err.Error()) } return nil } }
go
func newScanIntHandler(i *int) replyHandler { return func(reply interface{}) error { if i == nil { return fmt.Errorf("jobs: Error in newScanIntHandler: expected arg s to be a pointer to a string but it was nil") } var err error (*i), err = redis.Int(reply, nil) if err != nil { return fmt.Errorf("jobs: Error in newScanIntHandler: %s", err.Error()) } return nil } }
[ "func", "newScanIntHandler", "(", "i", "*", "int", ")", "replyHandler", "{", "return", "func", "(", "reply", "interface", "{", "}", ")", "error", "{", "if", "i", "==", "nil", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ")", "\n", "}", "\n", "var", "err", "error", "\n", "(", "*", "i", ")", ",", "err", "=", "redis", ".", "Int", "(", "reply", ",", "nil", ")", "\n", "if", "err", "!=", "nil", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "err", ".", "Error", "(", ")", ")", "\n", "}", "\n", "return", "nil", "\n", "}", "\n", "}" ]
// newScanIntHandler returns a replyHandler which, when run, will convert reply to a // int and scan it into i.
[ "newScanIntHandler", "returns", "a", "replyHandler", "which", "when", "run", "will", "convert", "reply", "to", "a", "int", "and", "scan", "it", "into", "i", "." ]
2580c613deb47dce29730c128a5dee775f552a1d
https://github.com/albrow/jobs/blob/2580c613deb47dce29730c128a5dee775f552a1d/transaction.go#L217-L229
1,353
albrow/jobs
transaction.go
newScanBoolHandler
func newScanBoolHandler(b *bool) replyHandler { return func(reply interface{}) error { if b == nil { return fmt.Errorf("jobs: Error in newScanBoolHandler: expected arg v to be a pointer to a bool but it was nil") } var err error (*b), err = redis.Bool(reply, nil) if err != nil { return fmt.Errorf("jobs: Error in newScanBoolHandler: %s", err.Error()) } return nil } }
go
func newScanBoolHandler(b *bool) replyHandler { return func(reply interface{}) error { if b == nil { return fmt.Errorf("jobs: Error in newScanBoolHandler: expected arg v to be a pointer to a bool but it was nil") } var err error (*b), err = redis.Bool(reply, nil) if err != nil { return fmt.Errorf("jobs: Error in newScanBoolHandler: %s", err.Error()) } return nil } }
[ "func", "newScanBoolHandler", "(", "b", "*", "bool", ")", "replyHandler", "{", "return", "func", "(", "reply", "interface", "{", "}", ")", "error", "{", "if", "b", "==", "nil", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ")", "\n", "}", "\n", "var", "err", "error", "\n", "(", "*", "b", ")", ",", "err", "=", "redis", ".", "Bool", "(", "reply", ",", "nil", ")", "\n", "if", "err", "!=", "nil", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "err", ".", "Error", "(", ")", ")", "\n", "}", "\n", "return", "nil", "\n", "}", "\n", "}" ]
// newScanBoolHandler returns a replyHandler which, when run, will convert reply to a // bool and scan it into b.
[ "newScanBoolHandler", "returns", "a", "replyHandler", "which", "when", "run", "will", "convert", "reply", "to", "a", "bool", "and", "scan", "it", "into", "b", "." ]
2580c613deb47dce29730c128a5dee775f552a1d
https://github.com/albrow/jobs/blob/2580c613deb47dce29730c128a5dee775f552a1d/transaction.go#L233-L245
1,354
albrow/jobs
transaction.go
retryOrFailJob
func (t *transaction) retryOrFailJob(job *Job, handler replyHandler) { t.script(retryOrFailJobScript, redis.Args{job.id}, handler) }
go
func (t *transaction) retryOrFailJob(job *Job, handler replyHandler) { t.script(retryOrFailJobScript, redis.Args{job.id}, handler) }
[ "func", "(", "t", "*", "transaction", ")", "retryOrFailJob", "(", "job", "*", "Job", ",", "handler", "replyHandler", ")", "{", "t", ".", "script", "(", "retryOrFailJobScript", ",", "redis", ".", "Args", "{", "job", ".", "id", "}", ",", "handler", ")", "\n", "}" ]
// retryOrFailJob is a small function wrapper around retryOrFailJobScript. // It offers some type safety and helps make sure the arguments you pass through to the are correct. // The script will either mark the job as failed or queue it for retry depending on the number of // retries left.
[ "retryOrFailJob", "is", "a", "small", "function", "wrapper", "around", "retryOrFailJobScript", ".", "It", "offers", "some", "type", "safety", "and", "helps", "make", "sure", "the", "arguments", "you", "pass", "through", "to", "the", "are", "correct", ".", "The", "script", "will", "either", "mark", "the", "job", "as", "failed", "or", "queue", "it", "for", "retry", "depending", "on", "the", "number", "of", "retries", "left", "." ]
2580c613deb47dce29730c128a5dee775f552a1d
https://github.com/albrow/jobs/blob/2580c613deb47dce29730c128a5dee775f552a1d/transaction.go#L261-L263
1,355
albrow/jobs
transaction.go
setStatus
func (t *transaction) setStatus(job *Job, status Status) { t.script(setJobStatusScript, redis.Args{job.id, string(status)}, nil) }
go
func (t *transaction) setStatus(job *Job, status Status) { t.script(setJobStatusScript, redis.Args{job.id, string(status)}, nil) }
[ "func", "(", "t", "*", "transaction", ")", "setStatus", "(", "job", "*", "Job", ",", "status", "Status", ")", "{", "t", ".", "script", "(", "setJobStatusScript", ",", "redis", ".", "Args", "{", "job", ".", "id", ",", "string", "(", "status", ")", "}", ",", "nil", ")", "\n", "}" ]
// setStatus is a small function wrapper around setStatusScript. // It offers some type safety and helps make sure the arguments you pass through to the are correct. // The script will atomically update the status of the job, removing it from its old status set and // adding it to the new one.
[ "setStatus", "is", "a", "small", "function", "wrapper", "around", "setStatusScript", ".", "It", "offers", "some", "type", "safety", "and", "helps", "make", "sure", "the", "arguments", "you", "pass", "through", "to", "the", "are", "correct", ".", "The", "script", "will", "atomically", "update", "the", "status", "of", "the", "job", "removing", "it", "from", "its", "old", "status", "set", "and", "adding", "it", "to", "the", "new", "one", "." ]
2580c613deb47dce29730c128a5dee775f552a1d
https://github.com/albrow/jobs/blob/2580c613deb47dce29730c128a5dee775f552a1d/transaction.go#L269-L271
1,356
albrow/jobs
transaction.go
destroyJob
func (t *transaction) destroyJob(job *Job) { t.script(destroyJobScript, redis.Args{job.id}, nil) }
go
func (t *transaction) destroyJob(job *Job) { t.script(destroyJobScript, redis.Args{job.id}, nil) }
[ "func", "(", "t", "*", "transaction", ")", "destroyJob", "(", "job", "*", "Job", ")", "{", "t", ".", "script", "(", "destroyJobScript", ",", "redis", ".", "Args", "{", "job", ".", "id", "}", ",", "nil", ")", "\n", "}" ]
// destroyJob is a small function wrapper around destroyJobScript. // It offers some type safety and helps make sure the arguments you pass through to the are correct. // The script will remove all records associated with job from the database.
[ "destroyJob", "is", "a", "small", "function", "wrapper", "around", "destroyJobScript", ".", "It", "offers", "some", "type", "safety", "and", "helps", "make", "sure", "the", "arguments", "you", "pass", "through", "to", "the", "are", "correct", ".", "The", "script", "will", "remove", "all", "records", "associated", "with", "job", "from", "the", "database", "." ]
2580c613deb47dce29730c128a5dee775f552a1d
https://github.com/albrow/jobs/blob/2580c613deb47dce29730c128a5dee775f552a1d/transaction.go#L276-L278
1,357
albrow/jobs
transaction.go
purgeStalePool
func (t *transaction) purgeStalePool(poolId string) { t.script(purgeStalePoolScript, redis.Args{poolId}, nil) }
go
func (t *transaction) purgeStalePool(poolId string) { t.script(purgeStalePoolScript, redis.Args{poolId}, nil) }
[ "func", "(", "t", "*", "transaction", ")", "purgeStalePool", "(", "poolId", "string", ")", "{", "t", ".", "script", "(", "purgeStalePoolScript", ",", "redis", ".", "Args", "{", "poolId", "}", ",", "nil", ")", "\n", "}" ]
// purgeStalePool is a small function wrapper around purgeStalePoolScript. // It offers some type safety and helps make sure the arguments you pass through to the are correct. // The script will remove the stale pool from the active pools set, and then requeue any jobs associated // with the stale pool that are stuck in the executing set.
[ "purgeStalePool", "is", "a", "small", "function", "wrapper", "around", "purgeStalePoolScript", ".", "It", "offers", "some", "type", "safety", "and", "helps", "make", "sure", "the", "arguments", "you", "pass", "through", "to", "the", "are", "correct", ".", "The", "script", "will", "remove", "the", "stale", "pool", "from", "the", "active", "pools", "set", "and", "then", "requeue", "any", "jobs", "associated", "with", "the", "stale", "pool", "that", "are", "stuck", "in", "the", "executing", "set", "." ]
2580c613deb47dce29730c128a5dee775f552a1d
https://github.com/albrow/jobs/blob/2580c613deb47dce29730c128a5dee775f552a1d/transaction.go#L284-L286
1,358
albrow/jobs
transaction.go
getJobsByIds
func (t *transaction) getJobsByIds(setKey string, handler replyHandler) { t.script(getJobsByIdsScript, redis.Args{setKey}, handler) }
go
func (t *transaction) getJobsByIds(setKey string, handler replyHandler) { t.script(getJobsByIdsScript, redis.Args{setKey}, handler) }
[ "func", "(", "t", "*", "transaction", ")", "getJobsByIds", "(", "setKey", "string", ",", "handler", "replyHandler", ")", "{", "t", ".", "script", "(", "getJobsByIdsScript", ",", "redis", ".", "Args", "{", "setKey", "}", ",", "handler", ")", "\n", "}" ]
// getJobsByIds is a small function wrapper around getJobsByIdsScript. // It offers some type safety and helps make sure the arguments you pass through to the are correct. // The script will return all the fields for jobs which are identified by ids in the given sorted set. // You can use the handler to scan the jobs into a slice of jobs.
[ "getJobsByIds", "is", "a", "small", "function", "wrapper", "around", "getJobsByIdsScript", ".", "It", "offers", "some", "type", "safety", "and", "helps", "make", "sure", "the", "arguments", "you", "pass", "through", "to", "the", "are", "correct", ".", "The", "script", "will", "return", "all", "the", "fields", "for", "jobs", "which", "are", "identified", "by", "ids", "in", "the", "given", "sorted", "set", ".", "You", "can", "use", "the", "handler", "to", "scan", "the", "jobs", "into", "a", "slice", "of", "jobs", "." ]
2580c613deb47dce29730c128a5dee775f552a1d
https://github.com/albrow/jobs/blob/2580c613deb47dce29730c128a5dee775f552a1d/transaction.go#L292-L294
1,359
albrow/jobs
transaction.go
setJobField
func (t *transaction) setJobField(job *Job, fieldName string, fieldValue interface{}) { t.script(setJobFieldScript, redis.Args{job.id, fieldName, fieldValue}, nil) }
go
func (t *transaction) setJobField(job *Job, fieldName string, fieldValue interface{}) { t.script(setJobFieldScript, redis.Args{job.id, fieldName, fieldValue}, nil) }
[ "func", "(", "t", "*", "transaction", ")", "setJobField", "(", "job", "*", "Job", ",", "fieldName", "string", ",", "fieldValue", "interface", "{", "}", ")", "{", "t", ".", "script", "(", "setJobFieldScript", ",", "redis", ".", "Args", "{", "job", ".", "id", ",", "fieldName", ",", "fieldValue", "}", ",", "nil", ")", "\n", "}" ]
// setJobField is a small function wrapper around setJobFieldScript. // It offers some type safety and helps make sure the arguments you pass through are correct. // The script will set the given field to the given value iff the job exists and has not been // destroyed.
[ "setJobField", "is", "a", "small", "function", "wrapper", "around", "setJobFieldScript", ".", "It", "offers", "some", "type", "safety", "and", "helps", "make", "sure", "the", "arguments", "you", "pass", "through", "are", "correct", ".", "The", "script", "will", "set", "the", "given", "field", "to", "the", "given", "value", "iff", "the", "job", "exists", "and", "has", "not", "been", "destroyed", "." ]
2580c613deb47dce29730c128a5dee775f552a1d
https://github.com/albrow/jobs/blob/2580c613deb47dce29730c128a5dee775f552a1d/transaction.go#L300-L302
1,360
albrow/jobs
transaction.go
addJobToSet
func (t *transaction) addJobToSet(job *Job, setName string, score float64) { t.script(addJobToSetScript, redis.Args{job.id, setName, score}, nil) }
go
func (t *transaction) addJobToSet(job *Job, setName string, score float64) { t.script(addJobToSetScript, redis.Args{job.id, setName, score}, nil) }
[ "func", "(", "t", "*", "transaction", ")", "addJobToSet", "(", "job", "*", "Job", ",", "setName", "string", ",", "score", "float64", ")", "{", "t", ".", "script", "(", "addJobToSetScript", ",", "redis", ".", "Args", "{", "job", ".", "id", ",", "setName", ",", "score", "}", ",", "nil", ")", "\n", "}" ]
// addJobToSet is a small function wrapper around addJobToSetScript. // It offers some type safety and helps make sure the arguments you pass through are correct. // The script will add the job to the given set with the given score iff the job exists // and has not been destroyed.
[ "addJobToSet", "is", "a", "small", "function", "wrapper", "around", "addJobToSetScript", ".", "It", "offers", "some", "type", "safety", "and", "helps", "make", "sure", "the", "arguments", "you", "pass", "through", "are", "correct", ".", "The", "script", "will", "add", "the", "job", "to", "the", "given", "set", "with", "the", "given", "score", "iff", "the", "job", "exists", "and", "has", "not", "been", "destroyed", "." ]
2580c613deb47dce29730c128a5dee775f552a1d
https://github.com/albrow/jobs/blob/2580c613deb47dce29730c128a5dee775f552a1d/transaction.go#L308-L310
1,361
albrow/jobs
scripts/generate.go
convertUnderscoresToCamelCase
func convertUnderscoresToCamelCase(s string) string { if len(s) == 0 { return "" } result := "" shouldUpper := false for _, char := range s { if char == '_' { shouldUpper = true continue } if shouldUpper { result += strings.ToUpper(string(char)) } else { result += string(char) } shouldUpper = false } return result }
go
func convertUnderscoresToCamelCase(s string) string { if len(s) == 0 { return "" } result := "" shouldUpper := false for _, char := range s { if char == '_' { shouldUpper = true continue } if shouldUpper { result += strings.ToUpper(string(char)) } else { result += string(char) } shouldUpper = false } return result }
[ "func", "convertUnderscoresToCamelCase", "(", "s", "string", ")", "string", "{", "if", "len", "(", "s", ")", "==", "0", "{", "return", "\"", "\"", "\n", "}", "\n", "result", ":=", "\"", "\"", "\n", "shouldUpper", ":=", "false", "\n", "for", "_", ",", "char", ":=", "range", "s", "{", "if", "char", "==", "'_'", "{", "shouldUpper", "=", "true", "\n", "continue", "\n", "}", "\n", "if", "shouldUpper", "{", "result", "+=", "strings", ".", "ToUpper", "(", "string", "(", "char", ")", ")", "\n", "}", "else", "{", "result", "+=", "string", "(", "char", ")", "\n", "}", "\n", "shouldUpper", "=", "false", "\n", "}", "\n", "return", "result", "\n", "}" ]
// convertUnderscoresToCamelCase converts a string of the form // foo_bar_baz to fooBarBaz.
[ "convertUnderscoresToCamelCase", "converts", "a", "string", "of", "the", "form", "foo_bar_baz", "to", "fooBarBaz", "." ]
2580c613deb47dce29730c128a5dee775f552a1d
https://github.com/albrow/jobs/blob/2580c613deb47dce29730c128a5dee775f552a1d/scripts/generate.go#L117-L136
1,362
mdlayher/ethernet
cmd/etherecho/main.go
sendMessages
func sendMessages(c net.PacketConn, source net.HardwareAddr, msg string) { // Message is broadcast to all machines in same network segment. f := &ethernet.Frame{ Destination: ethernet.Broadcast, Source: source, EtherType: etherType, Payload: []byte(msg), } b, err := f.MarshalBinary() if err != nil { log.Fatalf("failed to marshal ethernet frame: %v", err) } // Required by Linux, even though the Ethernet frame has a destination. // Unused by BSD. addr := &raw.Addr{ HardwareAddr: ethernet.Broadcast, } // Send message forever. t := time.NewTicker(1 * time.Second) for range t.C { if _, err := c.WriteTo(b, addr); err != nil { log.Fatalf("failed to send message: %v", err) } } }
go
func sendMessages(c net.PacketConn, source net.HardwareAddr, msg string) { // Message is broadcast to all machines in same network segment. f := &ethernet.Frame{ Destination: ethernet.Broadcast, Source: source, EtherType: etherType, Payload: []byte(msg), } b, err := f.MarshalBinary() if err != nil { log.Fatalf("failed to marshal ethernet frame: %v", err) } // Required by Linux, even though the Ethernet frame has a destination. // Unused by BSD. addr := &raw.Addr{ HardwareAddr: ethernet.Broadcast, } // Send message forever. t := time.NewTicker(1 * time.Second) for range t.C { if _, err := c.WriteTo(b, addr); err != nil { log.Fatalf("failed to send message: %v", err) } } }
[ "func", "sendMessages", "(", "c", "net", ".", "PacketConn", ",", "source", "net", ".", "HardwareAddr", ",", "msg", "string", ")", "{", "// Message is broadcast to all machines in same network segment.", "f", ":=", "&", "ethernet", ".", "Frame", "{", "Destination", ":", "ethernet", ".", "Broadcast", ",", "Source", ":", "source", ",", "EtherType", ":", "etherType", ",", "Payload", ":", "[", "]", "byte", "(", "msg", ")", ",", "}", "\n\n", "b", ",", "err", ":=", "f", ".", "MarshalBinary", "(", ")", "\n", "if", "err", "!=", "nil", "{", "log", ".", "Fatalf", "(", "\"", "\"", ",", "err", ")", "\n", "}", "\n\n", "// Required by Linux, even though the Ethernet frame has a destination.", "// Unused by BSD.", "addr", ":=", "&", "raw", ".", "Addr", "{", "HardwareAddr", ":", "ethernet", ".", "Broadcast", ",", "}", "\n\n", "// Send message forever.", "t", ":=", "time", ".", "NewTicker", "(", "1", "*", "time", ".", "Second", ")", "\n", "for", "range", "t", ".", "C", "{", "if", "_", ",", "err", ":=", "c", ".", "WriteTo", "(", "b", ",", "addr", ")", ";", "err", "!=", "nil", "{", "log", ".", "Fatalf", "(", "\"", "\"", ",", "err", ")", "\n", "}", "\n", "}", "\n", "}" ]
// sendMessages continuously sends a message over a connection at regular intervals, // sourced from specified hardware address.
[ "sendMessages", "continuously", "sends", "a", "message", "over", "a", "connection", "at", "regular", "intervals", "sourced", "from", "specified", "hardware", "address", "." ]
5b5fc417d966b71d3781b0d5860413e9fae947c1
https://github.com/mdlayher/ethernet/blob/5b5fc417d966b71d3781b0d5860413e9fae947c1/cmd/etherecho/main.go#L62-L89
1,363
mdlayher/ethernet
cmd/etherecho/main.go
receiveMessages
func receiveMessages(c net.PacketConn, mtu int) { var f ethernet.Frame b := make([]byte, mtu) // Keep receiving messages forever. for { n, addr, err := c.ReadFrom(b) if err != nil { log.Fatalf("failed to receive message: %v", err) } // Unpack Ethernet II frame into Go representation. if err := (&f).UnmarshalBinary(b[:n]); err != nil { log.Fatalf("failed to unmarshal ethernet frame: %v", err) } // Display source of message and message itself. log.Printf("[%s] %s", addr.String(), string(f.Payload)) } }
go
func receiveMessages(c net.PacketConn, mtu int) { var f ethernet.Frame b := make([]byte, mtu) // Keep receiving messages forever. for { n, addr, err := c.ReadFrom(b) if err != nil { log.Fatalf("failed to receive message: %v", err) } // Unpack Ethernet II frame into Go representation. if err := (&f).UnmarshalBinary(b[:n]); err != nil { log.Fatalf("failed to unmarshal ethernet frame: %v", err) } // Display source of message and message itself. log.Printf("[%s] %s", addr.String(), string(f.Payload)) } }
[ "func", "receiveMessages", "(", "c", "net", ".", "PacketConn", ",", "mtu", "int", ")", "{", "var", "f", "ethernet", ".", "Frame", "\n", "b", ":=", "make", "(", "[", "]", "byte", ",", "mtu", ")", "\n\n", "// Keep receiving messages forever.", "for", "{", "n", ",", "addr", ",", "err", ":=", "c", ".", "ReadFrom", "(", "b", ")", "\n", "if", "err", "!=", "nil", "{", "log", ".", "Fatalf", "(", "\"", "\"", ",", "err", ")", "\n", "}", "\n\n", "// Unpack Ethernet II frame into Go representation.", "if", "err", ":=", "(", "&", "f", ")", ".", "UnmarshalBinary", "(", "b", "[", ":", "n", "]", ")", ";", "err", "!=", "nil", "{", "log", ".", "Fatalf", "(", "\"", "\"", ",", "err", ")", "\n", "}", "\n\n", "// Display source of message and message itself.", "log", ".", "Printf", "(", "\"", "\"", ",", "addr", ".", "String", "(", ")", ",", "string", "(", "f", ".", "Payload", ")", ")", "\n", "}", "\n", "}" ]
// receiveMessages continuously receives messages over a connection. The messages // may be up to the interface's MTU in size.
[ "receiveMessages", "continuously", "receives", "messages", "over", "a", "connection", ".", "The", "messages", "may", "be", "up", "to", "the", "interface", "s", "MTU", "in", "size", "." ]
5b5fc417d966b71d3781b0d5860413e9fae947c1
https://github.com/mdlayher/ethernet/blob/5b5fc417d966b71d3781b0d5860413e9fae947c1/cmd/etherecho/main.go#L93-L112
1,364
mdlayher/ethernet
vlan.go
MarshalBinary
func (v *VLAN) MarshalBinary() ([]byte, error) { b := make([]byte, 2) _, err := v.read(b) return b, err }
go
func (v *VLAN) MarshalBinary() ([]byte, error) { b := make([]byte, 2) _, err := v.read(b) return b, err }
[ "func", "(", "v", "*", "VLAN", ")", "MarshalBinary", "(", ")", "(", "[", "]", "byte", ",", "error", ")", "{", "b", ":=", "make", "(", "[", "]", "byte", ",", "2", ")", "\n", "_", ",", "err", ":=", "v", ".", "read", "(", "b", ")", "\n", "return", "b", ",", "err", "\n", "}" ]
// MarshalBinary allocates a byte slice and marshals a VLAN into binary form.
[ "MarshalBinary", "allocates", "a", "byte", "slice", "and", "marshals", "a", "VLAN", "into", "binary", "form", "." ]
5b5fc417d966b71d3781b0d5860413e9fae947c1
https://github.com/mdlayher/ethernet/blob/5b5fc417d966b71d3781b0d5860413e9fae947c1/vlan.go#L72-L76
1,365
mdlayher/ethernet
vlan.go
read
func (v *VLAN) read(b []byte) (int, error) { // Check for VLAN priority in valid range if v.Priority > PriorityNetworkControl { return 0, ErrInvalidVLAN } // Check for VLAN ID in valid range if v.ID >= VLANMax { return 0, ErrInvalidVLAN } // 3 bits: priority ub := uint16(v.Priority) << 13 // 1 bit: drop eligible var drop uint16 if v.DropEligible { drop = 1 } ub |= drop << 12 // 12 bits: VLAN ID ub |= v.ID binary.BigEndian.PutUint16(b, ub) return 2, nil }
go
func (v *VLAN) read(b []byte) (int, error) { // Check for VLAN priority in valid range if v.Priority > PriorityNetworkControl { return 0, ErrInvalidVLAN } // Check for VLAN ID in valid range if v.ID >= VLANMax { return 0, ErrInvalidVLAN } // 3 bits: priority ub := uint16(v.Priority) << 13 // 1 bit: drop eligible var drop uint16 if v.DropEligible { drop = 1 } ub |= drop << 12 // 12 bits: VLAN ID ub |= v.ID binary.BigEndian.PutUint16(b, ub) return 2, nil }
[ "func", "(", "v", "*", "VLAN", ")", "read", "(", "b", "[", "]", "byte", ")", "(", "int", ",", "error", ")", "{", "// Check for VLAN priority in valid range", "if", "v", ".", "Priority", ">", "PriorityNetworkControl", "{", "return", "0", ",", "ErrInvalidVLAN", "\n", "}", "\n\n", "// Check for VLAN ID in valid range", "if", "v", ".", "ID", ">=", "VLANMax", "{", "return", "0", ",", "ErrInvalidVLAN", "\n", "}", "\n\n", "// 3 bits: priority", "ub", ":=", "uint16", "(", "v", ".", "Priority", ")", "<<", "13", "\n\n", "// 1 bit: drop eligible", "var", "drop", "uint16", "\n", "if", "v", ".", "DropEligible", "{", "drop", "=", "1", "\n", "}", "\n", "ub", "|=", "drop", "<<", "12", "\n\n", "// 12 bits: VLAN ID", "ub", "|=", "v", ".", "ID", "\n\n", "binary", ".", "BigEndian", ".", "PutUint16", "(", "b", ",", "ub", ")", "\n", "return", "2", ",", "nil", "\n", "}" ]
// read reads data from a VLAN into b. read is used to marshal a VLAN into // binary form, but does not allocate on its own.
[ "read", "reads", "data", "from", "a", "VLAN", "into", "b", ".", "read", "is", "used", "to", "marshal", "a", "VLAN", "into", "binary", "form", "but", "does", "not", "allocate", "on", "its", "own", "." ]
5b5fc417d966b71d3781b0d5860413e9fae947c1
https://github.com/mdlayher/ethernet/blob/5b5fc417d966b71d3781b0d5860413e9fae947c1/vlan.go#L80-L106
1,366
mdlayher/ethernet
vlan.go
UnmarshalBinary
func (v *VLAN) UnmarshalBinary(b []byte) error { // VLAN tag is always 2 bytes if len(b) != 2 { return io.ErrUnexpectedEOF } // 3 bits: priority // 1 bit : drop eligible // 12 bits: VLAN ID ub := binary.BigEndian.Uint16(b[0:2]) v.Priority = Priority(uint8(ub >> 13)) v.DropEligible = ub&0x1000 != 0 v.ID = ub & 0x0fff // Check for VLAN ID in valid range if v.ID >= VLANMax { return ErrInvalidVLAN } return nil }
go
func (v *VLAN) UnmarshalBinary(b []byte) error { // VLAN tag is always 2 bytes if len(b) != 2 { return io.ErrUnexpectedEOF } // 3 bits: priority // 1 bit : drop eligible // 12 bits: VLAN ID ub := binary.BigEndian.Uint16(b[0:2]) v.Priority = Priority(uint8(ub >> 13)) v.DropEligible = ub&0x1000 != 0 v.ID = ub & 0x0fff // Check for VLAN ID in valid range if v.ID >= VLANMax { return ErrInvalidVLAN } return nil }
[ "func", "(", "v", "*", "VLAN", ")", "UnmarshalBinary", "(", "b", "[", "]", "byte", ")", "error", "{", "// VLAN tag is always 2 bytes", "if", "len", "(", "b", ")", "!=", "2", "{", "return", "io", ".", "ErrUnexpectedEOF", "\n", "}", "\n\n", "// 3 bits: priority", "// 1 bit : drop eligible", "// 12 bits: VLAN ID", "ub", ":=", "binary", ".", "BigEndian", ".", "Uint16", "(", "b", "[", "0", ":", "2", "]", ")", "\n", "v", ".", "Priority", "=", "Priority", "(", "uint8", "(", "ub", ">>", "13", ")", ")", "\n", "v", ".", "DropEligible", "=", "ub", "&", "0x1000", "!=", "0", "\n", "v", ".", "ID", "=", "ub", "&", "0x0fff", "\n\n", "// Check for VLAN ID in valid range", "if", "v", ".", "ID", ">=", "VLANMax", "{", "return", "ErrInvalidVLAN", "\n", "}", "\n\n", "return", "nil", "\n", "}" ]
// UnmarshalBinary unmarshals a byte slice into a VLAN.
[ "UnmarshalBinary", "unmarshals", "a", "byte", "slice", "into", "a", "VLAN", "." ]
5b5fc417d966b71d3781b0d5860413e9fae947c1
https://github.com/mdlayher/ethernet/blob/5b5fc417d966b71d3781b0d5860413e9fae947c1/vlan.go#L109-L129
1,367
mdlayher/ethernet
ethernet.go
MarshalBinary
func (f *Frame) MarshalBinary() ([]byte, error) { b := make([]byte, f.length()) _, err := f.read(b) return b, err }
go
func (f *Frame) MarshalBinary() ([]byte, error) { b := make([]byte, f.length()) _, err := f.read(b) return b, err }
[ "func", "(", "f", "*", "Frame", ")", "MarshalBinary", "(", ")", "(", "[", "]", "byte", ",", "error", ")", "{", "b", ":=", "make", "(", "[", "]", "byte", ",", "f", ".", "length", "(", ")", ")", "\n", "_", ",", "err", ":=", "f", ".", "read", "(", "b", ")", "\n", "return", "b", ",", "err", "\n", "}" ]
// MarshalBinary allocates a byte slice and marshals a Frame into binary form.
[ "MarshalBinary", "allocates", "a", "byte", "slice", "and", "marshals", "a", "Frame", "into", "binary", "form", "." ]
5b5fc417d966b71d3781b0d5860413e9fae947c1
https://github.com/mdlayher/ethernet/blob/5b5fc417d966b71d3781b0d5860413e9fae947c1/ethernet.go#L90-L94
1,368
mdlayher/ethernet
ethernet.go
MarshalFCS
func (f *Frame) MarshalFCS() ([]byte, error) { // Frame length with 4 extra bytes for frame check sequence b := make([]byte, f.length()+4) if _, err := f.read(b); err != nil { return nil, err } // Compute IEEE CRC32 checksum of frame bytes and place it directly // in the last four bytes of the slice binary.BigEndian.PutUint32(b[len(b)-4:], crc32.ChecksumIEEE(b[0:len(b)-4])) return b, nil }
go
func (f *Frame) MarshalFCS() ([]byte, error) { // Frame length with 4 extra bytes for frame check sequence b := make([]byte, f.length()+4) if _, err := f.read(b); err != nil { return nil, err } // Compute IEEE CRC32 checksum of frame bytes and place it directly // in the last four bytes of the slice binary.BigEndian.PutUint32(b[len(b)-4:], crc32.ChecksumIEEE(b[0:len(b)-4])) return b, nil }
[ "func", "(", "f", "*", "Frame", ")", "MarshalFCS", "(", ")", "(", "[", "]", "byte", ",", "error", ")", "{", "// Frame length with 4 extra bytes for frame check sequence", "b", ":=", "make", "(", "[", "]", "byte", ",", "f", ".", "length", "(", ")", "+", "4", ")", "\n", "if", "_", ",", "err", ":=", "f", ".", "read", "(", "b", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "// Compute IEEE CRC32 checksum of frame bytes and place it directly", "// in the last four bytes of the slice", "binary", ".", "BigEndian", ".", "PutUint32", "(", "b", "[", "len", "(", "b", ")", "-", "4", ":", "]", ",", "crc32", ".", "ChecksumIEEE", "(", "b", "[", "0", ":", "len", "(", "b", ")", "-", "4", "]", ")", ")", "\n", "return", "b", ",", "nil", "\n", "}" ]
// MarshalFCS allocates a byte slice, marshals a Frame into binary form, and // finally calculates and places a 4-byte IEEE CRC32 frame check sequence at // the end of the slice. // // Most users should use MarshalBinary instead. MarshalFCS is provided as a // convenience for rare occasions when the operating system cannot // automatically generate a frame check sequence for an Ethernet frame.
[ "MarshalFCS", "allocates", "a", "byte", "slice", "marshals", "a", "Frame", "into", "binary", "form", "and", "finally", "calculates", "and", "places", "a", "4", "-", "byte", "IEEE", "CRC32", "frame", "check", "sequence", "at", "the", "end", "of", "the", "slice", ".", "Most", "users", "should", "use", "MarshalBinary", "instead", ".", "MarshalFCS", "is", "provided", "as", "a", "convenience", "for", "rare", "occasions", "when", "the", "operating", "system", "cannot", "automatically", "generate", "a", "frame", "check", "sequence", "for", "an", "Ethernet", "frame", "." ]
5b5fc417d966b71d3781b0d5860413e9fae947c1
https://github.com/mdlayher/ethernet/blob/5b5fc417d966b71d3781b0d5860413e9fae947c1/ethernet.go#L103-L114
1,369
mdlayher/ethernet
ethernet.go
read
func (f *Frame) read(b []byte) (int, error) { // S-VLAN must also have accompanying C-VLAN. if f.ServiceVLAN != nil && f.VLAN == nil { return 0, ErrInvalidVLAN } copy(b[0:6], f.Destination) copy(b[6:12], f.Source) // Marshal each non-nil VLAN tag into bytes, inserting the appropriate // EtherType/TPID before each, so devices know that one or more VLANs // are present. vlans := []struct { vlan *VLAN tpid EtherType }{ {vlan: f.ServiceVLAN, tpid: EtherTypeServiceVLAN}, {vlan: f.VLAN, tpid: EtherTypeVLAN}, } n := 12 for _, vt := range vlans { if vt.vlan == nil { continue } // Add VLAN EtherType and VLAN bytes. binary.BigEndian.PutUint16(b[n:n+2], uint16(vt.tpid)) if _, err := vt.vlan.read(b[n+2 : n+4]); err != nil { return 0, err } n += 4 } // Marshal actual EtherType after any VLANs, copy payload into // output bytes. binary.BigEndian.PutUint16(b[n:n+2], uint16(f.EtherType)) copy(b[n+2:], f.Payload) return len(b), nil }
go
func (f *Frame) read(b []byte) (int, error) { // S-VLAN must also have accompanying C-VLAN. if f.ServiceVLAN != nil && f.VLAN == nil { return 0, ErrInvalidVLAN } copy(b[0:6], f.Destination) copy(b[6:12], f.Source) // Marshal each non-nil VLAN tag into bytes, inserting the appropriate // EtherType/TPID before each, so devices know that one or more VLANs // are present. vlans := []struct { vlan *VLAN tpid EtherType }{ {vlan: f.ServiceVLAN, tpid: EtherTypeServiceVLAN}, {vlan: f.VLAN, tpid: EtherTypeVLAN}, } n := 12 for _, vt := range vlans { if vt.vlan == nil { continue } // Add VLAN EtherType and VLAN bytes. binary.BigEndian.PutUint16(b[n:n+2], uint16(vt.tpid)) if _, err := vt.vlan.read(b[n+2 : n+4]); err != nil { return 0, err } n += 4 } // Marshal actual EtherType after any VLANs, copy payload into // output bytes. binary.BigEndian.PutUint16(b[n:n+2], uint16(f.EtherType)) copy(b[n+2:], f.Payload) return len(b), nil }
[ "func", "(", "f", "*", "Frame", ")", "read", "(", "b", "[", "]", "byte", ")", "(", "int", ",", "error", ")", "{", "// S-VLAN must also have accompanying C-VLAN.", "if", "f", ".", "ServiceVLAN", "!=", "nil", "&&", "f", ".", "VLAN", "==", "nil", "{", "return", "0", ",", "ErrInvalidVLAN", "\n", "}", "\n\n", "copy", "(", "b", "[", "0", ":", "6", "]", ",", "f", ".", "Destination", ")", "\n", "copy", "(", "b", "[", "6", ":", "12", "]", ",", "f", ".", "Source", ")", "\n\n", "// Marshal each non-nil VLAN tag into bytes, inserting the appropriate", "// EtherType/TPID before each, so devices know that one or more VLANs", "// are present.", "vlans", ":=", "[", "]", "struct", "{", "vlan", "*", "VLAN", "\n", "tpid", "EtherType", "\n", "}", "{", "{", "vlan", ":", "f", ".", "ServiceVLAN", ",", "tpid", ":", "EtherTypeServiceVLAN", "}", ",", "{", "vlan", ":", "f", ".", "VLAN", ",", "tpid", ":", "EtherTypeVLAN", "}", ",", "}", "\n\n", "n", ":=", "12", "\n", "for", "_", ",", "vt", ":=", "range", "vlans", "{", "if", "vt", ".", "vlan", "==", "nil", "{", "continue", "\n", "}", "\n\n", "// Add VLAN EtherType and VLAN bytes.", "binary", ".", "BigEndian", ".", "PutUint16", "(", "b", "[", "n", ":", "n", "+", "2", "]", ",", "uint16", "(", "vt", ".", "tpid", ")", ")", "\n", "if", "_", ",", "err", ":=", "vt", ".", "vlan", ".", "read", "(", "b", "[", "n", "+", "2", ":", "n", "+", "4", "]", ")", ";", "err", "!=", "nil", "{", "return", "0", ",", "err", "\n", "}", "\n", "n", "+=", "4", "\n", "}", "\n\n", "// Marshal actual EtherType after any VLANs, copy payload into", "// output bytes.", "binary", ".", "BigEndian", ".", "PutUint16", "(", "b", "[", "n", ":", "n", "+", "2", "]", ",", "uint16", "(", "f", ".", "EtherType", ")", ")", "\n", "copy", "(", "b", "[", "n", "+", "2", ":", "]", ",", "f", ".", "Payload", ")", "\n\n", "return", "len", "(", "b", ")", ",", "nil", "\n", "}" ]
// read reads data from a Frame into b. read is used to marshal a Frame // into binary form, but does not allocate on its own.
[ "read", "reads", "data", "from", "a", "Frame", "into", "b", ".", "read", "is", "used", "to", "marshal", "a", "Frame", "into", "binary", "form", "but", "does", "not", "allocate", "on", "its", "own", "." ]
5b5fc417d966b71d3781b0d5860413e9fae947c1
https://github.com/mdlayher/ethernet/blob/5b5fc417d966b71d3781b0d5860413e9fae947c1/ethernet.go#L118-L158
1,370
mdlayher/ethernet
ethernet.go
UnmarshalBinary
func (f *Frame) UnmarshalBinary(b []byte) error { // Verify that both hardware addresses and a single EtherType are present if len(b) < 14 { return io.ErrUnexpectedEOF } // Track offset in packet for reading data n := 14 // Continue looping and parsing VLAN tags until no more VLAN EtherType // values are detected et := EtherType(binary.BigEndian.Uint16(b[n-2 : n])) switch et { case EtherTypeServiceVLAN, EtherTypeVLAN: // VLAN type is hinted for further parsing. An index is returned which // indicates how many bytes were consumed by VLAN tags. nn, err := f.unmarshalVLANs(et, b[n:]) if err != nil { return err } n += nn default: // No VLANs detected. f.EtherType = et } // Allocate single byte slice to store destination and source hardware // addresses, and payload bb := make([]byte, 6+6+len(b[n:])) copy(bb[0:6], b[0:6]) f.Destination = bb[0:6] copy(bb[6:12], b[6:12]) f.Source = bb[6:12] // There used to be a minimum payload length restriction here, but as // long as two hardware addresses and an EtherType are present, it // doesn't really matter what is contained in the payload. We will // follow the "robustness principle". copy(bb[12:], b[n:]) f.Payload = bb[12:] return nil }
go
func (f *Frame) UnmarshalBinary(b []byte) error { // Verify that both hardware addresses and a single EtherType are present if len(b) < 14 { return io.ErrUnexpectedEOF } // Track offset in packet for reading data n := 14 // Continue looping and parsing VLAN tags until no more VLAN EtherType // values are detected et := EtherType(binary.BigEndian.Uint16(b[n-2 : n])) switch et { case EtherTypeServiceVLAN, EtherTypeVLAN: // VLAN type is hinted for further parsing. An index is returned which // indicates how many bytes were consumed by VLAN tags. nn, err := f.unmarshalVLANs(et, b[n:]) if err != nil { return err } n += nn default: // No VLANs detected. f.EtherType = et } // Allocate single byte slice to store destination and source hardware // addresses, and payload bb := make([]byte, 6+6+len(b[n:])) copy(bb[0:6], b[0:6]) f.Destination = bb[0:6] copy(bb[6:12], b[6:12]) f.Source = bb[6:12] // There used to be a minimum payload length restriction here, but as // long as two hardware addresses and an EtherType are present, it // doesn't really matter what is contained in the payload. We will // follow the "robustness principle". copy(bb[12:], b[n:]) f.Payload = bb[12:] return nil }
[ "func", "(", "f", "*", "Frame", ")", "UnmarshalBinary", "(", "b", "[", "]", "byte", ")", "error", "{", "// Verify that both hardware addresses and a single EtherType are present", "if", "len", "(", "b", ")", "<", "14", "{", "return", "io", ".", "ErrUnexpectedEOF", "\n", "}", "\n\n", "// Track offset in packet for reading data", "n", ":=", "14", "\n\n", "// Continue looping and parsing VLAN tags until no more VLAN EtherType", "// values are detected", "et", ":=", "EtherType", "(", "binary", ".", "BigEndian", ".", "Uint16", "(", "b", "[", "n", "-", "2", ":", "n", "]", ")", ")", "\n", "switch", "et", "{", "case", "EtherTypeServiceVLAN", ",", "EtherTypeVLAN", ":", "// VLAN type is hinted for further parsing. An index is returned which", "// indicates how many bytes were consumed by VLAN tags.", "nn", ",", "err", ":=", "f", ".", "unmarshalVLANs", "(", "et", ",", "b", "[", "n", ":", "]", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "n", "+=", "nn", "\n", "default", ":", "// No VLANs detected.", "f", ".", "EtherType", "=", "et", "\n", "}", "\n\n", "// Allocate single byte slice to store destination and source hardware", "// addresses, and payload", "bb", ":=", "make", "(", "[", "]", "byte", ",", "6", "+", "6", "+", "len", "(", "b", "[", "n", ":", "]", ")", ")", "\n", "copy", "(", "bb", "[", "0", ":", "6", "]", ",", "b", "[", "0", ":", "6", "]", ")", "\n", "f", ".", "Destination", "=", "bb", "[", "0", ":", "6", "]", "\n", "copy", "(", "bb", "[", "6", ":", "12", "]", ",", "b", "[", "6", ":", "12", "]", ")", "\n", "f", ".", "Source", "=", "bb", "[", "6", ":", "12", "]", "\n\n", "// There used to be a minimum payload length restriction here, but as", "// long as two hardware addresses and an EtherType are present, it", "// doesn't really matter what is contained in the payload. We will", "// follow the \"robustness principle\".", "copy", "(", "bb", "[", "12", ":", "]", ",", "b", "[", "n", ":", "]", ")", "\n", "f", ".", "Payload", "=", "bb", "[", "12", ":", "]", "\n\n", "return", "nil", "\n", "}" ]
// UnmarshalBinary unmarshals a byte slice into a Frame.
[ "UnmarshalBinary", "unmarshals", "a", "byte", "slice", "into", "a", "Frame", "." ]
5b5fc417d966b71d3781b0d5860413e9fae947c1
https://github.com/mdlayher/ethernet/blob/5b5fc417d966b71d3781b0d5860413e9fae947c1/ethernet.go#L161-L204
1,371
mdlayher/ethernet
ethernet.go
UnmarshalFCS
func (f *Frame) UnmarshalFCS(b []byte) error { // Must contain enough data for FCS, to avoid panics if len(b) < 4 { return io.ErrUnexpectedEOF } // Verify checksum in slice versus newly computed checksum want := binary.BigEndian.Uint32(b[len(b)-4:]) got := crc32.ChecksumIEEE(b[0 : len(b)-4]) if want != got { return ErrInvalidFCS } return f.UnmarshalBinary(b[0 : len(b)-4]) }
go
func (f *Frame) UnmarshalFCS(b []byte) error { // Must contain enough data for FCS, to avoid panics if len(b) < 4 { return io.ErrUnexpectedEOF } // Verify checksum in slice versus newly computed checksum want := binary.BigEndian.Uint32(b[len(b)-4:]) got := crc32.ChecksumIEEE(b[0 : len(b)-4]) if want != got { return ErrInvalidFCS } return f.UnmarshalBinary(b[0 : len(b)-4]) }
[ "func", "(", "f", "*", "Frame", ")", "UnmarshalFCS", "(", "b", "[", "]", "byte", ")", "error", "{", "// Must contain enough data for FCS, to avoid panics", "if", "len", "(", "b", ")", "<", "4", "{", "return", "io", ".", "ErrUnexpectedEOF", "\n", "}", "\n\n", "// Verify checksum in slice versus newly computed checksum", "want", ":=", "binary", ".", "BigEndian", ".", "Uint32", "(", "b", "[", "len", "(", "b", ")", "-", "4", ":", "]", ")", "\n", "got", ":=", "crc32", ".", "ChecksumIEEE", "(", "b", "[", "0", ":", "len", "(", "b", ")", "-", "4", "]", ")", "\n", "if", "want", "!=", "got", "{", "return", "ErrInvalidFCS", "\n", "}", "\n\n", "return", "f", ".", "UnmarshalBinary", "(", "b", "[", "0", ":", "len", "(", "b", ")", "-", "4", "]", ")", "\n", "}" ]
// UnmarshalFCS computes the IEEE CRC32 frame check sequence of a Frame, // verifies it against the checksum present in the byte slice, and finally, // unmarshals a byte slice into a Frame. // // Most users should use UnmarshalBinary instead. UnmarshalFCS is provided as // a convenience for rare occasions when the operating system cannot // automatically verify a frame check sequence for an Ethernet frame.
[ "UnmarshalFCS", "computes", "the", "IEEE", "CRC32", "frame", "check", "sequence", "of", "a", "Frame", "verifies", "it", "against", "the", "checksum", "present", "in", "the", "byte", "slice", "and", "finally", "unmarshals", "a", "byte", "slice", "into", "a", "Frame", ".", "Most", "users", "should", "use", "UnmarshalBinary", "instead", ".", "UnmarshalFCS", "is", "provided", "as", "a", "convenience", "for", "rare", "occasions", "when", "the", "operating", "system", "cannot", "automatically", "verify", "a", "frame", "check", "sequence", "for", "an", "Ethernet", "frame", "." ]
5b5fc417d966b71d3781b0d5860413e9fae947c1
https://github.com/mdlayher/ethernet/blob/5b5fc417d966b71d3781b0d5860413e9fae947c1/ethernet.go#L213-L227
1,372
mdlayher/ethernet
ethernet.go
length
func (f *Frame) length() int { // If payload is less than the required minimum length, we zero-pad up to // the required minimum length pl := len(f.Payload) if pl < minPayload { pl = minPayload } // Add additional length if VLAN tags are needed. var vlanLen int switch { case f.ServiceVLAN != nil && f.VLAN != nil: vlanLen = 8 case f.VLAN != nil: vlanLen = 4 } // 6 bytes: destination hardware address // 6 bytes: source hardware address // N bytes: VLAN tags (if present) // 2 bytes: EtherType // N bytes: payload length (may be padded) return 6 + 6 + vlanLen + 2 + pl }
go
func (f *Frame) length() int { // If payload is less than the required minimum length, we zero-pad up to // the required minimum length pl := len(f.Payload) if pl < minPayload { pl = minPayload } // Add additional length if VLAN tags are needed. var vlanLen int switch { case f.ServiceVLAN != nil && f.VLAN != nil: vlanLen = 8 case f.VLAN != nil: vlanLen = 4 } // 6 bytes: destination hardware address // 6 bytes: source hardware address // N bytes: VLAN tags (if present) // 2 bytes: EtherType // N bytes: payload length (may be padded) return 6 + 6 + vlanLen + 2 + pl }
[ "func", "(", "f", "*", "Frame", ")", "length", "(", ")", "int", "{", "// If payload is less than the required minimum length, we zero-pad up to", "// the required minimum length", "pl", ":=", "len", "(", "f", ".", "Payload", ")", "\n", "if", "pl", "<", "minPayload", "{", "pl", "=", "minPayload", "\n", "}", "\n\n", "// Add additional length if VLAN tags are needed.", "var", "vlanLen", "int", "\n", "switch", "{", "case", "f", ".", "ServiceVLAN", "!=", "nil", "&&", "f", ".", "VLAN", "!=", "nil", ":", "vlanLen", "=", "8", "\n", "case", "f", ".", "VLAN", "!=", "nil", ":", "vlanLen", "=", "4", "\n", "}", "\n\n", "// 6 bytes: destination hardware address", "// 6 bytes: source hardware address", "// N bytes: VLAN tags (if present)", "// 2 bytes: EtherType", "// N bytes: payload length (may be padded)", "return", "6", "+", "6", "+", "vlanLen", "+", "2", "+", "pl", "\n", "}" ]
// length calculates the number of bytes required to store a Frame.
[ "length", "calculates", "the", "number", "of", "bytes", "required", "to", "store", "a", "Frame", "." ]
5b5fc417d966b71d3781b0d5860413e9fae947c1
https://github.com/mdlayher/ethernet/blob/5b5fc417d966b71d3781b0d5860413e9fae947c1/ethernet.go#L230-L253
1,373
grafana-tools/sdk
rest-user.go
GetActualUser
func (r *Client) GetActualUser() (User, error) { var ( raw []byte user User code int err error ) if raw, code, err = r.get("api/user", nil); err != nil { return user, err } if code != 200 { return user, fmt.Errorf("HTTP error %d: returns %s", code, raw) } dec := json.NewDecoder(bytes.NewReader(raw)) dec.UseNumber() if err := dec.Decode(&user); err != nil { return user, fmt.Errorf("unmarshal user: %s\n%s", err, raw) } return user, err }
go
func (r *Client) GetActualUser() (User, error) { var ( raw []byte user User code int err error ) if raw, code, err = r.get("api/user", nil); err != nil { return user, err } if code != 200 { return user, fmt.Errorf("HTTP error %d: returns %s", code, raw) } dec := json.NewDecoder(bytes.NewReader(raw)) dec.UseNumber() if err := dec.Decode(&user); err != nil { return user, fmt.Errorf("unmarshal user: %s\n%s", err, raw) } return user, err }
[ "func", "(", "r", "*", "Client", ")", "GetActualUser", "(", ")", "(", "User", ",", "error", ")", "{", "var", "(", "raw", "[", "]", "byte", "\n", "user", "User", "\n", "code", "int", "\n", "err", "error", "\n", ")", "\n", "if", "raw", ",", "code", ",", "err", "=", "r", ".", "get", "(", "\"", "\"", ",", "nil", ")", ";", "err", "!=", "nil", "{", "return", "user", ",", "err", "\n", "}", "\n", "if", "code", "!=", "200", "{", "return", "user", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "code", ",", "raw", ")", "\n", "}", "\n", "dec", ":=", "json", ".", "NewDecoder", "(", "bytes", ".", "NewReader", "(", "raw", ")", ")", "\n", "dec", ".", "UseNumber", "(", ")", "\n", "if", "err", ":=", "dec", ".", "Decode", "(", "&", "user", ")", ";", "err", "!=", "nil", "{", "return", "user", ",", "fmt", ".", "Errorf", "(", "\"", "\\n", "\"", ",", "err", ",", "raw", ")", "\n", "}", "\n", "return", "user", ",", "err", "\n", "}" ]
// GetActualUser gets an actual user.
[ "GetActualUser", "gets", "an", "actual", "user", "." ]
5158161510f07142e96b0c3d4be124b47fe2c070
https://github.com/grafana-tools/sdk/blob/5158161510f07142e96b0c3d4be124b47fe2c070/rest-user.go#L29-L48
1,374
grafana-tools/sdk
panel.go
NewDashlist
func NewDashlist(title string) *Panel { if title == "" { title = "Panel Title" } render := "flot" return &Panel{ commonPanel: commonPanel{ OfType: DashlistType, Title: title, Type: "dashlist", Renderer: &render, IsNew: true}, DashlistPanel: &DashlistPanel{}} }
go
func NewDashlist(title string) *Panel { if title == "" { title = "Panel Title" } render := "flot" return &Panel{ commonPanel: commonPanel{ OfType: DashlistType, Title: title, Type: "dashlist", Renderer: &render, IsNew: true}, DashlistPanel: &DashlistPanel{}} }
[ "func", "NewDashlist", "(", "title", "string", ")", "*", "Panel", "{", "if", "title", "==", "\"", "\"", "{", "title", "=", "\"", "\"", "\n", "}", "\n", "render", ":=", "\"", "\"", "\n", "return", "&", "Panel", "{", "commonPanel", ":", "commonPanel", "{", "OfType", ":", "DashlistType", ",", "Title", ":", "title", ",", "Type", ":", "\"", "\"", ",", "Renderer", ":", "&", "render", ",", "IsNew", ":", "true", "}", ",", "DashlistPanel", ":", "&", "DashlistPanel", "{", "}", "}", "\n", "}" ]
// NewDashlist initializes panel with a dashlist panel.
[ "NewDashlist", "initializes", "panel", "with", "a", "dashlist", "panel", "." ]
5158161510f07142e96b0c3d4be124b47fe2c070
https://github.com/grafana-tools/sdk/blob/5158161510f07142e96b0c3d4be124b47fe2c070/panel.go#L400-L413
1,375
grafana-tools/sdk
panel.go
NewGraph
func NewGraph(title string) *Panel { if title == "" { title = "Panel Title" } render := "flot" return &Panel{ commonPanel: commonPanel{ OfType: GraphType, Title: title, Type: "graph", Renderer: &render, Span: 12, IsNew: true}, GraphPanel: &GraphPanel{ NullPointMode: "connected", Pointradius: 5, XAxis: true, YAxis: true, }} }
go
func NewGraph(title string) *Panel { if title == "" { title = "Panel Title" } render := "flot" return &Panel{ commonPanel: commonPanel{ OfType: GraphType, Title: title, Type: "graph", Renderer: &render, Span: 12, IsNew: true}, GraphPanel: &GraphPanel{ NullPointMode: "connected", Pointradius: 5, XAxis: true, YAxis: true, }} }
[ "func", "NewGraph", "(", "title", "string", ")", "*", "Panel", "{", "if", "title", "==", "\"", "\"", "{", "title", "=", "\"", "\"", "\n", "}", "\n", "render", ":=", "\"", "\"", "\n", "return", "&", "Panel", "{", "commonPanel", ":", "commonPanel", "{", "OfType", ":", "GraphType", ",", "Title", ":", "title", ",", "Type", ":", "\"", "\"", ",", "Renderer", ":", "&", "render", ",", "Span", ":", "12", ",", "IsNew", ":", "true", "}", ",", "GraphPanel", ":", "&", "GraphPanel", "{", "NullPointMode", ":", "\"", "\"", ",", "Pointradius", ":", "5", ",", "XAxis", ":", "true", ",", "YAxis", ":", "true", ",", "}", "}", "\n", "}" ]
// NewGraph initializes panel with a graph panel.
[ "NewGraph", "initializes", "panel", "with", "a", "graph", "panel", "." ]
5158161510f07142e96b0c3d4be124b47fe2c070
https://github.com/grafana-tools/sdk/blob/5158161510f07142e96b0c3d4be124b47fe2c070/panel.go#L416-L435
1,376
grafana-tools/sdk
panel.go
NewTable
func NewTable(title string) *Panel { if title == "" { title = "Panel Title" } render := "flot" return &Panel{ commonPanel: commonPanel{ OfType: TableType, Title: title, Type: "table", Renderer: &render, IsNew: true}, TablePanel: &TablePanel{}} }
go
func NewTable(title string) *Panel { if title == "" { title = "Panel Title" } render := "flot" return &Panel{ commonPanel: commonPanel{ OfType: TableType, Title: title, Type: "table", Renderer: &render, IsNew: true}, TablePanel: &TablePanel{}} }
[ "func", "NewTable", "(", "title", "string", ")", "*", "Panel", "{", "if", "title", "==", "\"", "\"", "{", "title", "=", "\"", "\"", "\n", "}", "\n", "render", ":=", "\"", "\"", "\n", "return", "&", "Panel", "{", "commonPanel", ":", "commonPanel", "{", "OfType", ":", "TableType", ",", "Title", ":", "title", ",", "Type", ":", "\"", "\"", ",", "Renderer", ":", "&", "render", ",", "IsNew", ":", "true", "}", ",", "TablePanel", ":", "&", "TablePanel", "{", "}", "}", "\n", "}" ]
// NewTable initializes panel with a table panel.
[ "NewTable", "initializes", "panel", "with", "a", "table", "panel", "." ]
5158161510f07142e96b0c3d4be124b47fe2c070
https://github.com/grafana-tools/sdk/blob/5158161510f07142e96b0c3d4be124b47fe2c070/panel.go#L438-L451
1,377
grafana-tools/sdk
panel.go
NewText
func NewText(title string) *Panel { if title == "" { title = "Panel Title" } render := "flot" return &Panel{ commonPanel: commonPanel{ OfType: TextType, Title: title, Type: "text", Renderer: &render, IsNew: true}, TextPanel: &TextPanel{}} }
go
func NewText(title string) *Panel { if title == "" { title = "Panel Title" } render := "flot" return &Panel{ commonPanel: commonPanel{ OfType: TextType, Title: title, Type: "text", Renderer: &render, IsNew: true}, TextPanel: &TextPanel{}} }
[ "func", "NewText", "(", "title", "string", ")", "*", "Panel", "{", "if", "title", "==", "\"", "\"", "{", "title", "=", "\"", "\"", "\n", "}", "\n", "render", ":=", "\"", "\"", "\n", "return", "&", "Panel", "{", "commonPanel", ":", "commonPanel", "{", "OfType", ":", "TextType", ",", "Title", ":", "title", ",", "Type", ":", "\"", "\"", ",", "Renderer", ":", "&", "render", ",", "IsNew", ":", "true", "}", ",", "TextPanel", ":", "&", "TextPanel", "{", "}", "}", "\n", "}" ]
// NewText initializes panel with a text panel.
[ "NewText", "initializes", "panel", "with", "a", "text", "panel", "." ]
5158161510f07142e96b0c3d4be124b47fe2c070
https://github.com/grafana-tools/sdk/blob/5158161510f07142e96b0c3d4be124b47fe2c070/panel.go#L454-L467
1,378
grafana-tools/sdk
panel.go
NewSinglestat
func NewSinglestat(title string) *Panel { if title == "" { title = "Panel Title" } render := "flot" return &Panel{ commonPanel: commonPanel{ OfType: SinglestatType, Title: title, Type: "singlestat", Renderer: &render, IsNew: true}, SinglestatPanel: &SinglestatPanel{}} }
go
func NewSinglestat(title string) *Panel { if title == "" { title = "Panel Title" } render := "flot" return &Panel{ commonPanel: commonPanel{ OfType: SinglestatType, Title: title, Type: "singlestat", Renderer: &render, IsNew: true}, SinglestatPanel: &SinglestatPanel{}} }
[ "func", "NewSinglestat", "(", "title", "string", ")", "*", "Panel", "{", "if", "title", "==", "\"", "\"", "{", "title", "=", "\"", "\"", "\n", "}", "\n", "render", ":=", "\"", "\"", "\n", "return", "&", "Panel", "{", "commonPanel", ":", "commonPanel", "{", "OfType", ":", "SinglestatType", ",", "Title", ":", "title", ",", "Type", ":", "\"", "\"", ",", "Renderer", ":", "&", "render", ",", "IsNew", ":", "true", "}", ",", "SinglestatPanel", ":", "&", "SinglestatPanel", "{", "}", "}", "\n", "}" ]
// NewSinglestat initializes panel with a singlestat panel.
[ "NewSinglestat", "initializes", "panel", "with", "a", "singlestat", "panel", "." ]
5158161510f07142e96b0c3d4be124b47fe2c070
https://github.com/grafana-tools/sdk/blob/5158161510f07142e96b0c3d4be124b47fe2c070/panel.go#L470-L483
1,379
grafana-tools/sdk
panel.go
NewPluginlist
func NewPluginlist(title string) *Panel { if title == "" { title = "Panel Title" } render := "flot" return &Panel{ commonPanel: commonPanel{ OfType: PluginlistType, Title: title, Type: "pluginlist", Renderer: &render, IsNew: true}, PluginlistPanel: &PluginlistPanel{}} }
go
func NewPluginlist(title string) *Panel { if title == "" { title = "Panel Title" } render := "flot" return &Panel{ commonPanel: commonPanel{ OfType: PluginlistType, Title: title, Type: "pluginlist", Renderer: &render, IsNew: true}, PluginlistPanel: &PluginlistPanel{}} }
[ "func", "NewPluginlist", "(", "title", "string", ")", "*", "Panel", "{", "if", "title", "==", "\"", "\"", "{", "title", "=", "\"", "\"", "\n", "}", "\n", "render", ":=", "\"", "\"", "\n", "return", "&", "Panel", "{", "commonPanel", ":", "commonPanel", "{", "OfType", ":", "PluginlistType", ",", "Title", ":", "title", ",", "Type", ":", "\"", "\"", ",", "Renderer", ":", "&", "render", ",", "IsNew", ":", "true", "}", ",", "PluginlistPanel", ":", "&", "PluginlistPanel", "{", "}", "}", "\n", "}" ]
// NewPluginlist initializes panel with a singlestat panel.
[ "NewPluginlist", "initializes", "panel", "with", "a", "singlestat", "panel", "." ]
5158161510f07142e96b0c3d4be124b47fe2c070
https://github.com/grafana-tools/sdk/blob/5158161510f07142e96b0c3d4be124b47fe2c070/panel.go#L486-L499
1,380
grafana-tools/sdk
panel.go
NewCustom
func NewCustom(title string) *Panel { if title == "" { title = "Panel Title" } render := "flot" return &Panel{ commonPanel: commonPanel{ OfType: CustomType, Title: title, Type: "singlestat", Renderer: &render, IsNew: true}, CustomPanel: &CustomPanel{}} }
go
func NewCustom(title string) *Panel { if title == "" { title = "Panel Title" } render := "flot" return &Panel{ commonPanel: commonPanel{ OfType: CustomType, Title: title, Type: "singlestat", Renderer: &render, IsNew: true}, CustomPanel: &CustomPanel{}} }
[ "func", "NewCustom", "(", "title", "string", ")", "*", "Panel", "{", "if", "title", "==", "\"", "\"", "{", "title", "=", "\"", "\"", "\n", "}", "\n", "render", ":=", "\"", "\"", "\n", "return", "&", "Panel", "{", "commonPanel", ":", "commonPanel", "{", "OfType", ":", "CustomType", ",", "Title", ":", "title", ",", "Type", ":", "\"", "\"", ",", "Renderer", ":", "&", "render", ",", "IsNew", ":", "true", "}", ",", "CustomPanel", ":", "&", "CustomPanel", "{", "}", "}", "\n", "}" ]
// NewCustom initializes panel with a singlestat panel.
[ "NewCustom", "initializes", "panel", "with", "a", "singlestat", "panel", "." ]
5158161510f07142e96b0c3d4be124b47fe2c070
https://github.com/grafana-tools/sdk/blob/5158161510f07142e96b0c3d4be124b47fe2c070/panel.go#L517-L530
1,381
grafana-tools/sdk
panel.go
ResetTargets
func (p *Panel) ResetTargets() { switch p.OfType { case GraphType: p.GraphPanel.Targets = nil case SinglestatType: p.SinglestatPanel.Targets = nil case TableType: p.TablePanel.Targets = nil } }
go
func (p *Panel) ResetTargets() { switch p.OfType { case GraphType: p.GraphPanel.Targets = nil case SinglestatType: p.SinglestatPanel.Targets = nil case TableType: p.TablePanel.Targets = nil } }
[ "func", "(", "p", "*", "Panel", ")", "ResetTargets", "(", ")", "{", "switch", "p", ".", "OfType", "{", "case", "GraphType", ":", "p", ".", "GraphPanel", ".", "Targets", "=", "nil", "\n", "case", "SinglestatType", ":", "p", ".", "SinglestatPanel", ".", "Targets", "=", "nil", "\n", "case", "TableType", ":", "p", ".", "TablePanel", ".", "Targets", "=", "nil", "\n", "}", "\n", "}" ]
// ResetTargets delete all targets defined for a panel.
[ "ResetTargets", "delete", "all", "targets", "defined", "for", "a", "panel", "." ]
5158161510f07142e96b0c3d4be124b47fe2c070
https://github.com/grafana-tools/sdk/blob/5158161510f07142e96b0c3d4be124b47fe2c070/panel.go#L533-L542
1,382
grafana-tools/sdk
panel.go
AddTarget
func (p *Panel) AddTarget(t *Target) { switch p.OfType { case GraphType: p.GraphPanel.Targets = append(p.GraphPanel.Targets, *t) case SinglestatType: p.SinglestatPanel.Targets = append(p.SinglestatPanel.Targets, *t) case TableType: p.TablePanel.Targets = append(p.TablePanel.Targets, *t) } // TODO check for existing refID }
go
func (p *Panel) AddTarget(t *Target) { switch p.OfType { case GraphType: p.GraphPanel.Targets = append(p.GraphPanel.Targets, *t) case SinglestatType: p.SinglestatPanel.Targets = append(p.SinglestatPanel.Targets, *t) case TableType: p.TablePanel.Targets = append(p.TablePanel.Targets, *t) } // TODO check for existing refID }
[ "func", "(", "p", "*", "Panel", ")", "AddTarget", "(", "t", "*", "Target", ")", "{", "switch", "p", ".", "OfType", "{", "case", "GraphType", ":", "p", ".", "GraphPanel", ".", "Targets", "=", "append", "(", "p", ".", "GraphPanel", ".", "Targets", ",", "*", "t", ")", "\n", "case", "SinglestatType", ":", "p", ".", "SinglestatPanel", ".", "Targets", "=", "append", "(", "p", ".", "SinglestatPanel", ".", "Targets", ",", "*", "t", ")", "\n", "case", "TableType", ":", "p", ".", "TablePanel", ".", "Targets", "=", "append", "(", "p", ".", "TablePanel", ".", "Targets", ",", "*", "t", ")", "\n", "}", "\n", "// TODO check for existing refID", "}" ]
// AddTarget adds a new target as defined in the argument // but with refId letter incremented. Value of refID from // the argument will be used only if no target with such // value already exists.
[ "AddTarget", "adds", "a", "new", "target", "as", "defined", "in", "the", "argument", "but", "with", "refId", "letter", "incremented", ".", "Value", "of", "refID", "from", "the", "argument", "will", "be", "used", "only", "if", "no", "target", "with", "such", "value", "already", "exists", "." ]
5158161510f07142e96b0c3d4be124b47fe2c070
https://github.com/grafana-tools/sdk/blob/5158161510f07142e96b0c3d4be124b47fe2c070/panel.go#L548-L558
1,383
grafana-tools/sdk
panel.go
SetTarget
func (p *Panel) SetTarget(t *Target) { setTarget := func(t *Target, targets *[]Target) { for i, target := range *targets { if t.RefID == target.RefID { (*targets)[i] = *t return } } (*targets) = append((*targets), *t) } switch p.OfType { case GraphType: setTarget(t, &p.GraphPanel.Targets) case SinglestatType: setTarget(t, &p.SinglestatPanel.Targets) case TableType: setTarget(t, &p.TablePanel.Targets) } }
go
func (p *Panel) SetTarget(t *Target) { setTarget := func(t *Target, targets *[]Target) { for i, target := range *targets { if t.RefID == target.RefID { (*targets)[i] = *t return } } (*targets) = append((*targets), *t) } switch p.OfType { case GraphType: setTarget(t, &p.GraphPanel.Targets) case SinglestatType: setTarget(t, &p.SinglestatPanel.Targets) case TableType: setTarget(t, &p.TablePanel.Targets) } }
[ "func", "(", "p", "*", "Panel", ")", "SetTarget", "(", "t", "*", "Target", ")", "{", "setTarget", ":=", "func", "(", "t", "*", "Target", ",", "targets", "*", "[", "]", "Target", ")", "{", "for", "i", ",", "target", ":=", "range", "*", "targets", "{", "if", "t", ".", "RefID", "==", "target", ".", "RefID", "{", "(", "*", "targets", ")", "[", "i", "]", "=", "*", "t", "\n", "return", "\n", "}", "\n", "}", "\n", "(", "*", "targets", ")", "=", "append", "(", "(", "*", "targets", ")", ",", "*", "t", ")", "\n", "}", "\n", "switch", "p", ".", "OfType", "{", "case", "GraphType", ":", "setTarget", "(", "t", ",", "&", "p", ".", "GraphPanel", ".", "Targets", ")", "\n", "case", "SinglestatType", ":", "setTarget", "(", "t", ",", "&", "p", ".", "SinglestatPanel", ".", "Targets", ")", "\n", "case", "TableType", ":", "setTarget", "(", "t", ",", "&", "p", ".", "TablePanel", ".", "Targets", ")", "\n", "}", "\n", "}" ]
// SetTarget updates a target if target with such refId exists // or creates a new one.
[ "SetTarget", "updates", "a", "target", "if", "target", "with", "such", "refId", "exists", "or", "creates", "a", "new", "one", "." ]
5158161510f07142e96b0c3d4be124b47fe2c070
https://github.com/grafana-tools/sdk/blob/5158161510f07142e96b0c3d4be124b47fe2c070/panel.go#L562-L580
1,384
grafana-tools/sdk
panel.go
RepeatDatasourcesForEachTarget
func (p *Panel) RepeatDatasourcesForEachTarget(dsNames ...string) { repeatDS := func(dsNames []string, targets *[]Target) { var refID = "A" originalTargets := *targets cleanedTargets := make([]Target, 0, len(originalTargets)*len(dsNames)) *targets = cleanedTargets for _, target := range originalTargets { for _, ds := range dsNames { newTarget := target newTarget.RefID = refID newTarget.Datasource = ds refID = incRefID(refID) *targets = append(*targets, newTarget) } } } switch p.OfType { case GraphType: repeatDS(dsNames, &p.GraphPanel.Targets) case SinglestatType: repeatDS(dsNames, &p.SinglestatPanel.Targets) case TableType: repeatDS(dsNames, &p.TablePanel.Targets) } }
go
func (p *Panel) RepeatDatasourcesForEachTarget(dsNames ...string) { repeatDS := func(dsNames []string, targets *[]Target) { var refID = "A" originalTargets := *targets cleanedTargets := make([]Target, 0, len(originalTargets)*len(dsNames)) *targets = cleanedTargets for _, target := range originalTargets { for _, ds := range dsNames { newTarget := target newTarget.RefID = refID newTarget.Datasource = ds refID = incRefID(refID) *targets = append(*targets, newTarget) } } } switch p.OfType { case GraphType: repeatDS(dsNames, &p.GraphPanel.Targets) case SinglestatType: repeatDS(dsNames, &p.SinglestatPanel.Targets) case TableType: repeatDS(dsNames, &p.TablePanel.Targets) } }
[ "func", "(", "p", "*", "Panel", ")", "RepeatDatasourcesForEachTarget", "(", "dsNames", "...", "string", ")", "{", "repeatDS", ":=", "func", "(", "dsNames", "[", "]", "string", ",", "targets", "*", "[", "]", "Target", ")", "{", "var", "refID", "=", "\"", "\"", "\n", "originalTargets", ":=", "*", "targets", "\n", "cleanedTargets", ":=", "make", "(", "[", "]", "Target", ",", "0", ",", "len", "(", "originalTargets", ")", "*", "len", "(", "dsNames", ")", ")", "\n", "*", "targets", "=", "cleanedTargets", "\n", "for", "_", ",", "target", ":=", "range", "originalTargets", "{", "for", "_", ",", "ds", ":=", "range", "dsNames", "{", "newTarget", ":=", "target", "\n", "newTarget", ".", "RefID", "=", "refID", "\n", "newTarget", ".", "Datasource", "=", "ds", "\n", "refID", "=", "incRefID", "(", "refID", ")", "\n", "*", "targets", "=", "append", "(", "*", "targets", ",", "newTarget", ")", "\n", "}", "\n", "}", "\n", "}", "\n", "switch", "p", ".", "OfType", "{", "case", "GraphType", ":", "repeatDS", "(", "dsNames", ",", "&", "p", ".", "GraphPanel", ".", "Targets", ")", "\n", "case", "SinglestatType", ":", "repeatDS", "(", "dsNames", ",", "&", "p", ".", "SinglestatPanel", ".", "Targets", ")", "\n", "case", "TableType", ":", "repeatDS", "(", "dsNames", ",", "&", "p", ".", "TablePanel", ".", "Targets", ")", "\n", "}", "\n", "}" ]
// MapDatasources on all existing targets for the panel.
[ "MapDatasources", "on", "all", "existing", "targets", "for", "the", "panel", "." ]
5158161510f07142e96b0c3d4be124b47fe2c070
https://github.com/grafana-tools/sdk/blob/5158161510f07142e96b0c3d4be124b47fe2c070/panel.go#L583-L607
1,385
grafana-tools/sdk
panel.go
RepeatTargetsForDatasources
func (p *Panel) RepeatTargetsForDatasources(dsNames ...string) { repeatTarget := func(dsNames []string, targets *[]Target) { var lastRefID string lenTargets := len(*targets) for i, name := range dsNames { if i < lenTargets { (*targets)[i].Datasource = name lastRefID = (*targets)[i].RefID } else { newTarget := (*targets)[i%lenTargets] lastRefID = incRefID(lastRefID) newTarget.RefID = lastRefID newTarget.Datasource = name *targets = append(*targets, newTarget) } } } switch p.OfType { case GraphType: repeatTarget(dsNames, &p.GraphPanel.Targets) case SinglestatType: repeatTarget(dsNames, &p.SinglestatPanel.Targets) case TableType: repeatTarget(dsNames, &p.TablePanel.Targets) } }
go
func (p *Panel) RepeatTargetsForDatasources(dsNames ...string) { repeatTarget := func(dsNames []string, targets *[]Target) { var lastRefID string lenTargets := len(*targets) for i, name := range dsNames { if i < lenTargets { (*targets)[i].Datasource = name lastRefID = (*targets)[i].RefID } else { newTarget := (*targets)[i%lenTargets] lastRefID = incRefID(lastRefID) newTarget.RefID = lastRefID newTarget.Datasource = name *targets = append(*targets, newTarget) } } } switch p.OfType { case GraphType: repeatTarget(dsNames, &p.GraphPanel.Targets) case SinglestatType: repeatTarget(dsNames, &p.SinglestatPanel.Targets) case TableType: repeatTarget(dsNames, &p.TablePanel.Targets) } }
[ "func", "(", "p", "*", "Panel", ")", "RepeatTargetsForDatasources", "(", "dsNames", "...", "string", ")", "{", "repeatTarget", ":=", "func", "(", "dsNames", "[", "]", "string", ",", "targets", "*", "[", "]", "Target", ")", "{", "var", "lastRefID", "string", "\n", "lenTargets", ":=", "len", "(", "*", "targets", ")", "\n", "for", "i", ",", "name", ":=", "range", "dsNames", "{", "if", "i", "<", "lenTargets", "{", "(", "*", "targets", ")", "[", "i", "]", ".", "Datasource", "=", "name", "\n", "lastRefID", "=", "(", "*", "targets", ")", "[", "i", "]", ".", "RefID", "\n", "}", "else", "{", "newTarget", ":=", "(", "*", "targets", ")", "[", "i", "%", "lenTargets", "]", "\n", "lastRefID", "=", "incRefID", "(", "lastRefID", ")", "\n", "newTarget", ".", "RefID", "=", "lastRefID", "\n", "newTarget", ".", "Datasource", "=", "name", "\n", "*", "targets", "=", "append", "(", "*", "targets", ",", "newTarget", ")", "\n", "}", "\n", "}", "\n", "}", "\n", "switch", "p", ".", "OfType", "{", "case", "GraphType", ":", "repeatTarget", "(", "dsNames", ",", "&", "p", ".", "GraphPanel", ".", "Targets", ")", "\n", "case", "SinglestatType", ":", "repeatTarget", "(", "dsNames", ",", "&", "p", ".", "SinglestatPanel", ".", "Targets", ")", "\n", "case", "TableType", ":", "repeatTarget", "(", "dsNames", ",", "&", "p", ".", "TablePanel", ".", "Targets", ")", "\n", "}", "\n", "}" ]
// RepeatTargetsForDatasources repeats all existing targets for a panel // for all provided in the argument datasources. Existing datasources of // targets are ignored.
[ "RepeatTargetsForDatasources", "repeats", "all", "existing", "targets", "for", "a", "panel", "for", "all", "provided", "in", "the", "argument", "datasources", ".", "Existing", "datasources", "of", "targets", "are", "ignored", "." ]
5158161510f07142e96b0c3d4be124b47fe2c070
https://github.com/grafana-tools/sdk/blob/5158161510f07142e96b0c3d4be124b47fe2c070/panel.go#L612-L637
1,386
grafana-tools/sdk
panel.go
GetTargets
func (p *Panel) GetTargets() *[]Target { switch p.OfType { case GraphType: return &p.GraphPanel.Targets case SinglestatType: return &p.SinglestatPanel.Targets case TableType: return &p.TablePanel.Targets default: return nil } }
go
func (p *Panel) GetTargets() *[]Target { switch p.OfType { case GraphType: return &p.GraphPanel.Targets case SinglestatType: return &p.SinglestatPanel.Targets case TableType: return &p.TablePanel.Targets default: return nil } }
[ "func", "(", "p", "*", "Panel", ")", "GetTargets", "(", ")", "*", "[", "]", "Target", "{", "switch", "p", ".", "OfType", "{", "case", "GraphType", ":", "return", "&", "p", ".", "GraphPanel", ".", "Targets", "\n", "case", "SinglestatType", ":", "return", "&", "p", ".", "SinglestatPanel", ".", "Targets", "\n", "case", "TableType", ":", "return", "&", "p", ".", "TablePanel", ".", "Targets", "\n", "default", ":", "return", "nil", "\n", "}", "\n", "}" ]
// GetTargets is iterate over all panel targets. It just returns nil if // no targets defined for panel of concrete type.
[ "GetTargets", "is", "iterate", "over", "all", "panel", "targets", ".", "It", "just", "returns", "nil", "if", "no", "targets", "defined", "for", "panel", "of", "concrete", "type", "." ]
5158161510f07142e96b0c3d4be124b47fe2c070
https://github.com/grafana-tools/sdk/blob/5158161510f07142e96b0c3d4be124b47fe2c070/panel.go#L641-L652
1,387
grafana-tools/sdk
rest-dashboard.go
SetDashboard
func (r *Client) SetDashboard(board Board, overwrite bool) error { var ( isBoardFromDB bool newBoard struct { Dashboard Board `json:"dashboard"` Overwrite bool `json:"overwrite"` } raw []byte resp StatusMessage code int err error ) if board.Slug, isBoardFromDB = cleanPrefix(board.Slug); !isBoardFromDB { return errors.New("only database dashboard (with 'db/' prefix in a slug) can be set") } newBoard.Dashboard = board newBoard.Overwrite = overwrite if !overwrite { newBoard.Dashboard.ID = 0 } if raw, err = json.Marshal(newBoard); err != nil { return err } if raw, code, err = r.post("api/dashboards/db", nil, raw); err != nil { return err } if err = json.Unmarshal(raw, &resp); err != nil { return err } switch code { case 401: return fmt.Errorf("%d %s", code, *resp.Message) case 412: return fmt.Errorf("%d %s", code, *resp.Message) } return nil }
go
func (r *Client) SetDashboard(board Board, overwrite bool) error { var ( isBoardFromDB bool newBoard struct { Dashboard Board `json:"dashboard"` Overwrite bool `json:"overwrite"` } raw []byte resp StatusMessage code int err error ) if board.Slug, isBoardFromDB = cleanPrefix(board.Slug); !isBoardFromDB { return errors.New("only database dashboard (with 'db/' prefix in a slug) can be set") } newBoard.Dashboard = board newBoard.Overwrite = overwrite if !overwrite { newBoard.Dashboard.ID = 0 } if raw, err = json.Marshal(newBoard); err != nil { return err } if raw, code, err = r.post("api/dashboards/db", nil, raw); err != nil { return err } if err = json.Unmarshal(raw, &resp); err != nil { return err } switch code { case 401: return fmt.Errorf("%d %s", code, *resp.Message) case 412: return fmt.Errorf("%d %s", code, *resp.Message) } return nil }
[ "func", "(", "r", "*", "Client", ")", "SetDashboard", "(", "board", "Board", ",", "overwrite", "bool", ")", "error", "{", "var", "(", "isBoardFromDB", "bool", "\n", "newBoard", "struct", "{", "Dashboard", "Board", "`json:\"dashboard\"`", "\n", "Overwrite", "bool", "`json:\"overwrite\"`", "\n", "}", "\n", "raw", "[", "]", "byte", "\n", "resp", "StatusMessage", "\n", "code", "int", "\n", "err", "error", "\n", ")", "\n", "if", "board", ".", "Slug", ",", "isBoardFromDB", "=", "cleanPrefix", "(", "board", ".", "Slug", ")", ";", "!", "isBoardFromDB", "{", "return", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "}", "\n", "newBoard", ".", "Dashboard", "=", "board", "\n", "newBoard", ".", "Overwrite", "=", "overwrite", "\n", "if", "!", "overwrite", "{", "newBoard", ".", "Dashboard", ".", "ID", "=", "0", "\n", "}", "\n", "if", "raw", ",", "err", "=", "json", ".", "Marshal", "(", "newBoard", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "if", "raw", ",", "code", ",", "err", "=", "r", ".", "post", "(", "\"", "\"", ",", "nil", ",", "raw", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "if", "err", "=", "json", ".", "Unmarshal", "(", "raw", ",", "&", "resp", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "switch", "code", "{", "case", "401", ":", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "code", ",", "*", "resp", ".", "Message", ")", "\n", "case", "412", ":", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "code", ",", "*", "resp", ".", "Message", ")", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// SetDashboard updates existing dashboard or creates a new one. // Set dasboard ID to nil to create a new dashboard. // Set overwrite to true if you want to overwrite existing dashboard with // newer version or with same dashboard title. // Grafana only can create or update a dashboard in a database. File dashboards // may be only loaded with HTTP API but not created or updated.
[ "SetDashboard", "updates", "existing", "dashboard", "or", "creates", "a", "new", "one", ".", "Set", "dasboard", "ID", "to", "nil", "to", "create", "a", "new", "dashboard", ".", "Set", "overwrite", "to", "true", "if", "you", "want", "to", "overwrite", "existing", "dashboard", "with", "newer", "version", "or", "with", "same", "dashboard", "title", ".", "Grafana", "only", "can", "create", "or", "update", "a", "dashboard", "in", "a", "database", ".", "File", "dashboards", "may", "be", "only", "loaded", "with", "HTTP", "API", "but", "not", "created", "or", "updated", "." ]
5158161510f07142e96b0c3d4be124b47fe2c070
https://github.com/grafana-tools/sdk/blob/5158161510f07142e96b0c3d4be124b47fe2c070/rest-dashboard.go#L159-L195
1,388
grafana-tools/sdk
rest-dashboard.go
DeleteDashboard
func (r *Client) DeleteDashboard(slug string) (StatusMessage, error) { var ( isBoardFromDB bool raw []byte reply StatusMessage err error ) if slug, isBoardFromDB = cleanPrefix(slug); !isBoardFromDB { return StatusMessage{}, errors.New("only database dashboards (with 'db/' prefix in a slug) can be removed") } if raw, _, err = r.delete(fmt.Sprintf("api/dashboards/db/%s", slug)); err != nil { return StatusMessage{}, err } err = json.Unmarshal(raw, &reply) return reply, err }
go
func (r *Client) DeleteDashboard(slug string) (StatusMessage, error) { var ( isBoardFromDB bool raw []byte reply StatusMessage err error ) if slug, isBoardFromDB = cleanPrefix(slug); !isBoardFromDB { return StatusMessage{}, errors.New("only database dashboards (with 'db/' prefix in a slug) can be removed") } if raw, _, err = r.delete(fmt.Sprintf("api/dashboards/db/%s", slug)); err != nil { return StatusMessage{}, err } err = json.Unmarshal(raw, &reply) return reply, err }
[ "func", "(", "r", "*", "Client", ")", "DeleteDashboard", "(", "slug", "string", ")", "(", "StatusMessage", ",", "error", ")", "{", "var", "(", "isBoardFromDB", "bool", "\n", "raw", "[", "]", "byte", "\n", "reply", "StatusMessage", "\n", "err", "error", "\n", ")", "\n", "if", "slug", ",", "isBoardFromDB", "=", "cleanPrefix", "(", "slug", ")", ";", "!", "isBoardFromDB", "{", "return", "StatusMessage", "{", "}", ",", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "}", "\n", "if", "raw", ",", "_", ",", "err", "=", "r", ".", "delete", "(", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "slug", ")", ")", ";", "err", "!=", "nil", "{", "return", "StatusMessage", "{", "}", ",", "err", "\n", "}", "\n", "err", "=", "json", ".", "Unmarshal", "(", "raw", ",", "&", "reply", ")", "\n", "return", "reply", ",", "err", "\n", "}" ]
// DeleteDashboard deletes dashboard that selected by slug string. // Grafana only can delete a dashboard in a database. File dashboards // may be only loaded with HTTP API but not deteled.
[ "DeleteDashboard", "deletes", "dashboard", "that", "selected", "by", "slug", "string", ".", "Grafana", "only", "can", "delete", "a", "dashboard", "in", "a", "database", ".", "File", "dashboards", "may", "be", "only", "loaded", "with", "HTTP", "API", "but", "not", "deteled", "." ]
5158161510f07142e96b0c3d4be124b47fe2c070
https://github.com/grafana-tools/sdk/blob/5158161510f07142e96b0c3d4be124b47fe2c070/rest-dashboard.go#L237-L252
1,389
grafana-tools/sdk
rest-dashboard.go
setPrefix
func setPrefix(slug string) (string, bool) { if strings.HasPrefix(slug, "db") { return slug, true } if strings.HasPrefix(slug, "file") { return slug, false } return fmt.Sprintf("db/%s", slug), true }
go
func setPrefix(slug string) (string, bool) { if strings.HasPrefix(slug, "db") { return slug, true } if strings.HasPrefix(slug, "file") { return slug, false } return fmt.Sprintf("db/%s", slug), true }
[ "func", "setPrefix", "(", "slug", "string", ")", "(", "string", ",", "bool", ")", "{", "if", "strings", ".", "HasPrefix", "(", "slug", ",", "\"", "\"", ")", "{", "return", "slug", ",", "true", "\n", "}", "\n", "if", "strings", ".", "HasPrefix", "(", "slug", ",", "\"", "\"", ")", "{", "return", "slug", ",", "false", "\n", "}", "\n", "return", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "slug", ")", ",", "true", "\n", "}" ]
// implicitly use dashboards from Grafana DB not from a file system
[ "implicitly", "use", "dashboards", "from", "Grafana", "DB", "not", "from", "a", "file", "system" ]
5158161510f07142e96b0c3d4be124b47fe2c070
https://github.com/grafana-tools/sdk/blob/5158161510f07142e96b0c3d4be124b47fe2c070/rest-dashboard.go#L255-L263
1,390
grafana-tools/sdk
custom-types.go
UnmarshalJSON
func (v *IntString) UnmarshalJSON(raw []byte) error { if raw == nil || bytes.Equal(raw, []byte(`"null"`)) || bytes.Equal(raw, []byte(`""`)) { return nil } strVal := string(raw) if rune(raw[0]) == '"' { strVal = strings.Trim(strVal, `"`) } i, err := strconv.ParseInt(strVal, 10, 64) if err != nil { return err } v.Value = i v.Valid = true return nil }
go
func (v *IntString) UnmarshalJSON(raw []byte) error { if raw == nil || bytes.Equal(raw, []byte(`"null"`)) || bytes.Equal(raw, []byte(`""`)) { return nil } strVal := string(raw) if rune(raw[0]) == '"' { strVal = strings.Trim(strVal, `"`) } i, err := strconv.ParseInt(strVal, 10, 64) if err != nil { return err } v.Value = i v.Valid = true return nil }
[ "func", "(", "v", "*", "IntString", ")", "UnmarshalJSON", "(", "raw", "[", "]", "byte", ")", "error", "{", "if", "raw", "==", "nil", "||", "bytes", ".", "Equal", "(", "raw", ",", "[", "]", "byte", "(", "`\"null\"`", ")", ")", "||", "bytes", ".", "Equal", "(", "raw", ",", "[", "]", "byte", "(", "`\"\"`", ")", ")", "{", "return", "nil", "\n", "}", "\n\n", "strVal", ":=", "string", "(", "raw", ")", "\n", "if", "rune", "(", "raw", "[", "0", "]", ")", "==", "'\"'", "{", "strVal", "=", "strings", ".", "Trim", "(", "strVal", ",", "`\"`", ")", "\n", "}", "\n\n", "i", ",", "err", ":=", "strconv", ".", "ParseInt", "(", "strVal", ",", "10", ",", "64", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "v", ".", "Value", "=", "i", "\n", "v", ".", "Valid", "=", "true", "\n\n", "return", "nil", "\n", "}" ]
// UnmarshalJSON implements custom unmarshalling for IntString type
[ "UnmarshalJSON", "implements", "custom", "unmarshalling", "for", "IntString", "type" ]
5158161510f07142e96b0c3d4be124b47fe2c070
https://github.com/grafana-tools/sdk/blob/5158161510f07142e96b0c3d4be124b47fe2c070/custom-types.go#L118-L137
1,391
grafana-tools/sdk
custom-types.go
MarshalJSON
func (v *IntString) MarshalJSON() ([]byte, error) { if v.Valid { strVal := strconv.FormatInt(v.Value, 10) return []byte(strVal), nil } return []byte(`"null"`), nil }
go
func (v *IntString) MarshalJSON() ([]byte, error) { if v.Valid { strVal := strconv.FormatInt(v.Value, 10) return []byte(strVal), nil } return []byte(`"null"`), nil }
[ "func", "(", "v", "*", "IntString", ")", "MarshalJSON", "(", ")", "(", "[", "]", "byte", ",", "error", ")", "{", "if", "v", ".", "Valid", "{", "strVal", ":=", "strconv", ".", "FormatInt", "(", "v", ".", "Value", ",", "10", ")", "\n", "return", "[", "]", "byte", "(", "strVal", ")", ",", "nil", "\n", "}", "\n\n", "return", "[", "]", "byte", "(", "`\"null\"`", ")", ",", "nil", "\n", "}" ]
// MarshalJSON implements custom marshalling for IntString type
[ "MarshalJSON", "implements", "custom", "marshalling", "for", "IntString", "type" ]
5158161510f07142e96b0c3d4be124b47fe2c070
https://github.com/grafana-tools/sdk/blob/5158161510f07142e96b0c3d4be124b47fe2c070/custom-types.go#L140-L147
1,392
grafana-tools/sdk
custom-types.go
MarshalJSON
func (v *FloatString) MarshalJSON() ([]byte, error) { if v.Valid { strVal := strconv.FormatFloat(v.Value, 'g', -1, 64) return []byte(strVal), nil } return []byte(`"null"`), nil }
go
func (v *FloatString) MarshalJSON() ([]byte, error) { if v.Valid { strVal := strconv.FormatFloat(v.Value, 'g', -1, 64) return []byte(strVal), nil } return []byte(`"null"`), nil }
[ "func", "(", "v", "*", "FloatString", ")", "MarshalJSON", "(", ")", "(", "[", "]", "byte", ",", "error", ")", "{", "if", "v", ".", "Valid", "{", "strVal", ":=", "strconv", ".", "FormatFloat", "(", "v", ".", "Value", ",", "'g'", ",", "-", "1", ",", "64", ")", "\n", "return", "[", "]", "byte", "(", "strVal", ")", ",", "nil", "\n", "}", "\n\n", "return", "[", "]", "byte", "(", "`\"null\"`", ")", ",", "nil", "\n", "}" ]
// MarshalJSON implements custom marshalling for FloatString type
[ "MarshalJSON", "implements", "custom", "marshalling", "for", "FloatString", "type" ]
5158161510f07142e96b0c3d4be124b47fe2c070
https://github.com/grafana-tools/sdk/blob/5158161510f07142e96b0c3d4be124b47fe2c070/custom-types.go#L185-L192
1,393
keybase/saltpack
armor62_verify.go
NewDearmor62VerifyStream
func NewDearmor62VerifyStream(versionValidator VersionValidator, r io.Reader, keyring SigKeyring) (skey SigningPublicKey, vs io.Reader, brand string, err error) { dearmored, frame, err := NewArmor62DecoderStream(r, armor62SignatureHeaderChecker, armor62SignatureFrameChecker) if err != nil { return nil, nil, "", err } skey, vs, err = NewVerifyStream(versionValidator, dearmored, keyring) if err != nil { return nil, nil, "", err } if brand, err = frame.GetBrand(); err != nil { return nil, nil, "", err } return skey, vs, brand, nil }
go
func NewDearmor62VerifyStream(versionValidator VersionValidator, r io.Reader, keyring SigKeyring) (skey SigningPublicKey, vs io.Reader, brand string, err error) { dearmored, frame, err := NewArmor62DecoderStream(r, armor62SignatureHeaderChecker, armor62SignatureFrameChecker) if err != nil { return nil, nil, "", err } skey, vs, err = NewVerifyStream(versionValidator, dearmored, keyring) if err != nil { return nil, nil, "", err } if brand, err = frame.GetBrand(); err != nil { return nil, nil, "", err } return skey, vs, brand, nil }
[ "func", "NewDearmor62VerifyStream", "(", "versionValidator", "VersionValidator", ",", "r", "io", ".", "Reader", ",", "keyring", "SigKeyring", ")", "(", "skey", "SigningPublicKey", ",", "vs", "io", ".", "Reader", ",", "brand", "string", ",", "err", "error", ")", "{", "dearmored", ",", "frame", ",", "err", ":=", "NewArmor62DecoderStream", "(", "r", ",", "armor62SignatureHeaderChecker", ",", "armor62SignatureFrameChecker", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "nil", ",", "\"", "\"", ",", "err", "\n", "}", "\n", "skey", ",", "vs", ",", "err", "=", "NewVerifyStream", "(", "versionValidator", ",", "dearmored", ",", "keyring", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "nil", ",", "\"", "\"", ",", "err", "\n", "}", "\n", "if", "brand", ",", "err", "=", "frame", ".", "GetBrand", "(", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "nil", ",", "\"", "\"", ",", "err", "\n", "}", "\n", "return", "skey", ",", "vs", ",", "brand", ",", "nil", "\n", "}" ]
// NewDearmor62VerifyStream creates a stream that consumes data from reader // r. It returns the signer's public key and a reader that only // contains verified data. If the signer's key is not in keyring, // it will return an error. It expects the data it reads from r to // be armor62-encoded.
[ "NewDearmor62VerifyStream", "creates", "a", "stream", "that", "consumes", "data", "from", "reader", "r", ".", "It", "returns", "the", "signer", "s", "public", "key", "and", "a", "reader", "that", "only", "contains", "verified", "data", ".", "If", "the", "signer", "s", "key", "is", "not", "in", "keyring", "it", "will", "return", "an", "error", ".", "It", "expects", "the", "data", "it", "reads", "from", "r", "to", "be", "armor62", "-", "encoded", "." ]
0ac0b421a59b0473d103cc659cb8508e946a5f13
https://github.com/keybase/saltpack/blob/0ac0b421a59b0473d103cc659cb8508e946a5f13/armor62_verify.go#L32-L45
1,394
keybase/saltpack
armor62_verify.go
Dearmor62Verify
func Dearmor62Verify(versionValidator VersionValidator, signedMsg string, keyring SigKeyring) (skey SigningPublicKey, verifiedMsg []byte, brand string, err error) { skey, stream, brand, err := NewDearmor62VerifyStream(versionValidator, bytes.NewBufferString(signedMsg), keyring) if err != nil { return nil, nil, "", err } verifiedMsg, err = ioutil.ReadAll(stream) if err != nil { return nil, nil, "", err } return skey, verifiedMsg, brand, nil }
go
func Dearmor62Verify(versionValidator VersionValidator, signedMsg string, keyring SigKeyring) (skey SigningPublicKey, verifiedMsg []byte, brand string, err error) { skey, stream, brand, err := NewDearmor62VerifyStream(versionValidator, bytes.NewBufferString(signedMsg), keyring) if err != nil { return nil, nil, "", err } verifiedMsg, err = ioutil.ReadAll(stream) if err != nil { return nil, nil, "", err } return skey, verifiedMsg, brand, nil }
[ "func", "Dearmor62Verify", "(", "versionValidator", "VersionValidator", ",", "signedMsg", "string", ",", "keyring", "SigKeyring", ")", "(", "skey", "SigningPublicKey", ",", "verifiedMsg", "[", "]", "byte", ",", "brand", "string", ",", "err", "error", ")", "{", "skey", ",", "stream", ",", "brand", ",", "err", ":=", "NewDearmor62VerifyStream", "(", "versionValidator", ",", "bytes", ".", "NewBufferString", "(", "signedMsg", ")", ",", "keyring", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "nil", ",", "\"", "\"", ",", "err", "\n", "}", "\n\n", "verifiedMsg", ",", "err", "=", "ioutil", ".", "ReadAll", "(", "stream", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "nil", ",", "\"", "\"", ",", "err", "\n", "}", "\n\n", "return", "skey", ",", "verifiedMsg", ",", "brand", ",", "nil", "\n", "}" ]
// Dearmor62Verify checks the signature in signedMsg. It returns the // signer's public key and a verified message. It expects // signedMsg to be armor62-encoded.
[ "Dearmor62Verify", "checks", "the", "signature", "in", "signedMsg", ".", "It", "returns", "the", "signer", "s", "public", "key", "and", "a", "verified", "message", ".", "It", "expects", "signedMsg", "to", "be", "armor62", "-", "encoded", "." ]
0ac0b421a59b0473d103cc659cb8508e946a5f13
https://github.com/keybase/saltpack/blob/0ac0b421a59b0473d103cc659cb8508e946a5f13/armor62_verify.go#L50-L62
1,395
keybase/saltpack
armor62_verify.go
Dearmor62VerifyDetachedReader
func Dearmor62VerifyDetachedReader(versionValidator VersionValidator, r io.Reader, signature string, keyring SigKeyring) (skey SigningPublicKey, brand string, err error) { dearmored, brand, _, _, err := Armor62OpenWithValidation(signature, armor62DetachedSignatureHeaderChecker, armor62DetachedSignatureFrameChecker) if err != nil { return nil, "", err } skey, err = VerifyDetachedReader(versionValidator, r, dearmored, keyring) return skey, brand, err }
go
func Dearmor62VerifyDetachedReader(versionValidator VersionValidator, r io.Reader, signature string, keyring SigKeyring) (skey SigningPublicKey, brand string, err error) { dearmored, brand, _, _, err := Armor62OpenWithValidation(signature, armor62DetachedSignatureHeaderChecker, armor62DetachedSignatureFrameChecker) if err != nil { return nil, "", err } skey, err = VerifyDetachedReader(versionValidator, r, dearmored, keyring) return skey, brand, err }
[ "func", "Dearmor62VerifyDetachedReader", "(", "versionValidator", "VersionValidator", ",", "r", "io", ".", "Reader", ",", "signature", "string", ",", "keyring", "SigKeyring", ")", "(", "skey", "SigningPublicKey", ",", "brand", "string", ",", "err", "error", ")", "{", "dearmored", ",", "brand", ",", "_", ",", "_", ",", "err", ":=", "Armor62OpenWithValidation", "(", "signature", ",", "armor62DetachedSignatureHeaderChecker", ",", "armor62DetachedSignatureFrameChecker", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "\"", "\"", ",", "err", "\n", "}", "\n", "skey", ",", "err", "=", "VerifyDetachedReader", "(", "versionValidator", ",", "r", ",", "dearmored", ",", "keyring", ")", "\n", "return", "skey", ",", "brand", ",", "err", "\n", "}" ]
// Dearmor62VerifyDetachedReader verifies that signature is a valid // armor62-encoded signature for entire message read from Reader, // and that the public key for the signer is in keyring. It returns // the signer's public key.
[ "Dearmor62VerifyDetachedReader", "verifies", "that", "signature", "is", "a", "valid", "armor62", "-", "encoded", "signature", "for", "entire", "message", "read", "from", "Reader", "and", "that", "the", "public", "key", "for", "the", "signer", "is", "in", "keyring", ".", "It", "returns", "the", "signer", "s", "public", "key", "." ]
0ac0b421a59b0473d103cc659cb8508e946a5f13
https://github.com/keybase/saltpack/blob/0ac0b421a59b0473d103cc659cb8508e946a5f13/armor62_verify.go#L68-L75
1,396
keybase/saltpack
armor62_verify.go
Dearmor62VerifyDetached
func Dearmor62VerifyDetached(versionValidator VersionValidator, message []byte, signature string, keyring SigKeyring) (skey SigningPublicKey, brand string, err error) { return Dearmor62VerifyDetachedReader(versionValidator, bytes.NewReader(message), signature, keyring) }
go
func Dearmor62VerifyDetached(versionValidator VersionValidator, message []byte, signature string, keyring SigKeyring) (skey SigningPublicKey, brand string, err error) { return Dearmor62VerifyDetachedReader(versionValidator, bytes.NewReader(message), signature, keyring) }
[ "func", "Dearmor62VerifyDetached", "(", "versionValidator", "VersionValidator", ",", "message", "[", "]", "byte", ",", "signature", "string", ",", "keyring", "SigKeyring", ")", "(", "skey", "SigningPublicKey", ",", "brand", "string", ",", "err", "error", ")", "{", "return", "Dearmor62VerifyDetachedReader", "(", "versionValidator", ",", "bytes", ".", "NewReader", "(", "message", ")", ",", "signature", ",", "keyring", ")", "\n", "}" ]
// Dearmor62VerifyDetached verifies that signature is a valid // armor62-encoded signature for message, and that the public key // for the signer is in keyring. It returns the signer's public key.
[ "Dearmor62VerifyDetached", "verifies", "that", "signature", "is", "a", "valid", "armor62", "-", "encoded", "signature", "for", "message", "and", "that", "the", "public", "key", "for", "the", "signer", "is", "in", "keyring", ".", "It", "returns", "the", "signer", "s", "public", "key", "." ]
0ac0b421a59b0473d103cc659cb8508e946a5f13
https://github.com/keybase/saltpack/blob/0ac0b421a59b0473d103cc659cb8508e946a5f13/armor62_verify.go#L80-L82
1,397
keybase/saltpack
signcrypt_seal.go
init
func (sss *signcryptSealStream) init( receiverBoxKeys []BoxPublicKey, receiverSymmetricKeys []ReceiverSymmetricKey, ephemeralKeyCreator EphemeralKeyCreator, rng signcryptRNG) error { if err := checkSigncryptReceivers(receiverBoxKeys, receiverSymmetricKeys); err != nil { return err } receivers, err := rng.shuffleReceivers(receiverBoxKeys, receiverSymmetricKeys) if err != nil { return err } ephemeralKey, err := ephemeralKeyCreator.CreateEphemeralKey() if err != nil { return err } eh := SigncryptionHeader{ FormatName: FormatName, Version: sss.version, Type: MessageTypeSigncryption, Ephemeral: ephemeralKey.GetPublicKey().ToKID(), } encryptionKey, err := rng.createSymmetricKey() if err != nil { return err } sss.encryptionKey = *encryptionKey // Prepare the secretbox that contains the sender's public key. If the // sender is anonymous, use an all-zeros key, so that the anonymity bit // doesn't leak out. nonce := nonceForSenderKeySecretBox() if sss.signingKey == nil { // anonymous sender mode, all zeros eh.SenderSecretbox = secretbox.Seal([]byte{}, make([]byte, ed25519.PublicKeySize), (*[24]byte)(&nonce), (*[32]byte)(&sss.encryptionKey)) } else { // regular sender mode, an actual key signingPublicKeyBytes := sss.signingKey.GetPublicKey().ToKID() if len(signingPublicKeyBytes) != ed25519.PublicKeySize { panic("unexpected signing key length, anonymity bit will leak") } eh.SenderSecretbox = secretbox.Seal([]byte{}, sss.signingKey.GetPublicKey().ToKID(), (*[24]byte)(&nonce), (*[32]byte)(&sss.encryptionKey)) } // Collect all the recipient identifiers, and encrypt the payload key for // all of them. for i, r := range receivers { eh.Receivers = append(eh.Receivers, r.makeReceiverKeys(ephemeralKey, sss.encryptionKey, uint64(i))) } // Encode the header to bytes, hash it, then double encode it. headerBytes, err := encodeToBytes(eh) if err != nil { return err } sss.headerHash = sha512.Sum512(headerBytes) err = sss.encoder.Encode(headerBytes) if err != nil { return err } return nil }
go
func (sss *signcryptSealStream) init( receiverBoxKeys []BoxPublicKey, receiverSymmetricKeys []ReceiverSymmetricKey, ephemeralKeyCreator EphemeralKeyCreator, rng signcryptRNG) error { if err := checkSigncryptReceivers(receiverBoxKeys, receiverSymmetricKeys); err != nil { return err } receivers, err := rng.shuffleReceivers(receiverBoxKeys, receiverSymmetricKeys) if err != nil { return err } ephemeralKey, err := ephemeralKeyCreator.CreateEphemeralKey() if err != nil { return err } eh := SigncryptionHeader{ FormatName: FormatName, Version: sss.version, Type: MessageTypeSigncryption, Ephemeral: ephemeralKey.GetPublicKey().ToKID(), } encryptionKey, err := rng.createSymmetricKey() if err != nil { return err } sss.encryptionKey = *encryptionKey // Prepare the secretbox that contains the sender's public key. If the // sender is anonymous, use an all-zeros key, so that the anonymity bit // doesn't leak out. nonce := nonceForSenderKeySecretBox() if sss.signingKey == nil { // anonymous sender mode, all zeros eh.SenderSecretbox = secretbox.Seal([]byte{}, make([]byte, ed25519.PublicKeySize), (*[24]byte)(&nonce), (*[32]byte)(&sss.encryptionKey)) } else { // regular sender mode, an actual key signingPublicKeyBytes := sss.signingKey.GetPublicKey().ToKID() if len(signingPublicKeyBytes) != ed25519.PublicKeySize { panic("unexpected signing key length, anonymity bit will leak") } eh.SenderSecretbox = secretbox.Seal([]byte{}, sss.signingKey.GetPublicKey().ToKID(), (*[24]byte)(&nonce), (*[32]byte)(&sss.encryptionKey)) } // Collect all the recipient identifiers, and encrypt the payload key for // all of them. for i, r := range receivers { eh.Receivers = append(eh.Receivers, r.makeReceiverKeys(ephemeralKey, sss.encryptionKey, uint64(i))) } // Encode the header to bytes, hash it, then double encode it. headerBytes, err := encodeToBytes(eh) if err != nil { return err } sss.headerHash = sha512.Sum512(headerBytes) err = sss.encoder.Encode(headerBytes) if err != nil { return err } return nil }
[ "func", "(", "sss", "*", "signcryptSealStream", ")", "init", "(", "receiverBoxKeys", "[", "]", "BoxPublicKey", ",", "receiverSymmetricKeys", "[", "]", "ReceiverSymmetricKey", ",", "ephemeralKeyCreator", "EphemeralKeyCreator", ",", "rng", "signcryptRNG", ")", "error", "{", "if", "err", ":=", "checkSigncryptReceivers", "(", "receiverBoxKeys", ",", "receiverSymmetricKeys", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "receivers", ",", "err", ":=", "rng", ".", "shuffleReceivers", "(", "receiverBoxKeys", ",", "receiverSymmetricKeys", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "ephemeralKey", ",", "err", ":=", "ephemeralKeyCreator", ".", "CreateEphemeralKey", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "eh", ":=", "SigncryptionHeader", "{", "FormatName", ":", "FormatName", ",", "Version", ":", "sss", ".", "version", ",", "Type", ":", "MessageTypeSigncryption", ",", "Ephemeral", ":", "ephemeralKey", ".", "GetPublicKey", "(", ")", ".", "ToKID", "(", ")", ",", "}", "\n", "encryptionKey", ",", "err", ":=", "rng", ".", "createSymmetricKey", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "sss", ".", "encryptionKey", "=", "*", "encryptionKey", "\n\n", "// Prepare the secretbox that contains the sender's public key. If the", "// sender is anonymous, use an all-zeros key, so that the anonymity bit", "// doesn't leak out.", "nonce", ":=", "nonceForSenderKeySecretBox", "(", ")", "\n", "if", "sss", ".", "signingKey", "==", "nil", "{", "// anonymous sender mode, all zeros", "eh", ".", "SenderSecretbox", "=", "secretbox", ".", "Seal", "(", "[", "]", "byte", "{", "}", ",", "make", "(", "[", "]", "byte", ",", "ed25519", ".", "PublicKeySize", ")", ",", "(", "*", "[", "24", "]", "byte", ")", "(", "&", "nonce", ")", ",", "(", "*", "[", "32", "]", "byte", ")", "(", "&", "sss", ".", "encryptionKey", ")", ")", "\n", "}", "else", "{", "// regular sender mode, an actual key", "signingPublicKeyBytes", ":=", "sss", ".", "signingKey", ".", "GetPublicKey", "(", ")", ".", "ToKID", "(", ")", "\n", "if", "len", "(", "signingPublicKeyBytes", ")", "!=", "ed25519", ".", "PublicKeySize", "{", "panic", "(", "\"", "\"", ")", "\n", "}", "\n", "eh", ".", "SenderSecretbox", "=", "secretbox", ".", "Seal", "(", "[", "]", "byte", "{", "}", ",", "sss", ".", "signingKey", ".", "GetPublicKey", "(", ")", ".", "ToKID", "(", ")", ",", "(", "*", "[", "24", "]", "byte", ")", "(", "&", "nonce", ")", ",", "(", "*", "[", "32", "]", "byte", ")", "(", "&", "sss", ".", "encryptionKey", ")", ")", "\n", "}", "\n\n", "// Collect all the recipient identifiers, and encrypt the payload key for", "// all of them.", "for", "i", ",", "r", ":=", "range", "receivers", "{", "eh", ".", "Receivers", "=", "append", "(", "eh", ".", "Receivers", ",", "r", ".", "makeReceiverKeys", "(", "ephemeralKey", ",", "sss", ".", "encryptionKey", ",", "uint64", "(", "i", ")", ")", ")", "\n", "}", "\n\n", "// Encode the header to bytes, hash it, then double encode it.", "headerBytes", ",", "err", ":=", "encodeToBytes", "(", "eh", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "sss", ".", "headerHash", "=", "sha512", ".", "Sum512", "(", "headerBytes", ")", "\n", "err", "=", "sss", ".", "encoder", ".", "Encode", "(", "headerBytes", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "return", "nil", "\n", "}" ]
// This generates the payload key, and encrypts it for all the different // recipients of the two different types. Symmetric key recipients and DH key // recipients use different types of identifiers, but they are the same length, // and should both be indistinguishable from random noise.
[ "This", "generates", "the", "payload", "key", "and", "encrypts", "it", "for", "all", "the", "different", "recipients", "of", "the", "two", "different", "types", ".", "Symmetric", "key", "recipients", "and", "DH", "key", "recipients", "use", "different", "types", "of", "identifiers", "but", "they", "are", "the", "same", "length", "and", "should", "both", "be", "indistinguishable", "from", "random", "noise", "." ]
0ac0b421a59b0473d103cc659cb8508e946a5f13
https://github.com/keybase/saltpack/blob/0ac0b421a59b0473d103cc659cb8508e946a5f13/signcrypt_seal.go#L286-L349
1,398
keybase/saltpack
signcrypt_seal.go
NewSigncryptSealStream
func NewSigncryptSealStream(ciphertext io.Writer, ephemeralKeyCreator EphemeralKeyCreator, sender SigningSecretKey, receiverBoxKeys []BoxPublicKey, receiverSymmetricKeys []ReceiverSymmetricKey) (io.WriteCloser, error) { return newSigncryptSealStream(ciphertext, sender, receiverBoxKeys, receiverSymmetricKeys, ephemeralKeyCreator, defaultSigncryptRNG{}) }
go
func NewSigncryptSealStream(ciphertext io.Writer, ephemeralKeyCreator EphemeralKeyCreator, sender SigningSecretKey, receiverBoxKeys []BoxPublicKey, receiverSymmetricKeys []ReceiverSymmetricKey) (io.WriteCloser, error) { return newSigncryptSealStream(ciphertext, sender, receiverBoxKeys, receiverSymmetricKeys, ephemeralKeyCreator, defaultSigncryptRNG{}) }
[ "func", "NewSigncryptSealStream", "(", "ciphertext", "io", ".", "Writer", ",", "ephemeralKeyCreator", "EphemeralKeyCreator", ",", "sender", "SigningSecretKey", ",", "receiverBoxKeys", "[", "]", "BoxPublicKey", ",", "receiverSymmetricKeys", "[", "]", "ReceiverSymmetricKey", ")", "(", "io", ".", "WriteCloser", ",", "error", ")", "{", "return", "newSigncryptSealStream", "(", "ciphertext", ",", "sender", ",", "receiverBoxKeys", ",", "receiverSymmetricKeys", ",", "ephemeralKeyCreator", ",", "defaultSigncryptRNG", "{", "}", ")", "\n", "}" ]
// NewSigncryptSealStream creates a stream that consumes plaintext data. It // will write out signed and encrypted data to the io.Writer passed in as // ciphertext. The encryption is from the specified sender, and is encrypted // for the given receivers. // // ephemeralKeyCreator should be the last argument; it's the 2nd one // to preserve the public API. // // If initialization succeeds, returns an io.WriteCloser that accepts // plaintext data to be encrypted and a nil error. Otherwise, returns // nil and the initialization error.
[ "NewSigncryptSealStream", "creates", "a", "stream", "that", "consumes", "plaintext", "data", ".", "It", "will", "write", "out", "signed", "and", "encrypted", "data", "to", "the", "io", ".", "Writer", "passed", "in", "as", "ciphertext", ".", "The", "encryption", "is", "from", "the", "specified", "sender", "and", "is", "encrypted", "for", "the", "given", "receivers", ".", "ephemeralKeyCreator", "should", "be", "the", "last", "argument", ";", "it", "s", "the", "2nd", "one", "to", "preserve", "the", "public", "API", ".", "If", "initialization", "succeeds", "returns", "an", "io", ".", "WriteCloser", "that", "accepts", "plaintext", "data", "to", "be", "encrypted", "and", "a", "nil", "error", ".", "Otherwise", "returns", "nil", "and", "the", "initialization", "error", "." ]
0ac0b421a59b0473d103cc659cb8508e946a5f13
https://github.com/keybase/saltpack/blob/0ac0b421a59b0473d103cc659cb8508e946a5f13/signcrypt_seal.go#L399-L401
1,399
keybase/saltpack
signcrypt_seal.go
SigncryptSeal
func SigncryptSeal(plaintext []byte, ephemeralKeyCreator EphemeralKeyCreator, sender SigningSecretKey, receiverBoxKeys []BoxPublicKey, receiverSymmetricKeys []ReceiverSymmetricKey) (out []byte, err error) { return signcryptSeal(plaintext, sender, receiverBoxKeys, receiverSymmetricKeys, ephemeralKeyCreator, defaultSigncryptRNG{}) }
go
func SigncryptSeal(plaintext []byte, ephemeralKeyCreator EphemeralKeyCreator, sender SigningSecretKey, receiverBoxKeys []BoxPublicKey, receiverSymmetricKeys []ReceiverSymmetricKey) (out []byte, err error) { return signcryptSeal(plaintext, sender, receiverBoxKeys, receiverSymmetricKeys, ephemeralKeyCreator, defaultSigncryptRNG{}) }
[ "func", "SigncryptSeal", "(", "plaintext", "[", "]", "byte", ",", "ephemeralKeyCreator", "EphemeralKeyCreator", ",", "sender", "SigningSecretKey", ",", "receiverBoxKeys", "[", "]", "BoxPublicKey", ",", "receiverSymmetricKeys", "[", "]", "ReceiverSymmetricKey", ")", "(", "out", "[", "]", "byte", ",", "err", "error", ")", "{", "return", "signcryptSeal", "(", "plaintext", ",", "sender", ",", "receiverBoxKeys", ",", "receiverSymmetricKeys", ",", "ephemeralKeyCreator", ",", "defaultSigncryptRNG", "{", "}", ")", "\n", "}" ]
// SigncryptSeal a plaintext from the given sender, for the specified // receiver groups. Returns a ciphertext, or an error if something // bad happened. // // ephemeralKeyCreator should be the last argument; it's the 2nd one // to preserve the public API.
[ "SigncryptSeal", "a", "plaintext", "from", "the", "given", "sender", "for", "the", "specified", "receiver", "groups", ".", "Returns", "a", "ciphertext", "or", "an", "error", "if", "something", "bad", "happened", ".", "ephemeralKeyCreator", "should", "be", "the", "last", "argument", ";", "it", "s", "the", "2nd", "one", "to", "preserve", "the", "public", "API", "." ]
0ac0b421a59b0473d103cc659cb8508e946a5f13
https://github.com/keybase/saltpack/blob/0ac0b421a59b0473d103cc659cb8508e946a5f13/signcrypt_seal.go#L424-L426