Code Monkey home page Code Monkey logo

holster's Introduction

Holster

A place to holster mailgun's golang libraries and tools

Installation

To use, run the following command:

go get github.com/mailgun/holster/v4

Clock

A drop in (almost) replacement for the system time package to make scheduled events deterministic in tests. See the clock readme for details

HttpSign

HttpSign is a library for signing and authenticating HTTP requests between web services. See the httpsign readme for details

Distributed Election

A distributed election implementation using etcd to coordinate elections See the etcd v3 readme for details

Errors

Errors is a fork of https://github.com/pkg/errors with additional functions for improving the relationship between structured logging and error handling in go See the errors readme for details

WaitGroup

Waitgroup is a simplification of sync.Waitgroup with item and error collection included.

Running many short term routines over a collection with .Run()

import "github.com/mailgun/holster/v4/syncutils"
var wg syncutils.WaitGroup
for _, item := range items {
    wg.Run(func(item interface{}) error {
        // Do some long running thing with the item
        fmt.Printf("Item: %+v\n", item.(MyItem))
        return nil
    }, item)
}
errs := wg.Wait()
if errs != nil {
    fmt.Printf("Errs: %+v\n", errs)
}

Clean up long running routines easily with .Loop()

import "github.com/mailgun/holster/v4/syncutils"
pipe := make(chan int32, 0)
var wg syncutils.WaitGroup
var count int32

wg.Loop(func() bool {
    select {
    case inc, ok := <-pipe:
        // If the pipe was closed, return false
        if !ok {
            return false
        }
        atomic.AddInt32(&count, inc)
    }
    return true
})

// Feed the loop some numbers and close the pipe
pipe <- 1
pipe <- 5
pipe <- 10
close(pipe)

// Wait for the loop to exit
wg.Wait()

Loop .Until() .Stop() is called

import "github.com/mailgun/holster/v4/syncutils"
var wg syncutils.WaitGroup

wg.Until(func(done chan struct{}) bool {
    select {
    case <- time.Tick(time.Second):
        // Do some periodic thing
    case <- done:
        return false
    }
    return true
})

// Close the done channel and wait for the routine to exit
wg.Stop()

FanOut

FanOut spawns a new go-routine each time .Run() is called until size is reached, subsequent calls to .Run() will block until previously .Run() routines have completed. Allowing the user to control how many routines will run simultaneously. .Wait() then collects any errors from the routines once they have all completed. FanOut allows you to control how many goroutines spawn at a time while WaitGroup will not.

import "github.com/mailgun/holster/v4/syncutils"
// Insert records into the database 10 at a time
fanOut := syncutils.NewFanOut(10)
for _, item := range items {
    fanOut.Run(func(cast interface{}) error {
        item := cast.(Item)
        return db.ExecuteQuery("insert into tbl (id, field) values (?, ?)",
            item.Id, item.Field)
    }, item)
}

// Collect errors
errs := fanOut.Wait()
if errs != nil {
    // do something with errs
}

LRUCache

Implements a Least Recently Used Cache with optional TTL and stats collection

This is a LRU cache based off github.com/golang/groupcache/lru expanded with the following

  • Peek() - Get the value without updating the expiration or last used or stats
  • Keys() - Get a list of keys at this point in time
  • Stats() - Returns stats about the current state of the cache
  • AddWithTTL() - Adds a value to the cache with a expiration time
  • Each() - Concurrent non blocking access to each item in the cache
  • Map() - Efficient blocking modification to each item in the cache

TTL is evaluated during calls to .Get() if the entry is past the requested TTL .Get() removes the entry from the cache counts a miss and returns not ok

import "github.com/mailgun/holster/v4/collections"
cache := collections.NewLRUCache(5000)
go func() {
    for {
        select {
        // Send cache stats every 5 seconds
        case <-time.Tick(time.Second * 5):
            stats := cache.GetStats()
            metrics.Gauge(metrics.Metric("demo", "cache", "size"), int64(stats.Size), 1)
            metrics.Gauge(metrics.Metric("demo", "cache", "hit"), stats.Hit, 1)
            metrics.Gauge(metrics.Metric("demo", "cache", "miss"), stats.Miss, 1)
        }
    }
}()

cache.Add("key", "value")
value, ok := cache.Get("key")

for _, key := range cache.Keys() {
    value, ok := cache.Get(key)
    if ok {
        fmt.Printf("Key: %+v Value %+v\n", key, value)
    }
}

ExpireCache

ExpireCache is a cache which expires entries only after 2 conditions are met

  1. The Specified TTL has expired
  2. The item has been processed with ExpireCache.Each()

This is an unbounded cache which guaranties each item in the cache has been processed before removal. This cache is useful if you need an unbounded queue, that can also act like an LRU cache.

