holster

package module
v3.0.0+incompatible Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: May 15, 2019 License: Apache-2.0 Imports: 13 Imported by: 0

README

Holster

A place to holster mailgun's golang libraries and tools

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

Random

Random is an Interface for random number generators. See the random readme for details

Secret

Secret is a library for encrypting and decrypting authenticated messages. See the secret readme for details

Distributed Election

A distributed election implementation using etcd to coordinate elections See the etcd v2 readme for details 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()

var wg 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", errrs)
}

Clean up long running routines easily with .Loop()

pipe := make(chan int32, 0)
var wg 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

var wg 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.

// Insert records into the database 10 at a time
fanOut := holster.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

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

cache := 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

// 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 := holster.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 inteface{}, 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.

ttlMap := holster.NewTTLMap(10)
ttlMap.Clock = &holster.FrozenClock{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
ttlMap.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

var value string

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

// Returns true if 'value' is zero (the default golang value)
holster.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
}
holster.SetDefault(&config.Foo, "default")
holster.SetDefault(&config.Bar, 200)

// Supply additional default values and SetDefault will
// choose the first default that is not of zero value
holster.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")

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

GetEnv

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

var conf = sandra.CassandraConfig{
   Nodes:    []string{holster.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
holster.RandomRunes("prefix-", 10, holster.AlphaRunes, hoslter.NumericRunes)

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

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

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

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

Logrus ToFields()

Recursively convert a deeply nested struct or map to logrus.Fields such that the result is safe for JSON encoding. (IE: Ignore non marshallerable types like func)

conf := struct {
   Endpoints []string
   CallBack  func([]byte) bool
   LogLevel  int
}
// Outputs the contents of the config struct along with the info message
logrus.WithFields(holster.ToFields(conf)).Info("Starting service")

GoRoutine ID

Get the go routine id (useful for logging)

import "github.com/mailgun/holster/stack"
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/slice"

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

Clock

DEPRECATED: Use clock package instead.

Provides an interface which allows users to inject a modified clock during testing.

type MyApp struct {
    Clock holster.Clock
}

// Defaults to the system clock
app := MyApp{Clock: &holster.SystemClock{}}

// Override the system clock for testing
app.Clock = &holster.FrozenClock{time.Date(2009, time.November, 10, 23, 0, 0, 0, time.UTC)}

// Simulate sleeping for 10 seconds
app.Clock.Sleep(time.Second * 10)

fmt.Printf("Time is Now: %s", app.Clock.Now())

// Output: Time is Now: 2009-11-10 23:00:10 +0000 UTC
}

Priority Queue

Provides a Priority Queue implementation as described here

queue := holster.NewPriorityQueue()

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

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

queue.Push(&holster.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

User Agent

Provides user agent parsing into Mailgun ClientInfo events.

clientInfo := useragent.Parse("Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.17 (KHTML, like Gecko) Chrome/24.0.1312.70 Safari/537.17")

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.

	broadcaster := holster.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)

Documentation

Overview

Copyright 2017 Mailgun Technologies Inc

Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at

http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.

Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at

http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.

Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at

http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.

Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at

http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.

This work is derived from github.com/golang/groupcache/lru

Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at

http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.

Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at

http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.

Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at

http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.

Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at

http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.

Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at

http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.

Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at

http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.

Index

Constants

View Source
const AlphaRunes = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"
View Source
const NumericRunes = "0123456789"

Variables

This section is empty.

Functions

func AdvanceSleepClock

func AdvanceSleepClock(clock Clock, d time.Duration)

Helper method for sleep clock (See SleepClock.Advance())

func BackOff

func BackOff(attempt int) time.Duration

BackOff is a convenience function which returns a back off duration with a default 300 millisecond minimum and a 30 second maximum with a factor of 2 for each attempt.

func GetEnv

func GetEnv(envName, defaultValue string) string

Get the environment variable or return the default value if unset

func IsZero

func IsZero(value interface{}) bool

Returns true if 'value' is zero (the default golang value)

var thingy string
holster.IsZero(thingy) == true

func IsZeroValue

func IsZeroValue(value reflect.Value) bool

Returns true if 'value' is zero (the default golang value)

var count int64
holster.IsZeroValue(reflect.ValueOf(count)) == true

func RandomAlpha

func RandomAlpha(prefix string, length int) string

Return a random string of alpha characters

func RandomDomainName

func RandomDomainName() string

Return a random domain name in the form "randomAlpha.net"

func RandomItem

func RandomItem(items ...string) string

Given a list of strings, return one of the strings randomly

func RandomRunes

func RandomRunes(prefix string, length int, runes ...string) string

Return a random string made up of characters passed

func RandomString

func RandomString(prefix string, length int) string

Return a random string of alpha and numeric characters

func SetDefault

func SetDefault(dest interface{}, defaultValue ...interface{})

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 {
		Verbose *bool
		Foo string
		Bar int
	}
	holster.SetDefault(&config.Foo, "default")
	holster.SetDefault(&config.Bar, 200)

Supply additional default values and SetDefault will choose the first default that is not of zero value

holster.SetDefault(&config.Foo, os.Getenv("FOO"), "default")

func SetOverride

func SetOverride(dest interface{}, values ...interface{})

Assign the first value that is not empty or of zero 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 {
		Verbose *bool
		Foo string
		Bar int
	}

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

 // Override the config file if 'foo' is provided via
 // the cli or defined in the environment.
	holster.SetOverride(&config.Foo, *argFoo, os.Env("FOO"))

Supply additional values and SetOverride() will choose the first value that is not of zero value. If all values are empty or zero the 'dest' will remain unchanged.

func ToFields

func ToFields(value interface{}) logrus.Fields

Given a struct or map[string]interface{} return as a logrus.Fields{} map

Types

type BackOffCounter

type BackOffCounter struct {
	// contains filtered or unexported fields
}

func NewBackOff

func NewBackOff(min, max time.Duration, factor float64) *BackOffCounter

func (*BackOffCounter) BackOff

func (b *BackOffCounter) BackOff(attempt int) time.Duration

BackOff calculates the back depending on the attempts provided

func (*BackOffCounter) Next

func (b *BackOffCounter) Next() time.Duration

Next returns the next back off duration based on the number of times Next() was called. Each call to next returns the next factor of back off. Call Reset() to reset the back off attempts to zero.

func (*BackOffCounter) Reset

func (b *BackOffCounter) Reset()

Reset sets the back off attempt counter to zero

type Broadcaster

type Broadcaster interface {
	WaitChan(string) chan struct{}
	Wait(string)
	Broadcast()
	Done()
}

func NewBroadcaster

func NewBroadcaster() Broadcaster

type Clock

type Clock interface {
	Now() time.Time
	Sleep(time.Duration)
	After(time.Duration) <-chan time.Time
}

TimeProvider is an interface we use to mock time in tests.

func NewSleepClock

func NewSleepClock(currentTime time.Time) Clock

type ExpireCache

type ExpireCache struct {
	// contains filtered or unexported fields
}

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 is different from a LRU cache, as the cache might decide an item needs to be removed (because we hit the cache limit) before the item has been processed.

Every time an item is touched by `Get()` or `Add()` the duration is updated which ensures items in frequent use stay in the cache

Processing 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 track the size of the cache

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

func NewExpireCache

func NewExpireCache(ttl time.Duration) *ExpireCache

New creates a new ExpireCache.

func (*ExpireCache) Add

func (c *ExpireCache) Add(key interface{}, value interface{})

Put the key, value and TTL in the cache

func (*ExpireCache) Each

func (c *ExpireCache) Each(concurrent int, callBack func(key interface{}, value interface{}) error) []error

Processes each item in the cache in a thread safe way, such that the cache can be in use while processing items in the cache

func (*ExpireCache) Get

func (c *ExpireCache) Get(key interface{}) (interface{}, bool)

Retrieves a key's value from the cache

func (*ExpireCache) GetStats

func (c *ExpireCache) GetStats() ExpireCacheStats

Retrieve stats about the cache

func (*ExpireCache) Keys

func (c *ExpireCache) Keys() (keys []interface{})

Get a list of keys at this point in time

func (*ExpireCache) Peek

func (c *ExpireCache) Peek(key interface{}) (value interface{}, ok bool)

Get the value without updating the expiration

func (*ExpireCache) Size

func (c *ExpireCache) Size() int64

Returns the number of items in the cache.

func (*ExpireCache) Update

func (c *ExpireCache) Update(key interface{}, value interface{}) error

Update the value in the cache without updating the TTL

type ExpireCacheStats

type ExpireCacheStats struct {
	Size int64
	Miss int64
	Hit  int64
}

type FanOut

type FanOut struct {
	// contains filtered or unexported fields
}

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.

func NewFanOut

func NewFanOut(size int) *FanOut

func (*FanOut) Run

func (p *FanOut) Run(callBack func(interface{}) error, data interface{})

Run a new routine with an optional data value

func (*FanOut) Wait

func (p *FanOut) Wait() []error

Wait for all the routines to complete and return any errors

type FrozenClock

type FrozenClock struct {
	CurrentTime time.Time
}

Manually controlled clock for use in tests Advance time by calling FrozenClock.Sleep()

func (*FrozenClock) After

func (t *FrozenClock) After(d time.Duration) <-chan time.Time

func (*FrozenClock) Now

func (t *FrozenClock) Now() time.Time

func (*FrozenClock) Sleep

func (t *FrozenClock) Sleep(d time.Duration)

type Key

type Key interface{}

A Key may be any value that is comparable. See http://golang.org/ref/spec#Comparison_operators

type LRUCache

type LRUCache struct {
	// MaxEntries is the maximum number of cache entries before
	// an item is evicted. Zero means no limit.
	MaxEntries int

	// OnEvicted optionally specifies a callback function to be
	// executed when an entry is purged from the cache.
	OnEvicted func(key Key, value interface{})
	// contains filtered or unexported fields
}

Cache is an thread safe LRU cache that also supports optional TTL expiration You can use an non thread safe version of this

func NewLRUCache

func NewLRUCache(maxEntries int) *LRUCache

New creates a new Cache. If maxEntries is zero, the cache has no limit and it's assumed that eviction is done by the caller.

func (*LRUCache) Add

func (c *LRUCache) Add(key Key, value interface{}) bool

Add or Update a value in the cache, return true if the key already existed

func (*LRUCache) AddWithTTL

func (c *LRUCache) AddWithTTL(key Key, value interface{}, TTL time.Duration) bool

Adds a value to the cache with a TTL

func (LRUCache) Each

func (c LRUCache) Each(concurrent int, callBack func(key interface{}, value interface{}) error) []error

Processes each item in the cache in a thread safe way, such that the cache can be in use while processing items in the cache. Processing the cache with `Each()` does not update the expiration or last used.

func (*LRUCache) Get

func (c *LRUCache) Get(key Key) (value interface{}, ok bool)

Get looks up a key's value from the cache.

func (*LRUCache) Keys

func (c *LRUCache) Keys() (keys []interface{})

Get a list of keys at this point in time

func (*LRUCache) Peek

func (c *LRUCache) Peek(key interface{}) (value interface{}, ok bool)

Get the value without updating the expiration or last used or stats

func (*LRUCache) Remove

func (c *LRUCache) Remove(key Key)

Remove removes the provided key from the cache.

func (*LRUCache) Size

func (c *LRUCache) Size() int

Len returns the number of items in the cache.

func (*LRUCache) Stats

func (c *LRUCache) Stats() LRUCacheStats

Returns stats about the current state of the cache

type LRUCacheStats

type LRUCacheStats struct {
	Size int64
	Miss int64
	Hit  int64
}

Holds stats collected about the cache

type PQItem

type PQItem struct {
	Value    interface{}
	Priority int // The priority of the item in the queue.
	// contains filtered or unexported fields
}

An PQItem is something we manage in a priority queue.

type PriorityQueue

type PriorityQueue struct {
	// contains filtered or unexported fields
}

Implements a PriorityQueue

func NewPriorityQueue

func NewPriorityQueue() *PriorityQueue

func (PriorityQueue) Len

func (p PriorityQueue) Len() int

func (*PriorityQueue) Peek

func (p *PriorityQueue) Peek() *PQItem

func (*PriorityQueue) Pop

func (p *PriorityQueue) Pop() *PQItem

func (*PriorityQueue) Push

func (p *PriorityQueue) Push(el *PQItem)

func (*PriorityQueue) Remove

func (p *PriorityQueue) Remove(el *PQItem)

func (*PriorityQueue) Update

func (p *PriorityQueue) Update(el *PQItem, priority int)

Modifies the priority and value of an Item in the queue.

type SleepClock

type SleepClock struct {
	// contains filtered or unexported fields
}

SleepClock returns a Clock that has good fakes for time.Sleep and time.After. Both functions will behave as if time is frozen until you call AdvanceTimeBy, at which point any calls to time.Sleep that should return do return and any ticks from time.After that should happen do happen.

func (*SleepClock) Advance

func (t *SleepClock) Advance(d time.Duration)

Simulates advancing time by some time.Duration (Use for testing only)

func (*SleepClock) After

func (t *SleepClock) After(d time.Duration) <-chan time.Time

func (*SleepClock) Now

func (t *SleepClock) Now() time.Time

func (*SleepClock) Sleep

func (t *SleepClock) Sleep(d time.Duration)

type SystemClock

type SystemClock struct{}

system clock, time as reported by the operating system. Use this in production workloads.

func (*SystemClock) After

func (*SystemClock) After(d time.Duration) <-chan time.Time

func (*SystemClock) Now

func (*SystemClock) Now() time.Time

func (*SystemClock) Sleep

func (*SystemClock) Sleep(d time.Duration)

type TTLMap

type TTLMap struct {
	// Optionally specifies a callback function to be
	// executed when an entry has expired
	OnExpire func(key string, i interface{})

	// Optionally specify a time custom time object
	// used to determine if an item has expired
	Clock Clock
	// contains filtered or unexported fields
}

func NewTTLMap

func NewTTLMap(capacity int) *TTLMap

func NewTTLMapWithClock

func NewTTLMapWithClock(capacity int, clock Clock) *TTLMap

func (*TTLMap) Get

func (m *TTLMap) Get(key string) (interface{}, bool)

func (*TTLMap) GetInt

func (m *TTLMap) GetInt(key string) (int, bool, error)

func (*TTLMap) Increment

func (m *TTLMap) Increment(key string, value int, ttlSeconds int) (int, error)

func (*TTLMap) Len

func (m *TTLMap) Len() int

func (*TTLMap) RemoveExpired

func (m *TTLMap) RemoveExpired(iterations int) int

func (*TTLMap) RemoveLastUsed

func (m *TTLMap) RemoveLastUsed(iterations int)

func (*TTLMap) Set

func (m *TTLMap) Set(key string, value interface{}, ttlSeconds int) error

type WaitGroup

type WaitGroup struct {
	// contains filtered or unexported fields
}

func (*WaitGroup) Go

func (wg *WaitGroup) Go(cb func())

Execute a long running routine

func (*WaitGroup) Loop

func (wg *WaitGroup) Loop(callBack func() bool)

Run a goroutine in a loop continuously, if the callBack returns false the loop is broken

func (*WaitGroup) Run

func (wg *WaitGroup) Run(callBack func(interface{}) error, data interface{})

Run a routine and collect errors if any

func (*WaitGroup) Stop

func (wg *WaitGroup) Stop()

closes the done channel passed into `Until()` calls and waits for the `Until()` callBack to return false

func (*WaitGroup) Until

func (wg *WaitGroup) Until(callBack func(done chan struct{}) bool)

Run a goroutine in a loop continuously, if the callBack returns false the loop is broken. `Until()` differs from `Loop()` in that if the `Stop()` is called on the WaitGroup the `done` channel is closed. Implementations of the callBack function can listen for the close to indicate a stop was requested.

func (*WaitGroup) Wait

func (wg *WaitGroup) Wait() []error

Wait for all the routines to complete and return any errors collected

Directories

Path Synopsis
Package clock provides the same functions as the system package time.
Package clock provides the same functions as the system package time.
cmd
bunker
Bunkercmd is a command-line wrapper for bunker.
Bunkercmd is a command-line wrapper for bunker.
Package errors provides simple error handling primitives.
Package errors provides simple error handling primitives.
Provides tools for signing and authenticating HTTP requests between web services An keyed-hash message authentication code (HMAC) is used to provide integrity and authenticity of a message between web services.
Provides tools for signing and authenticating HTTP requests between web services An keyed-hash message authentication code (HMAC) is used to provide integrity and authenticity of a message between web services.
rfc

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL