fridge

package module
v0.0.0-...-da1c43e Latest Latest
Warning

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

Go to latest
Published: Jun 8, 2019 License: MIT Imports: 8 Imported by: 1 module, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

README

fridge Build Status Go Report Card GoDoc

fridge is a layer applied on top of a cache that makes interacting with it similar to interacting with a fridge. Items are tagged with a "Best By" and "Use By" timestamps, stored, restocked and retrieved.

Typically when using a cache, one would store some value along with a timeout. The value could be retrieved from the cache as long as it has not expired. If the value had expired, then an external call (Such as a database query) is usually made to retrieve the value, put it back in the cache and return it.

With fridge, we are taking a slightly different approach. Before storing a value in the fridge, one tags its key with a Best By and a Use By durations. When retrieving the value, a Restock function can be provided to refresh the value.

When attempting to retrieve a value from the fridge, there are multiple scenarios that could happen:

  • If the item has not passed its Best By duration (it is fresh)
    • Then the item is returned immediately.
  • If the item has passed its Best By duration but not its Use By duration (Not fresh but not expired either)
    • Then the item is returned immediately
    • But the Restock function is called asynchronously to refresh the item.
  • If the item has passed its Use By duration (it has expired)
    • The Restock function is called synchronously to retrieve a fresh item and return it.
  • If the item was not found
    • It is treated similarly to an expired item
    • The Restock function is called synchronously to retrieve a fresh item and return it.

Why?

The thinking behind fridge is to increase the chances for a value to be retrieved from the cache. The longer the value stays in the cache, the better the chances are to retrieve it faster (As opposed to from the database)

The challenge, of course, is to keep the value in the cache "fresh".

Dependencies

Examples

Example 1

Using NewClient to create a new fridge client. Note: NewClient accepts an object that implements the Cache interface which allows the user to use fridge with any underlying implementation.

// Cache is a Fridge cache interface
type Cache interface {
	// Get a value by key
	Get(key string) (string, bool, error)

	// Set a key value pair
	Set(key string, value string, timeout time.Duration) error

	// Remove a key
	Remove(key string) error

	// Ping to test connectivity
	Ping() error

	// Close to close resources
	Close() error
}
package main

import (
	"fmt"
	"github.com/shomali11/fridge"
	"time"
)

type SimpleCache struct {
	memory map[string]string
}

func (c *SimpleCache) Get(key string) (string, bool, error) {
	value, ok := c.memory[key]
	return value, ok, nil
}

func (c *SimpleCache) Set(key string, value string, timeout time.Duration) error {
	// We are not implementing the expiration to keep the example simple
	c.memory[key] = value
	return nil
}

func (c *SimpleCache) Remove(key string) error {
	delete(c.memory, key)
	return nil
}

func (c *SimpleCache) Ping() error {
	return nil
}

func (c *SimpleCache) Close() error {
	return nil
}

func main() {
	simpleCache := &SimpleCache{memory: make(map[string]string)}
	client := fridge.NewClient(simpleCache)

	fmt.Println(client.Ping())
}

Example 2

Using NewRedisCache to use fridge with redis. Note: NewRedisCache creates an redis client that implements the Cache interface

package main

import (
	"fmt"
	"github.com/shomali11/fridge"
)

func main() {
	redisCache := fridge.NewRedisCache()
	client := fridge.NewClient(redisCache)
	defer client.Close()

	fmt.Println(client.Ping())
}

Output

<nil>

Example 3

Using NewRedisCache with modified settings for a redis client

package main

import (
	"fmt"
	"github.com/shomali11/fridge"
)

func main() {
	redisCache := fridge.NewRedisCache(
		fridge.WithHost("localhost"), 
		fridge.WithPort(6379))
		
	client := fridge.NewClient(redisCache)
	defer client.Close()

	fmt.Println(client.Ping())
}

Output

<nil>

Example 4

Using NewSentinelCache with modified settings for a redis sentinel client. Note: NewSentinelCache creates an redis sentinel client that implements the Cache interface

package main

import (
	"fmt"
	"github.com/shomali11/fridge"
)

func main() {
	redisCache := fridge.NewSentinelCache(
		fridge.WithSentinelAddresses([]string{"localhost:26379"}),
		fridge.WithSentinelMasterName("master"))

	client := fridge.NewClient(redisCache)
	defer client.Close()

	fmt.Println(client.Ping())
}

Output

<nil>

Example 5

Using Put, Get & Remove to show how to put, get and remove an item. Note: That we are using a default client that has a default Best By of 1 hour and Use By of 1 Day for all keys

package main

import (
	"fmt"
	"github.com/shomali11/fridge"
)

func main() {
	redisCache := fridge.NewRedisCache()
	client := fridge.NewClient(redisCache)
	defer client.Close()

	fmt.Println(client.Put("food", "Pizza"))
	fmt.Println(client.Get("food"))
	fmt.Println(client.Remove("food"))
	fmt.Println(client.Get("food"))
}

Output

<nil>
Pizza true <nil>
<nil>
 false <nil>

Example 6

Using WithDefaultDurations to override the default Best By and Use By durations for all keys

package main

import (
	"fmt"
	"github.com/shomali11/fridge"
	"time"
)

func main() {
	redisCache := fridge.NewRedisCache()
	client := fridge.NewClient(redisCache, fridge.WithDefaultDurations(time.Second, 2*time.Second))
	defer client.Close()

	fmt.Println(client.Put("food", "Pizza"))
	fmt.Println(client.Get("food"))

	time.Sleep(time.Second)

	fmt.Println(client.Get("food"))

	time.Sleep(2 * time.Second)

	fmt.Println(client.Get("food"))
	fmt.Println(client.Remove("food"))
}

Output

<nil>
Pizza true <nil>
Pizza true <nil>
 false <nil>
<nil>

Example 7

Using Put to show how to put an item and override that item's durations.

package main

import (
	"fmt"
	"github.com/shomali11/fridge"
	"time"
)

func main() {
	redisCache := fridge.NewRedisCache()
	client := fridge.NewClient(redisCache)
	defer client.Close()

	fmt.Println(client.Put("food", "Pizza", fridge.WithDurations(time.Second, 2*time.Second)))
	fmt.Println(client.Get("food"))

	time.Sleep(time.Second)

	fmt.Println(client.Get("food"))

	time.Sleep(2 * time.Second)

	fmt.Println(client.Get("food"))
	fmt.Println(client.Remove("food"))
}

Output

<nil>
Pizza true <nil>
Pizza true <nil>
 false <nil>
<nil>

Example 8

Using Get to show how to retrieve an item while providing a restocking mechanism.

package main

import (
	"fmt"
	"github.com/shomali11/fridge"
	"time"
)

func main() {
	redisCache := fridge.NewRedisCache()
	client := fridge.NewClient(redisCache)
	defer client.Close()

	restock := func() (string, error) {
		return "Hot Pizza", nil
	}

	fmt.Println(client.Put("food", "Pizza", fridge.WithDurations(time.Second, 2*time.Second)))
	fmt.Println(client.Get("food", fridge.WithRestock(restock)))

	time.Sleep(time.Second)

	fmt.Println(client.Get("food", fridge.WithRestock(restock)))

	time.Sleep(2 * time.Second)

	fmt.Println(client.Get("food", fridge.WithRestock(restock)))
	fmt.Println(client.Remove("food"))
}

Output

<nil>
Pizza true <nil>
Pizza true <nil>
Hot Pizza true <nil>
<nil>

Example 9

Using HandleEvent to pass a callback to access the stream of events generated

package main

import (
	"fmt"
	"github.com/shomali11/fridge"
	"time"
)