Every time an item is touched by .Get() or .Set() the duration is updated which ensures items in frequent use stay in the cache. Processing the cache with .Each() can modify the item in the cache without updating the expiration time by using the .Update() method.

The cache can also return statistics which can be used to graph cache usage and size.

NOTE: Because this is an unbounded cache, the user MUST process the cache with .Each() regularly! Else the cache items will never expire and the cache will eventually eat all the memory on the system

import "github.com/mailgun/holster/v4/collections"
// How often the cache is processed
syncInterval := time.Second * 10

// In this example the cache TTL is slightly less than the sync interval
// such that before the first sync; items that where only accessed once
// between sync intervals should expire. This technique is useful if you
// have a long syncInterval and are only interested in keeping items
// that where accessed during the sync cycle
cache := collections.NewExpireCache((syncInterval / 5) * 4)

go func() {
    for {
        select {
        // Sync the cache with the database every 10 seconds
        // Items in the cache will not be expired until this completes without error
        case <-time.Tick(syncInterval):
            // Each() uses FanOut() to run several of these concurrently, in this
            // example we are capped at running 10 concurrently, Use 0 or 1 if you
            // don't need concurrent FanOut
            cache.Each(10, func(key interface{}, value interface{}) error {
                item := value.(Item)
                return db.ExecuteQuery("insert into tbl (id, field) values (?, ?)",
                    item.Id, item.Field)
            })
        // Periodically send stats about the cache
        case <-time.Tick(time.Second * 5):
            stats := cache.GetStats()
            metrics.Gauge(metrics.Metric("demo", "cache", "size"), int64(stats.Size), 1)
            metrics.Gauge(metrics.Metric("demo", "cache", "hit"), stats.Hit, 1)
            metrics.Gauge(metrics.Metric("demo", "cache", "miss"), stats.Miss, 1)
        }
    }
}()

