consulstore

package module
v0.0.0-...-5621cd3 Latest Latest
Warning

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

Go to latest
Published: Dec 27, 2022 License: MIT Imports: 4 Imported by: 0

README

consulstore

A Consul based session store for SCS.

Setup

You should follow the instructions to setup a connection, and pass the connection to consulstore.New() to establish the session store.

Example

package main

import (
	"io"
	"net/http"

	"github.com/alexedwards/scs/v2"
	"github.com/alexedwards/scs/consulstore"
	"github.com/hashicorp/consul/api"
)

var sessionManager *scs.SessionManager

func main() {
	// Establish connection to Consul.
	cli, err := api.NewClient(api.DefaultConfig())
	if err != nil {
		log.Fatal(err)
	}

	// Initialize a new session manager and configure it to use consulstore as the session store.
	sessionManager = scs.New()
	sessionManager.Store = consulstore.New(cli)

	mux := http.NewServeMux()
	mux.HandleFunc("/put", putHandler)
	mux.HandleFunc("/get", getHandler)

	http.ListenAndServe(":4000", sessionManager.LoadAndSave(mux))
}

func putHandler(w http.ResponseWriter, r *http.Request) {
	sessionManager.Put(r.Context(), "message", "Hello from a session!")
}

func getHandler(w http.ResponseWriter, r *http.Request) {
	msg := sessionManager.GetString(r.Context(), "message")
	io.WriteString(w, msg)
}

Expired Session Cleanup

Consul uses sessions to apply TTL's to keys in the K/V store with a max-lifetime of 24hrs. To avoid complexities and restrictions this package provides a background 'cleanup' goroutine to delete expired session data. This stops the store from holding on to invalid sessions indefinitely and growing unnecessarily large. By default the cleanup runs every 1 minute. You can change this by using the NewWithOptions() function to initialize your session store. For example:

// Run a cleanup every 5 minutes.
consulstore.NewWithOptions(db, 5*time.Minute, "scs:session:")

// Disable the cleanup goroutine by setting the cleanup interval to zero.
consulstore.NewWithOptions(db, 0, "scs:session:")
Terminating the Cleanup Goroutine

It's rare that the cleanup goroutine needs to be terminated --- it is generally intended to be long-lived and run for the lifetime of your application.

However, there may be occasions when your use of a session store instance is transient. A common example would be using it in a short-lived test function. In this scenario, the cleanup goroutine (which will run forever) will prevent the session store instance from being garbage collected even after the test function has finished. You can prevent this by either disabling the cleanup goroutine altogether (as described above) or by stopping it using the StopCleanup() method. For example:

func TestExample(t *testing.T) {
	cli, err := api.NewClient(api.DefaultConfig())
	if err != nil {
		log.Fatal(err)
	}

	store := consulstore.New(cli)
	defer store.StopCleanup()

	sessionManager = scs.New()
	sessionManager.Store = store

	// Run test...
}

Key Collisions

By default keys are in the form scs:session:<token>. For example:

"scs:session:ZnirGwi2FiLwXeVlP5nD77IpfJZMVr6un9oZu2qtJrg"

Because the token is highly unique, key collisions are not a concern. But if you're configuring multiple session managers, both of which use consulstore, then you may want the keys to have a different prefix depending on which session manager wrote them. You can do this by using the NewWithOptions() method like so:

cli, err := api.NewClient(api.DefaultConfig())
if err != nil {
	log.Fatal(err)
}

sessionManagerOne = scs.New()
sessionManagerOne.Store = consulstore.NewWithOptions(cli, time.Minute, "scs:session:1:")

sessionManagerTwo = scs.New()
sessionManagerTwo.Store = consulstore.NewWithOptions(cli, time.Minute, "scs:session:2:")

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type ConsulStore

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

ConsulStore represents the session store.

func New

func New(client *api.Client) *ConsulStore

New returns a new ConsulStore instance. The client parameter should be a pointer to a Consul client instance.

func NewWithOptions

func NewWithOptions(client *api.Client, cleanupInterval time.Duration, prefix string) *ConsulStore

NewWithOptions returns a new ConsulStore instance. The client parameter should be a pointer to a Consul client instance. The prefix parameter controls the Consul key prefix, which can be used to avoid naming clashes if necessary. The cleanupInterval parameter controls how frequently expired session data is removed by the background cleanup goroutine. Setting it to 0 prevents the cleanup goroutine from running (i.e. expired sessions will not be removed).

func (*ConsulStore) All

func (c *ConsulStore) All() (map[string][]byte, error)

All returns a map containing the token and data for all active (i.e. not expired) sessions in the ConsulStore instance.

func (*ConsulStore) Commit

func (c *ConsulStore) Commit(token string, b []byte, expiry time.Time) error

Commit adds a session token and data to the ConsulStore instance with the given expiry time. If the session token already exists then the data and expiry time are updated.

func (*ConsulStore) Delete

func (c *ConsulStore) Delete(token string) error

Delete removes a session token and corresponding data from the ConsulStore instance.

func (*ConsulStore) Find

func (c *ConsulStore) Find(token string) (b []byte, exists bool, err error)

Find returns the data for a given session token from the ConsulStore instance. If the session token is not found or is expired, the returned exists flag will be set to false.

func (*ConsulStore) StopCleanup

func (c *ConsulStore) StopCleanup()

StopCleanup terminates the background cleanup goroutine for the ConsulStore instance. It's rare to terminate this; generally ConsulStore instances and their cleanup goroutines are intended to be long-lived and run for the lifetime of your application.

There may be occasions though when your use of the ConsulStore is transient. An example is creating a new ConsulStore instance in a test function. In this scenario, the cleanup goroutine (which will run forever) will prevent the ConsulStore object from being garbage collected even after the test function has finished. You can prevent this by manually calling StopCleanup.

Jump to

Keyboard shortcuts

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