func main() {
	redisCache := fridge.NewRedisCache()
	client := fridge.NewClient(redisCache, fridge.WithDefaultDurations(time.Second, 2*time.Second))
	defer client.Close()

	client.HandleEvent(func(event *fridge.Event) {
		fmt.Print("Key: " + event.Key + " - ")

		switch event.Type {
		case fridge.Fresh:
			fmt.Println("Woohoo! it is fresh!")
		case fridge.Cold:
			fmt.Println("Not fresh! But not bad either!")
		case fridge.Expired:
			fmt.Println("Sigh. It has expired!")
		case fridge.NotFound:
			fmt.Println("Oops! Did not find it.")
		case fridge.Restock:
			fmt.Println("Yay! Getting a new one!")
		case fridge.OutOfStock:
			fmt.Println("Oh no! It is out of stock.")
		case fridge.Unchanged:
			fmt.Println("Interesting! It has not changed.")
		}
	})

	restock := func() (string, error) {
		return "Pizza", nil
	}

	client.Put("food1", "Pizza")
	client.Put("food2", "Milk")

	client.Get("food1", fridge.WithRestock(restock))
	client.Get("food2")
	client.Get("food3")

	time.Sleep(time.Second)

	client.Get("food1", fridge.WithRestock(restock))
	client.Get("food2")
	client.Get("food3")

	time.Sleep(2 * time.Second)

	client.Get("food1", fridge.WithRestock(restock))
	client.Get("food2")
	client.Get("food3")

	client.Remove("food1")
	client.Remove("food2")
	client.Remove("food3")
}

Output:

Key: food1 - Woohoo! it is fresh!
Key: food2 - Woohoo! it is fresh!
Key: food3 - Oops! Did not find it.
Key: food1 - Not fresh! But not bad either!
Key: food1 - Yay! Getting a new one!
Key: food1 - Interesting! It has not changed.
Key: food2 - Not fresh! But not bad either!
Key: food2 - Oh no! It is out of stock.
Key: food3 - Oops! Did not find it.
Key: food1 - Sigh. It has expired!
Key: food1 - Yay! Getting a new one!
Key: food2 - Sigh. It has expired!
Key: food2 - Oh no! It is out of stock.
Key: food3 - Oops! Did not find it.

Documentation

Index

Constants

View Source
const (
	// Fresh is when an item has not passed its "Best By" duration
	Fresh = "FRESH"

	// Cold is when an item has passed its "Best By" duration but not its "Use By" one
	Cold = "COLD"

	// Expired is when an item has passed its "Use By" duration
	Expired = "EXPIRED"

	// NotFound is when an item was not found due to being removed or was never stored before
	NotFound = "NOT_FOUND"

	// Restock is when an item was restocked with a fresher one
	Restock = "RESTOCK"

	// OutOfStock is when an item needs restocking, but no restocking function was provided
	OutOfStock = "OUT_OF_STOCK"

	// Unchanged is when the restocked item is not different from the version in the cache
	Unchanged = "UNCHANGED"
)

Variables

This section is empty.

Functions

This section is empty.

Types

type Cache

type Cache interface {
	// Get a value by key
	Get(key string) (string, bool, error)

	// Set a key value pair
	Set(key string, value string, timeout time.Duration) error

	// Remove a key
	Remove(key string) error

	// Ping to test connectivity
	Ping() error

	// Close to close resources
	Close() error
}

Cache is a Fridge cache interface

type Client

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

Client fridge client

func NewClient

func NewClient(cache Cache, options ...DefaultsOption) *Client

NewClient returns a client

func (*Client) Close

func (c *Client) Close() error

Close closes resources

func (*Client) Get

func (c *Client) Get(key string, options ...RetrievalOption) (string, bool, error)

Get an item

func (*Client) HandleEvent

func (c *Client) HandleEvent(handleEvent func(event *Event))

HandleEvent overrides the default handleEvent callback

func (*Client) Ping

func (c *Client) Ping() error

Ping pings redis

func (*Client) Put

func (c *Client) Put(key string, value string, options ...StorageOption) error

Put an item

func (*Client) Remove

func (c *Client) Remove(key string) error

Remove an item

type Dao

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

Dao controls access to redis

func (*Dao) Close

func (d *Dao) Close() error

Close closes resources

func (*Dao) Get

func (d *Dao) Get(key string) (string, bool, error)

Get retrieves an item

func (*Dao) GetStorageDetails

func (d *Dao) GetStorageDetails(key string) (*StorageDetails, bool, error)

GetStorageDetails retrieves a key's storage details

func (*Dao) Ping

func (d *Dao) Ping() error

Ping pings redis

func (*Dao) Remove

func (d *Dao) Remove(key string) error

Remove an item

func (*Dao) Set

func (d *Dao) Set(key string, value string, timeout time.Duration) error

Set stores a value

func (*Dao) SetStorageDetails

func (d *Dao) SetStorageDetails(key string, storageDetails *StorageDetails) error