cache.Add("domain-id", Item{Id: 1, Field: "value"},
item, ok := cache.Get("domain-id")
if ok {
    fmt.Printf("%+v\n", item.(Item))
}

TTLMap

Provides a threadsafe time to live map useful for holding a bounded set of key'd values that can expire before being accessed. The expiration of values is calculated when the value is accessed or the map capacity has been reached.

import "github.com/mailgun/holster/v4/collections"
ttlMap := collections.NewTTLMap(10)
clock.Freeze(time.Now())

// Set a value that expires in 5 seconds
ttlMap.Set("one", "one", 5)

// Set a value that expires in 10 seconds
ttlMap.Set("two", "twp", 10)

// Simulate sleeping for 6 seconds
clock.Sleep(time.Second * 6)

// Retrieve the expired value and un-expired value
_, ok1 := ttlMap.Get("one")
_, ok2 := ttlMap.Get("two")

fmt.Printf("value one exists: %t\n", ok1)
fmt.Printf("value two exists: %t\n", ok2)

// Output: value one exists: false
// value two exists: true

Default values

These functions assist in determining if values are the golang default and if so, set a value

import "github.com/mailgun/holster/v4/setter"
var value string

// Returns true if 'value' is zero (the default golang value)
setter.IsZero(value)

// Returns true if 'value' is zero (the default golang value)
setter.IsZeroValue(reflect.ValueOf(value))

// If 'dest' is empty or of zero value, assign the default value.
// This panics if the value is not a pointer or if value and
// default value are not of the same type.
var config struct {
    Foo string
    Bar int
}
setter.SetDefault(&config.Foo, "default")
setter.SetDefault(&config.Bar, 200)

// Supply additional default values and SetDefault will
// choose the first default that is not of zero value
setter.SetDefault(&config.Foo, os.Getenv("FOO"), "default")

// Use 'SetOverride() to assign the first value that is not empty or of zero
// value.  The following will override the config file if 'foo' is provided via
// the cli or defined in the environment.

loadFromFile(&config)
argFoo = flag.String("foo", "", "foo via cli arg")

setter.SetOverride(&config.Foo, *argFoo, os.Env("FOO"))

Check for Nil interface

func NewImplementation() MyInterface {
    // Type and Value are not nil
    var p *MyImplementation = nil
    return p
}

thing := NewImplementation()
assert.False(t, thing == nil)
assert.True(t, setter.IsNil(thing))
assert.False(t, setter.IsNil(&MyImplementation{}))

GetEnv

Get a value from an environment variable or return the provided default

import "github.com/mailgun/holster/v4/config"

var conf = sandra.CassandraConfig{
   Nodes:    []string{config.GetEnv("CASSANDRA_ENDPOINT", "127.0.0.1:9042")},
   Keyspace: "test",
}

Random Things

A set of functions to generate random domain names and strings useful for testing

// Return a random string 10 characters long made up of runes passed
util.RandomRunes("prefix-", 10, util.AlphaRunes, holster.NumericRunes)

// Return a random string 10 characters long made up of Alpha Characters A-Z, a-z
util.RandomAlpha("prefix-", 10)

// Return a random string 10 characters long made up of Alpha and Numeric Characters A-Z, a-z, 0-9
util.RandomString("prefix-", 10)

// Return a random item from the list given
util.RandomItem("foo", "bar", "fee", "bee")

// Return a random domain name in the form "random-numbers.[gov, net, com, ..]"
util.RandomDomainName()

GoRoutine ID

Get the go routine id (useful for logging)

import "github.com/mailgun/holster/v4/callstack"
logrus.Infof("[%d] Info about this go routine", stack.GoRoutineID())

ContainsString

Checks if a given slice of strings contains the provided string. If a modifier func is provided, it is called with the slice item before the comparation.

import "github.com/mailgun/holster/v4/slice"

haystack := []string{"one", "Two", "Three"}
slice.ContainsString("two", haystack, strings.ToLower) // true
slice.ContainsString("two", haystack, nil) // false

Priority Queue

Provides a Priority Queue implementation as described here

import "github.com/mailgun/holster/v4/collections"
queue := collections.NewPriorityQueue()

queue.Push(&collections.PQItem{
    Value: "thing3",
    Priority: 3,
})

queue.Push(&collections.PQItem{
    Value: "thing1",
    Priority: 1,
})

queue.Push(&collections.PQItem{
    Value: "thing2",
    Priority: 2,
})

// Pops item off the queue according to the priority instead of the Push() order
item := queue.Pop()

fmt.Printf("Item: %s", item.Value.(string))

// Output: Item: thing1

Broadcaster

Allow the user to notify multiple goroutines of an event. This implementation guarantees every goroutine will wake for every broadcast sent. In the event the goroutine falls behind and more broadcasts() are sent than the goroutine has handled the broadcasts are buffered up to 10,000 broadcasts. Once the broadcast buffer limit is reached calls to broadcast() will block until goroutines consuming the broadcasts can catch up.

import "github.com/mailgun/holster/v4/syncutil"
    broadcaster := syncutil.NewBroadcaster()
    done := make(chan struct{})
    var mutex sync.Mutex
    var chat []string

    // Start some simple chat clients that are responsible for
    // sending the contents of the []chat slice to their clients
    for i := 0; i < 2; i++ {
        go func(idx int) {
            var clientIndex int
            for {
                mutex.Lock()
                if clientIndex != len(chat) {
                    // Pretend we are sending a message to our client via a socket
                    fmt.Printf("Client [%d] Chat: %s\n", idx, chat[clientIndex])
                    clientIndex++
                    mutex.Unlock()
                    continue
                }
                mutex.Unlock()

                // Wait for more chats to be added to chat[]
                select {
                case <-broadcaster.WaitChan(string(idx)):
                case <-done:
                    return
                }
            }
        }(i)
    }

    // Add some chat lines to the []chat slice
    for i := 0; i < 5; i++ {
        mutex.Lock()
        chat = append(chat, fmt.Sprintf("Message '%d'", i))
        mutex.Unlock()

        // Notify any clients there are new chats to read
        broadcaster.Broadcast()
    }

    // Tell the clients to quit
    close(done)

UntilPass

Functional test helper which will run a suite of tests until the entire suite passes, or all attempts have been exhausted.

import (
    "github.com/mailgun/holster/v4/testutil"
    "github.com/stretchr/testify/require"
    "github.com/stretchr/testify/assert"
)

func TestUntilPass(t *testing.T) {
    rand.Seed(time.Now().UnixNano())
    var value string

    ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
        if r.Method == http.MethodPost {
            // Sleep some rand amount to time to simulate some
            // async process happening on the server
            time.Sleep(time.Duration(rand.Intn(10))*time.Millisecond)
            // Set the value
            value = r.FormValue("value")
        } else {
            fmt.Fprintln(w, value)
        }
    }))
    defer ts.Close()

    // Start the async process that produces a value on the server
    http.PostForm(ts.URL, url.Values{"value": []string{"batch job completed"}})

    // Keep running this until the batch job completes or attempts are exhausted
    testutil.UntilPass(t, 10, time.Millisecond*100, func(t testutil.TestingT) {
        r, err := http.Get(ts.URL)

        // use of `require` will abort the current test here and tell UntilPass() to
        // run again after 100 milliseconds
        require.NoError(t, err)

        // Or you can check if the assert returned true or not
        if !assert.Equal(t, 200, r.StatusCode) {
            return
        }

        b, err := ioutil.ReadAll(r.Body)
        require.NoError(t, err)

        assert.Equal(t, "batch job completed\n", string(b))
    })
}

UntilConnect

Waits until the test can connect to the TCP/HTTP server before continuing the test

import (
    "github.com/mailgun/holster/v4/testutil"
    "golang.org/x/net/nettest"
    "github.com/stretchr/testify/require"
)

func TestUntilConnect(t *testing.T) {
    ln, err := nettest.NewLocalListener("tcp")
    require.NoError(t, err)

    go func() {
        cn, err := ln.Accept()
        require.NoError(t, err)
        cn.Close()
    }()
    // Wait until we can connect, then continue with the test
    testutil.UntilConnect(t, 10, time.Millisecond*100, ln.Addr().String())
}

Retry Until

Retries a function until the function returns error = nil or until the context is deadline is exceeded

ctx, cancel := context.WithTimeout(context.Background(), time.Second*20)
defer cancel()
err := retry.Until(ctx, retry.Interval(time.Millisecond*10), func(ctx context.Context, att int) error {
    res, err := http.Get("http://example.com/get")
    if err != nil {
        return err
    }
    if res.StatusCode != http.StatusOK {
        return errors.New("expected status 200")
    }
    // Do something with the body
    return nil
})
if err != nil {
    panic(err)
}

Backoff functions provided

  • retry.Attempts(10, time.Millisecond*10) retries up to 10 attempts
  • retry.Interval(time.Millisecond*10) retries at an interval indefinitely or until context is cancelled
  • retry.ExponentialBackoff{ Min: time.Millisecond, Max: time.Millisecond * 100, Factor: 2} retries at an exponential backoff interval. Can accept an optional Attempts which will limit the number of attempts

Retry Async

Runs a function asynchronously and retries it until it succeeds, or the context is cancelled or Stop() is called. This is useful in distributed programming where you know a remote thing will eventually succeed, but you need to keep trying until the remote thing succeeds, or we are told to shutdown.

ctx := context.Background()
async := retry.NewRetryAsync()

backOff := &retry.ExponentialBackoff{
    Min:      time.Millisecond,
    Max:      time.Millisecond * 100,
    Factor:   2,
    Attempts: 10,
}

id := createNewEC2("my-new-server")

async.Async(id, ctx, backOff, func(ctx context.Context, i int) error {
    // Waits for a new EC2 instance to be created then updates the config and exits
    if err := updateInstance(id, mySettings); err != nil {
        return err
    }
    return nil
})
// Wait for all the asyncs to complete
async.Wait()

OpenTelemetry

Tracing tools using OpenTelemetry client SDK and Jaeger Tracing server.

See tracing readme for details.

Context Utilities

See package directory ctxutil.

Use functions ctxutil.WithDeadline()/WithTimeout() instead of the context equivalents to log details of the deadline and source file:line where it was set. Must enable debug logging.

Contributing code

Please read the Contribution Guidelines before sending patches.

holster's People

Contributors

0xflotus avatar b0d0nne11 avatar baliedge avatar cpustejovsky avatar dependabot[bot] avatar highlycaffeinated avatar horkhe avatar ilyabrin avatar inge4pres avatar kbundgaard avatar matthewedge avatar mkbond avatar nexweb avatar obukhov-sergey avatar powellchristoph avatar rneillj avatar takumi2008 avatar thrawn01 avatar toutpetitadrien avatar tresoelze avatar vikmik avatar vtopc avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

holster's Issues

undefined: holster.BackOffCounter

../github.com/mailgun/holster/etcdutil/election.go:48:13: undefined: holster.BackOffCounter
../github.com/mailgun/holster/etcdutil/session.go:20:17: undefined: holster.BackOffCounter

Fix and enable mxresolv.TestLookupError

=== RUN   TestLookupError/kaboom
    mxresolv_test.go:119: 
        	Error Trace:	/home/runner/work/holster/holster/mxresolv/mxresolv_test.go:119
        	Error:      	Expect "lookup kaboom: Temporary failure in name resolution" to match "lookup kaboom.*: no such host"
        	Test:       	TestLookupError/kaboom
    mxresolv_test.go:126: 
        	Error Trace:	/home/runner/work/holster/holster/mxresolv/mxresolv_test.go:126
        	Error:      	Should be false
        	Test:       	TestLookupError/kaboom
    mxresolv_test.go:131: 
        	Error Trace:	/home/runner/work/holster/holster/mxresolv/mxresolv_test.go:131
        	Error:      	Expect "lookup kaboom: Temporary failure in name resolution" to match "lookup kaboom.*: no such host"
        	Test:       	TestLookupError/kaboom

Fix errors.TestFormatGeneric

Fix test/code or deprecate and switch to built-in package errors.

