mnemo

package module
v0.0.1-beta.4 Latest Latest
Warning

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

Go to latest
Published: Jan 17, 2024 License: MIT Imports: 14 Imported by: 1

README

Mnemo

Check out the documentation here: https://pkg.go.dev/github.com/kitkitchen/mnemo

Documentation

Overview

Package mnemo provides a simple and robust way to generate and manage caches for any data type.

Example
// Create some keys for stores, caches, and commands
var (
	ExampleStoreKey StoreKey   = "example_store"
	ExampleCacheKey CacheKey   = "example_cache"
	ExampleCmdKey   CommandKey = "example_cmd"
)

m := New()
// Add optional configuration for one server per instance
// Instances do not require a server to access stores, caches, or commands
// However, a server is required to access the Mnemo API with a client
m.WithServer("example", WithPattern("/example"), WithPort(8080))

// Create a new store
store, _ := NewStore(ExampleStoreKey)

// Add commands to the store
cmd := store.Commands()
cmd.Assign(map[CommandKey]func(){
	ExampleCmdKey: func() {
		fmt.Println("I'm a command!")
	},
})

// Create a type to cache
type Message struct {
	Msg string
}

// Create a new cache for messages
cache, _ := NewCache[Message](ExampleStoreKey, ExampleCacheKey)

// Cache a message
cache.Cache(ExampleCacheKey, &Message{Msg: "Hello, Mnemo!"})

// Set a reducer for the cache
// A reducer is a function that takes the current state of the cache and returns a mutation
// The mutation is then cached and sent to the reducer's feed channel
cache.SetReducer(func(state Message) (mutation any) {
	return state.Msg + " With a reducer!"
})

// The integrity of the original cache is maintained and stored by it's creation time
_ = cache.RawHistory()

// Add store(s) by key
// This can be done at any time, however, it is recommended to do so before attempting to access the store
// Unique stores may only be added to one instance of Mnemo, although you may have multiple instances
m.WithStores(ExampleStoreKey)

// Access stores or caches by key from anywhere in the application
myStore, _ := UseStore(ExampleStoreKey)

// Access and execute commands from anywhere
myCmds := myStore.Commands()
myCmds.Execute(ExampleCmdKey)

// List commands if needed
_ = myCmds.List()

// Access caches from anywhere
myCache, _ := UseCache[Message](ExampleStoreKey, ExampleCacheKey)

// Access data from the cache
item, _ := myCache.Get(ExampleCacheKey)
fmt.Println(item.Data.Msg)

// Update the cache
myCache.Update(ExampleCacheKey, Message{Msg: "Hello, Mnemo! With an update!"})

// Server is a wrapper around http.Server and is non-blocking
m.Server().ListenAndServe()
Output:

I'm a command!
Hello, Mnemo! With a reducer!

Index

Examples

Constants

This section is empty.

Variables

This section is empty.

Functions

func NewCache

func NewCache[Cache any](s StoreKey, c CacheKey) (*cache[Cache], error)

NewCache creates a new cache or returns an error if a cache with the same key already exists.

func NewCacheTimeoutConfig

func NewCacheTimeoutConfig[T any](
	data *T,
	key interface{},
	timeoutFun func(data *T),
	timeout time.Duration,
) cacheTimeoutConfig[T]

NewCacheTimeoutConfig creates a new cacheTimeoutConfig. TODO: Convert to option

func UseCache

func UseCache[Cache any](s StoreKey, c CacheKey) (*cache[Cache], error)

UseCache returns a cache by key or an error if the cache does not exist.

Types

type CacheKey

type CacheKey any

CacheKey is a unique identifier for a cache.

type CommandKey

type CommandKey string

CommandKey is a unique identifier for a command.

type Commands

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

Commands is a collection of commands.

func NewCommands

func NewCommands() Commands

NewCommands creates a new collection of commands.

func (*Commands) Assign

func (c *Commands) Assign(cmds map[CommandKey]func())

Assign assigns a map of commands to the collection.

func (*Commands) Execute

func (c *Commands) Execute(key CommandKey) error

Execute executes a command and returns an error if the command does not exist.

func (*Commands) List

func (c *Commands) List() map[CommandKey]func()

type Conn

type Conn struct {
	Pool     *Pool
	Key      interface{}
	Messages chan interface{}
	// contains filtered or unexported fields
}

Conn is a websocket connection with a unique key, a pointer to a pool, and a channel for messages.

func NewConn

func NewConn(w http.ResponseWriter, r *http.Request) (*Conn, error)

NewConn upgrades an http connection to a websocket connection and returns a Conn or an error if the upgrade fails.

func (*Conn) Close

func (c *Conn) Close() error

Close closes the websocket connection and removes the Conn from the pool. It returns an error if the Conn is nil.

func (*Conn) Listen

func (c *Conn) Listen()

Listen listens for messages on the Conn's Messages channel and writes them to the websocket connection.

func (*Conn) Publish

func (c *Conn) Publish(msg interface{})

Publish publishes a message to the Conn's Messages channel.

type Error

type Error[T any] struct {
	Err    error
	Status int
	Logger Logger
	// contains filtered or unexported fields
}

Error is a generic error type for the Mnemo package.

func IsErrorType

func IsErrorType[T any](err error) (Error[T], bool)

IsErrorType reflects Error[T] from an error.

func NewError

func NewError[T any](msg string, opts ...Opt[Error[T]]) Error[T]

NewError returns a new Error instance with a logger

func (Error[T]) Error

func (e Error[T]) Error() string

Error implements the error interface.

func (Error[T]) IsStatusError

func (e Error[T]) IsStatusError() bool

IsStatusError returns true if the error has a status code.

func (Error[T]) Log

func (e Error[T]) Log()

Log logs the error by level.

func (Error[T]) Type

func (e Error[T]) Type() string

func (Error[T]) WithLogLevel

func (e Error[T]) WithLogLevel(level LogLevel) Error[T]

WithLogLevel sets the log level for the error.

func (Error[T]) WithStatus

func (e Error[T]) WithStatus(status int) Error[T]

WithStatus sets the status code for the error.

type Item

type Item[T any] struct {
	CreatedAt time.Time `json:"created_at"`
	Data      *T        `json:"data"`
}

Item holds cached data and the time it was cached.

type LogLevel

type LogLevel int
const (
	Err LogLevel = iota
	Debug
	Info
	Warn
	Fatal
	Panic
)

type Logger

type Logger interface {
	Info(string)
	Debug(string)
	Warn(string)
	Error(string)
	Fatal(string)
}

type Mnemo

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

Mnemo is the main struct for the Mnemo package.

func New

func New(opts ...Opt[Mnemo]) *Mnemo

New returns a new Mnemo instance.

func (*Mnemo) DetachStore

func (m *Mnemo) DetachStore(key StoreKey)

func (*Mnemo) Server

func (m *Mnemo) Server() *Server

Server returns the Mnemo instance's server or panics if the server is nil.

func (*Mnemo) StoreKeys

func (m *Mnemo) StoreKeys() map[StoreKey]bool

func (*Mnemo) UseStore

func (m *Mnemo) UseStore(key StoreKey) (*Store, error)

UseStore returns a store from the Mnemo instance.

Returns an error if the store does not exist or does not belong to the Mnemo instance.

func (*Mnemo) WithServer

func (m *Mnemo) WithServer(key string, opts ...Opt[Server]) *Mnemo

WithServer creates a server for the Mnemo instance.

func (*Mnemo) WithStores

func (m *Mnemo) WithStores(keys ...StoreKey) *Mnemo

WithStore adds one or more stores to the Mnemo instance.

type Opt

type Opt[T any] func(t *T)

func WithPattern

func WithPattern(pattern string) Opt[Server]

WithPattern sets the pattern for the server's http handler.

func WithPort

func WithPort(port int) Opt[Server]

WithPort sets the port for the server.

func WithSilence

func WithSilence() Opt[Server]

WithSilence silences the server's http error log.

type Pool

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

Pool is a collection of Conns

func NewPool

func NewPool() *Pool

NewPool creates a new pool of Conns

func (*Pool) AddConn

func (p *Pool) AddConn(c *Conn) error

AddConn adds a Conn to the pool

func (*Pool) Close

func (p *Pool) Close()

func (*Pool) Conns

func (p *Pool) Conns() map[interface{}]*Conn

Conns returns a map of the pool's Conns

type ReducerFunc

type ReducerFunc[T any, U any] func(state T) (mutation U)

ReducerFunc is a function that takes a cache and returns a reduced version of it.

It is run against the raw cache on every change and must return json serializable data.

type Server

type Server struct {
	context.Context
	// contains filtered or unexported fields
}

Server is a websocket server that manages connections and messages.

func NewServer

func NewServer(key string, opts ...Opt[Server]) (*Server, error)

NewServer creates a new server.

The server's key must be unique. If a server with the same key already exists, an error is returned.

func (*Server) HandleSubscribe

func (s *Server) HandleSubscribe(w http.ResponseWriter, r *http.Request)

HandleSubscribe upgrades the http connection to a websocket connection and adds the connection to the connection pool.

func (*Server) ListenAndServe

func (s *Server) ListenAndServe()

ListenAndServe starts the server in a go routine

func (*Server) Publish

func (s *Server) Publish(msg interface{})

Publish publishes a message to all connections in the connection pool.

func (*Server) SetOnNewConnection

func (s *Server) SetOnNewConnection(fn func(c *Conn))

SetOnNewConnection sets a user defined call back function when a new connection is established.

Mnemo must be initialized with a server before calling this method.

func (*Server) Shutdown

func (s *Server) Shutdown() error

Shutdown gracefully shuts down the server

type Store

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

Store is a collection of caches.

func NewStore

func NewStore(key StoreKey, opts ...Opt[Store]) (*Store, error)

NewStore creates a new store or returns an error if a store with the same key already exists.

func UseStore

func UseStore(key StoreKey) (*Store, error)

UseStore returns a store by key or an error if the store does not exist.

func (*Store) Commands

func (s *Store) Commands() *Commands

func (*Store) Key

func (s *Store) Key() StoreKey

Key returns the store's key.

func (*Store) Mnemo

func (s *Store) Mnemo() *Mnemo

type StoreKey

type StoreKey string

StoreKey is a unique identifier for a store.

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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