SetStorageDetails stores a key's defaults

type Defaults

type Defaults struct {
	BestBy time.Duration
	UseBy  time.Duration
}

Defaults configuration for the fridge client

type DefaultsOption

type DefaultsOption func(*Defaults)

DefaultsOption an option for default values

func WithDefaultDurations

func WithDefaultDurations(bestBy time.Duration, useBy time.Duration) DefaultsOption

WithDefaultDurations sets default best by and use by durations

type Event

type Event struct {
	Key  string
	Type string
}

Event is a Fridge event

type RedisCache

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

RedisCache contains redis client

func NewRedisCache

func NewRedisCache(options ...RedisOption) *RedisCache

NewRedisCache creates a new redis client

func (*RedisCache) Close

func (c *RedisCache) Close() error

Close to close resources

func (*RedisCache) Get

func (c *RedisCache) Get(key string) (string, bool, error)

Get a value by key

func (*RedisCache) Ping

func (c *RedisCache) Ping() error

Ping to test connectivity

func (*RedisCache) Remove

func (c *RedisCache) Remove(key string) error

Remove a key

func (*RedisCache) Set

func (c *RedisCache) Set(key string, value string, timeout time.Duration) error

Set a key value pair

type RedisOption

type RedisOption func(*RedisSettings)

RedisOption an option for a redis option

func WithConnectTimeout

func WithConnectTimeout(connectTimeout time.Duration) RedisOption

WithConnectTimeout sets redis connect timeout

func WithConnectionIdleTimeout

func WithConnectionIdleTimeout(connectionIdleTimeout time.Duration) RedisOption

WithConnectionIdleTimeout sets redis connection idle timeout

func WithConnectionMaxActive

func WithConnectionMaxActive(connectionMaxActive int) RedisOption

WithConnectionMaxActive sets redis connection max active

func WithConnectionMaxIdle

func WithConnectionMaxIdle(connectionMaxIdle int) RedisOption

WithConnectionMaxIdle sets redis connection max idle

func WithConnectionWait

func WithConnectionWait(connectionWait bool) RedisOption

WithConnectionWait sets redis connection wait

func WithDatabase

func WithDatabase(database int) RedisOption

WithDatabase sets redis database

func WithHost

func WithHost(host string) RedisOption

WithHost sets redis host

func WithNetwork

func WithNetwork(network string) RedisOption

WithNetwork sets redis network

func WithPassword

func WithPassword(password string) RedisOption

WithPassword sets redis password

func WithPort

func WithPort(port int) RedisOption

WithPort sets redis port

func WithReadTimeout

func WithReadTimeout(readTimeout time.Duration) RedisOption

WithReadTimeout sets redis read timeout

func WithTestOnBorrowPeriod

func WithTestOnBorrowPeriod(testOnBorrowPeriod time.Duration) RedisOption

WithTestOnBorrowPeriod sets redis test on borrow period

func WithTlsConfig

func WithTlsConfig(tlsConfig *tls.Config) RedisOption

WithTlsConfig sets redis tls config

func WithTlsSkipVerify

func WithTlsSkipVerify(tlsSkipVerify bool) RedisOption

WithTlsSkipVerify sets redis tls skip verification

func WithWriteTimeout

func WithWriteTimeout(writeTimeout time.Duration) RedisOption

WithWriteTimeout sets redis write timeout

type RedisSettings

type RedisSettings struct {
	Host                  string
	Port                  int
	Password              string
	Database              int
	Network               string
	ConnectTimeout        time.Duration
	WriteTimeout          time.Duration
	ReadTimeout           time.Duration
	ConnectionIdleTimeout time.Duration
	ConnectionMaxIdle     int
	ConnectionMaxActive   int
	ConnectionWait        bool
	TlsConfig             *tls.Config
	TlsSkipVerify         bool
	TestOnBorrowPeriod    time.Duration
}

RedisSettings contains redis settings

type RetrievalDetails

type RetrievalDetails struct {
	Restock func() (string, error)
}

RetrievalDetails contains retrieval information

type RetrievalOption

type RetrievalOption func(*RetrievalDetails)

RetrievalOption an option for retrieval

func WithRestock

func WithRestock(restock func() (string, error)) RetrievalOption