=== RUN   TestFormatGeneric
    format_test.go:476: test 1: block 6: fmt.Sprintf("%+v", err):
        got:
        "github.com/mailgun/holster/v4/errors.testGenericRecursive\n\tgithub.com/mailgun/holster/v4/errors/format_test.go:504\ngithub.com/mailgun/holster/v4/errors.testGenericRecursive\n\tgithub.com/mailgun/holster/v4/errors/format_test.go:523\ngithub.com/mailgun/holster/v4/errors.testGenericRecursive\n\tgithub.com/mailgun/holster/v4/errors/format_test.go:523\ngithub.com/mailgun/holster/v4/errors.testGenericRecursive\n\tgithub.com/mailgun/holster/v4/errors/format_test.go:523\ngithub.com/mailgun/holster/v4/errors.TestFormatGeneric\n\tgithub.com/mailgun/holster/v4/errors/format_test.go:359\ntesting.tRunner\n\ttesting/testing.go:1446\nruntime.goexit\n\truntime/asm_amd64.s:1594"
        want:
        "github.com/mailgun/holster/v4/errors.(func·002|TestFormatGeneric.func2)\n\t.+/errors/format_test.go:333"
        all-got:
           new-error
           github.com/mailgun/holster/v4/errors.TestFormatGeneric
        	github.com/mailgun/holster/v4/errors/format_test.go:315
        testing.tRunner
        	testing/testing.go:1446
        runtime.goexit
        	runtime/asm_amd64.s:1594
           with-message
           with-message
           with-message
           github.com/mailgun/holster/v4/errors.testGenericRecursive
        	github.com/mailgun/holster/v4/errors/format_test.go:504
        github.com/mailgun/holster/v4/errors.testGenericRecursive
        	github.com/mailgun/holster/v4/errors/format_test.go:523
        github.com/mailgun/holster/v4/errors.testGenericRecursive
        	github.com/mailgun/holster/v4/errors/format_test.go:523
        github.com/mailgun/holster/v4/errors.testGenericRecursive
        	github.com/mailgun/holster/v4/errors/format_test.go:523
        github.com/mailgun/holster/v4/errors.TestFormatGeneric
        	github.com/mailgun/holster/v4/errors/format_test.go:359
        testing.tRunner
        	testing/testing.go:1446
        runtime.goexit
        	runtime/asm_amd64.s:1594
        all-want:
           new-error
           github.com/mailgun/holster/v4/errors.TestFormatGeneric
        	.+/errors/format_test.go:315
           with-message
           with-message
           with-message
           github.com/mailgun/holster/v4/errors.(func·002|TestFormatGeneric.func2)
        	.+/errors/format_test.go:333
--- FAIL: TestFormatGeneric (0.00s)

https://github.com/mailgun/holster/actions/runs/3740540806/jobs/6349033540

Fix and enable tracing.TestDummySpan

=== RUN   TestDummySpan
=== RUN   TestDummySpan/Single_dropped_span
time="2022-12-20T12:43:57Z" level=info msg="Initializing OTLP exporter" category=tracing endpoint= protocol=grpc
    dummy_span_test.go:36: PASS:	Shutdown(string)
=== RUN   TestDummySpan/Nested_scope_with_dropped_leaf_span
time="2022-12-20T12:43:57Z" level=info msg="Initializing OTLP exporter" category=tracing endpoint= protocol=grpc
    dummy_span_test.go:65: 
        	Error Trace:	/home/runner/work/holster/holster/tracing/dummy_span_test.go:65
        	Error:      	Received unexpected error:
        	            	context deadline exceeded
        	            	error in tp.Shutdown
        	            	github.com/mailgun/holster/v4/tracing.CloseTracing
        	            		github.com/mailgun/holster/v4/tracing/tracing.go:149
        	            	github.com/mailgun/holster/v4/tracing_test.TestDummySpan.func2
        	            		github.com/mailgun/holster/v4/tracing/dummy_span_test.go:64
        	            	testing.tRunner
        	            		testing/testing.go:1446
        	            	runtime.goexit
        	            		runtime/asm_amd64.s:1594
        	Test:       	TestDummySpan/Nested_scope_with_dropped_leaf_span

https://github.com/mailgun/holster/actions/runs/3740540806/jobs/6349033540

this is not an issue with tracing.CloseTracing() cause TestTracing is not failing.

dummy_span is not compatible with opentelemetry-go v1.25.0

If holster library is used in a project that has opentelemetry-go v1.25.0 or above, it will fail to build due to

# github.com/mailgun/holster/v4/tracing
../../../../go/pkg/mod/github.com/mailgun/holster/[email protected]/tracing/dummy_span.go:30:35: cannot use span (variable of type *DummySpan) as "go.opentelemetry.io/otel/trace".Span value in argument to trace.ContextWithSpan: *DummySpan does not implement "go.opentelemetry.io/otel/trace".Span (missing method AddLink)
../../../../go/pkg/mod/github.com/mailgun/holster/[email protected]/tracing/dummy_span.go:32:14: cannot use span (variable of type *DummySpan) as "go.opentelemetry.io/otel/trace".Span value in return statement: *DummySpan does not implement "go.opentelemetry.io/otel/trace".Span (missing method AddLink)
make: *** [build] Error 1

Root cause of issue is that opentelemetry-go v1.25.0 now expects trace interface to have AddLink(link Link)

errors.Wrap()/errors.Is() is not working

See tests in the #104

errors.Is() docs:

// Is reports whether any error in err's chain matches target.
//
// The chain consists of err itself followed by the sequence of errors obtained by
// repeatedly calling Unwrap.
//
// An error is considered to match a target if it is equal to that target or if
// it implements a method Is(error) bool such that Is(target) returns true.

which is not true now.

DATA RACE in holster/discovery

=== RUN   TestSrvResolverBuilderSuccess
==================
WARNING: DATA RACE
Read at 0x00c0003322a8 by goroutine 43:
  github.com/mailgun/holster/v4/discovery_test.TestSrvResolverBuilderSuccess()
      /Users/vtopc/mailgun/holster/discovery/grpc_srv_resolver_test.go:82 +0x9f7
  testing.tRunner()
      /usr/local/go/src/testing/testing.go:1446 +0x216
  testing.(*T).Run.func1()
      /usr/local/go/src/testing/testing.go:1493 +0x47

Previous write at 0x00c0003322a8 by goroutine 46:
  github.com/mailgun/holster/v4/discovery_test.(*testClientConn).UpdateState()
      /Users/vtopc/mailgun/holster/discovery/grpc_srv_resolver_test.go:32 +0xea
  github.com/mailgun/holster/v4/discovery.(*srvResolver).lookupSRV()
      /Users/vtopc/mailgun/holster/discovery/grpc_srv_resolver.go:201 +0x688
  github.com/mailgun/holster/v4/discovery.(*srvResolver).watcher()
      /Users/vtopc/mailgun/holster/discovery/grpc_srv_resolver.go:117 +0x1b7
  github.com/mailgun/holster/v4/discovery.(*srvResolverBuilder).Build.func1()
      /Users/vtopc/mailgun/holster/discovery/grpc_srv_resolver.go:62 +0x39

Goroutine 43 (running) created at:
  testing.(*T).Run()
      /usr/local/go/src/testing/testing.go:1493 +0x75d
  testing.runTests.func1()
      /usr/local/go/src/testing/testing.go:1846 +0x99
  testing.tRunner()
      /usr/local/go/src/testing/testing.go:1446 +0x216
  testing.runTests()
      /usr/local/go/src/testing/testing.go:1844 +0x7ec
  testing.(*M).Run()
      /usr/local/go/src/testing/testing.go:1726 +0xa84
  main.main()
      _testmain.go:63 +0x2e9

Goroutine 46 (running) created at:
  github.com/mailgun/holster/v4/discovery.(*srvResolverBuilder).Build()
      /Users/vtopc/mailgun/holster/discovery/grpc_srv_resolver.go:62 +0x336
  github.com/mailgun/holster/v4/discovery_test.TestSrvResolverBuilderSuccess()
      /Users/vtopc/mailgun/holster/discovery/grpc_srv_resolver_test.go:67 +0x836
  testing.tRunner()
      /usr/local/go/src/testing/testing.go:1446 +0x216
  testing.(*T).Run.func1()
      /usr/local/go/src/testing/testing.go:1493 +0x47
==================
==================
WARNING: DATA RACE
Read at 0x00c0000ae480 by goroutine 43:
  github.com/mailgun/holster/v4/discovery_test.TestSrvResolverBuilderSuccess()
      /Users/vtopc/mailgun/holster/discovery/grpc_srv_resolver_test.go:82 +0xa1b
  testing.tRunner()
      /usr/local/go/src/testing/testing.go:1446 +0x216
  testing.(*T).Run.func1()
      /usr/local/go/src/testing/testing.go:1493 +0x47

Previous write at 0x00c0000ae480 by goroutine 46:
  runtime.slicecopy()
      /usr/local/go/src/runtime/slice.go:307 +0x0
  github.com/mailgun/holster/v4/discovery.(*srvResolver).lookupSRV()
      /Users/vtopc/mailgun/holster/discovery/grpc_srv_resolver.go:186 +0xb8f
  github.com/mailgun/holster/v4/discovery.(*srvResolver).watcher()
      /Users/vtopc/mailgun/holster/discovery/grpc_srv_resolver.go:117 +0x1b7
  github.com/mailgun/holster/v4/discovery.(*srvResolverBuilder).Build.func1()
      /Users/vtopc/mailgun/holster/discovery/grpc_srv_resolver.go:62 +0x39