WithRestock sets retrieval restocking option

type SentinelCache

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

SentinelCache contains redis client

func NewSentinelCache

func NewSentinelCache(options ...SentinelOption) *SentinelCache

NewSentinelCache creates a new redis client

func (*SentinelCache) Close

func (c *SentinelCache) Close() error

Close to close resources

func (*SentinelCache) Get

func (c *SentinelCache) Get(key string) (string, bool, error)

Get a value by key

func (*SentinelCache) Ping

func (c *SentinelCache) Ping() error

Ping to test connectivity

func (*SentinelCache) Remove

func (c *SentinelCache) Remove(key string) error

Remove a key

func (*SentinelCache) Set

func (c *SentinelCache) Set(key string, value string, timeout time.Duration) error

Set a key value pair

type SentinelOption

type SentinelOption func(*SentinelSettings)

SentinelOption an option for a sentinel option

func WithRedisConnectTimeout

func WithRedisConnectTimeout(connectTimeout time.Duration) SentinelOption

WithRedisConnectTimeout sets redis connect timeout

func WithRedisConnectionIdleTimeout

func WithRedisConnectionIdleTimeout(connectionIdleTimeout time.Duration) SentinelOption

WithRedisConnectionIdleTimeout sets redis connection idle timeout

func WithRedisConnectionMaxActive

func WithRedisConnectionMaxActive(connectionMaxActive int) SentinelOption

WithRedisConnectionMaxActive sets redis connection max active

func WithRedisConnectionMaxIdle

func WithRedisConnectionMaxIdle(connectionMaxIdle int) SentinelOption

WithRedisConnectionMaxIdle sets redis connection max idle

func WithRedisConnectionWait

func WithRedisConnectionWait(connectionWait bool) SentinelOption

WithRedisConnectionWait sets redis connection wait

func WithRedisDatabase

func WithRedisDatabase(database int) SentinelOption

WithRedisDatabase sets redis database

func WithRedisNetwork

func WithRedisNetwork(network string) SentinelOption

WithRedisNetwork sets redis network

func WithRedisPassword

func WithRedisPassword(password string) SentinelOption

WithRedisPassword sets redis password

func WithRedisReadTimeout

func WithRedisReadTimeout(readTimeout time.Duration) SentinelOption

WithRedisReadTimeout sets redis read timeout

func WithRedisTlsConfig

func WithRedisTlsConfig(tlsConfig *tls.Config) SentinelOption

WithRedisTlsConfig sets redis tls config

func WithRedisTlsSkipVerify

func WithRedisTlsSkipVerify(tlsSkipVerify bool) SentinelOption

WithRedisTlsSkipVerify sets redis tls skip verification

func WithRedisWriteTimeout

func WithRedisWriteTimeout(writeTimeout time.Duration) SentinelOption

WithRedisWriteTimeout sets redis write timeout

func WithSentinelAddresses

func WithSentinelAddresses(addresses []string) SentinelOption

WithSentinelAddresses sets sentinel addresses

func WithSentinelMasterName

func WithSentinelMasterName(masterName string) SentinelOption

WithSentinelMasterName sets sentinel master name

type SentinelSettings

type SentinelSettings struct {
	Addresses             []string
	MasterName            string
	Password              string
	Database              int
	Network               string
	ConnectTimeout        time.Duration
	WriteTimeout          time.Duration
	ReadTimeout           time.Duration
	ConnectionIdleTimeout time.Duration
	ConnectionMaxIdle     int
	ConnectionMaxActive   int
	ConnectionWait        bool
	TlsConfig             *tls.Config
	TlsSkipVerify         bool
}

SentinelSettings contains redis settings

type StorageDetails

type StorageDetails struct {
	Timestamp  time.Time
	Restocking bool
	BestBy     time.Duration
	UseBy      time.Duration
}

StorageDetails contains storage information

type StorageOption

type StorageOption func(*StorageDetails)

StorageOption an option for a storage

func WithDurations

func WithDurations(bestBy time.Duration, useBy time.Duration) StorageOption

WithDurations sets storage best by and use by durations

Directories

Path Synopsis
examples
1 command
2 command
3 command
4 command
5 command
6 command
7 command
8 command
9 command

Jump to

Keyboard shortcuts

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