Goroutine 43 (running) created at:
  testing.(*T).Run()
      /usr/local/go/src/testing/testing.go:1493 +0x75d
  testing.runTests.func1()
      /usr/local/go/src/testing/testing.go:1846 +0x99
  testing.tRunner()
      /usr/local/go/src/testing/testing.go:1446 +0x216
  testing.runTests()
      /usr/local/go/src/testing/testing.go:1844 +0x7ec
  testing.(*M).Run()
      /usr/local/go/src/testing/testing.go:1726 +0xa84
  main.main()
      _testmain.go:63 +0x2e9

Goroutine 46 (running) created at:
  github.com/mailgun/holster/v4/discovery.(*srvResolverBuilder).Build()
      /Users/vtopc/mailgun/holster/discovery/grpc_srv_resolver.go:62 +0x336
  github.com/mailgun/holster/v4/discovery_test.TestSrvResolverBuilderSuccess()
      /Users/vtopc/mailgun/holster/discovery/grpc_srv_resolver_test.go:67 +0x836
  testing.tRunner()
      /usr/local/go/src/testing/testing.go:1446 +0x216
  testing.(*T).Run.func1()
      /usr/local/go/src/testing/testing.go:1493 +0x47
==================
==================
WARNING: DATA RACE
Read at 0x00c0000ae4c8 by goroutine 43:
  github.com/mailgun/holster/v4/discovery_test.TestSrvResolverBuilderSuccess()
      /Users/vtopc/mailgun/holster/discovery/grpc_srv_resolver_test.go:83 +0xaa4
  testing.tRunner()
      /usr/local/go/src/testing/testing.go:1446 +0x216
  testing.(*T).Run.func1()
      /usr/local/go/src/testing/testing.go:1493 +0x47

Previous write at 0x00c0000ae4c8 by goroutine 46:
  runtime.slicecopy()
      /usr/local/go/src/runtime/slice.go:307 +0x0
  github.com/mailgun/holster/v4/discovery.(*srvResolver).lookupSRV()
      /Users/vtopc/mailgun/holster/discovery/grpc_srv_resolver.go:186 +0xb8f
  github.com/mailgun/holster/v4/discovery.(*srvResolver).watcher()
      /Users/vtopc/mailgun/holster/discovery/grpc_srv_resolver.go:117 +0x1b7
  github.com/mailgun/holster/v4/discovery.(*srvResolverBuilder).Build.func1()
      /Users/vtopc/mailgun/holster/discovery/grpc_srv_resolver.go:62 +0x39

Goroutine 43 (running) created at:
  testing.(*T).Run()
      /usr/local/go/src/testing/testing.go:1493 +0x75d
  testing.runTests.func1()
      /usr/local/go/src/testing/testing.go:1846 +0x99
  testing.tRunner()
      /usr/local/go/src/testing/testing.go:1446 +0x216
  testing.runTests()
      /usr/local/go/src/testing/testing.go:1844 +0x7ec
  testing.(*M).Run()
      /usr/local/go/src/testing/testing.go:1726 +0xa84
  main.main()
      _testmain.go:63 +0x2e9

Goroutine 46 (running) created at:
  github.com/mailgun/holster/v4/discovery.(*srvResolverBuilder).Build()
      /Users/vtopc/mailgun/holster/discovery/grpc_srv_resolver.go:62 +0x336
  github.com/mailgun/holster/v4/discovery_test.TestSrvResolverBuilderSuccess()
      /Users/vtopc/mailgun/holster/discovery/grpc_srv_resolver_test.go:67 +0x836
  testing.tRunner()
      /usr/local/go/src/testing/testing.go:1446 +0x216
  testing.(*T).Run.func1()
      /usr/local/go/src/testing/testing.go:1493 +0x47
==================
    testing.go:1319: race detected during execution of test
--- FAIL: TestSrvResolverBuilderSuccess (0.00s)

Broken links in README

The README seems to have multiple broken links on account of the tag v3 not existing. And a few of the packages that have been documented in the README, such as config don't seem to exist in the repo anymore.

I can send in a PR for this

can't load package while doing go get

tried pulling the package using go get and got this error

$ go get -v github.com/mailgun/holster
$ can't load package: package github.com/mailgun/holster: no Go files in $GOPATH/src/github.com/mailgun/holster

Fix and enable consul.TestNewClientTLS

=== RUN   TestNewClientTLS
    config_test.go:26: 
        	Error Trace:	/home/runner/work/holster/holster/consul/config_test.go:26
        	Error:      	Received unexpected error:
        	            	Put "https://127.0.0.1:8501/v1/kv/test-key-tls": x509: certificate has expired or is not yet valid: current time 2022-12-20T12:40:42Z is after 2021-11-18T22:57:23Z
        	Test:       	TestNewClientTLS
--- FAIL: TestNewClientTLS (0.01s)

How to fix:
Update certificates?

openssl req -x509 -nodes -newkey rsa:2048 -keyout <key_file> -out <cert_file> -days 3650 -subj "/C=US/ST=TX/L=San Antonio/O=Mailgun/OU=Technology/CN=foobarserver"

useragent depends on Events which is not open source

github.com/mailgun/holster/useragent depends upon github.com/mailgun/events, which is seemingly not open source or available anywhere. Either useragent shouldn't be here, or the struct should be copied into holster... or events made open?

DATA RACE in holster/clock

Version: v4.9.5

WARNING: DATA RACE
Write at 0x00c00006c0f8 by goroutine 16:
  github.com/mailgun/holster/v4/clock.(*frozenTime).unlockedStartTimer()
      github.com/mailgun/holster/v4/clock/frozen.go:151 +0x211
  github.com/mailgun/holster/v4/clock.(*frozenTime).startTimer()
      github.com/mailgun/holster/v4/clock/frozen.go:133 +0xa4
  github.com/mailgun/holster/v4/clock.(*frozenTime).AfterFunc()
      github.com/mailgun/holster/v4/clock/frozen.go:50 +0x1db
  github.com/mailgun/holster/v4/clock.(*frozenTime).NewTimer()
      github.com/mailgun/holster/v4/clock/frozen.go:[38](https://github.com/mailgun/holster/actions/runs/3740540806/jobs/6349033540#step:7:39) +0x38
  github.com/mailgun/holster/v4/clock.(*frozenTime).Sleep()
      github.com/mailgun/holster/v4/clock/frozen.go:30 +0x[39](https://github.com/mailgun/holster/actions/runs/3740540806/jobs/6349033540#step:7:40)
  github.com/mailgun/holster/v4/clock.Sleep()
      github.com/mailgun/holster/v4/clock/clock.go:76 +0x37
  github.com/mailgun/holster/v4/clock.(*FrozenSuite).TestSleep.func1()
      github.com/mailgun/holster/v4/clock/frozen_test.go:57 +0x3c
  github.com/mailgun/holster/v4/clock.(*FrozenSuite).TestSleep.func5()
      github.com/mailgun/holster/v4/clock/frozen_test.go:84 +0x47

Previous read at 0x00c00006c0f8 by goroutine 15:
  github.com/mailgun/holster/v4/clock.(*FrozenSuite).TestSleep()
      github.com/mailgun/holster/v4/clock/frozen_test.go:89 +0x63c
  runtime.call16()
      runtime/asm_amd64.s:724 +0x48
  reflect.Value.Call()
      reflect/value.go:368 +0xc7
  github.com/stretchr/testify/suite.Run.func1()
      github.com/stretchr/[email protected]/suite/suite.go:175 +0x6e6
  testing.tRunner()
      testing/testing.go:1[44](https://github.com/mailgun/holster/actions/runs/3740540806/jobs/6349033540#step:7:45)6 +0x216
  testing.(*T).Run.func1()
      testing/testing.go:1493 +0x47

Goroutine 16 (running) created at:
  github.com/mailgun/holster/v4/clock.(*FrozenSuite).TestSleep()
      github.com/mailgun/holster/v4/clock/frozen_test.go:84 +0x55d
  runtime.call16()
      runtime/asm_amd64.s:724 +0x48
  reflect.Value.Call()
      reflect/value.go:368 +0xc7
  github.com/stretchr/testify/suite.Run.func1()
      github.com/stretchr/[email protected]/suite/suite.go:175 +0x6e6
  testing.tRunner()
      testing/testing.go:14[46](https://github.com/mailgun/holster/actions/runs/3740540806/jobs/6349033540#step:7:47) +0x216
  testing.(*T).Run.func1()
      testing/testing.go:1493 +0x[47](https://github.com/mailgun/holster/actions/runs/3740540806/jobs/6349033540#step:7:48)

Goroutine 15 (running) created at:
  testing.(*T).Run()
      testing/testing.go:1[49](https://github.com/mailgun/holster/actions/runs/3740540806/jobs/6349033540#step:7:50)3 +0x75d
  github.com/stretchr/testify/suite.runTests()
      github.com/stretchr/[email protected]/suite/suite.go:220 +0x198
  github.com/stretchr/testify/suite.Run()
      github.com/stretchr/[email protected]/suite/suite.go:193 +0x9ae
  github.com/mailgun/holster/v4/clock.TestFrozenSuite()
      github.com/mailgun/holster/v4/clock/frozen_test.go:21 +0x44
  testing.tRunner()
      testing/testing.go:1446 +0x216
  testing.(*T).Run.func1()
      testing/testing.go:1493 +0x47
==================

https://github.com/mailgun/holster/actions/runs/3740540806/jobs/6349033540


one more proof

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.