Skip to content

Commit

Permalink
redis sessiondb: support more than one driver - builtin redigo(defaul…
Browse files Browse the repository at this point in the history
…t) and radix - rel to: #1328
  • Loading branch information
kataras committed Aug 6, 2019
1 parent aeeff07 commit 7f64919
Show file tree
Hide file tree
Showing 7 changed files with 498 additions and 135 deletions.
10 changes: 9 additions & 1 deletion _examples/sessions/database/redis/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,15 @@ func main() {
Database: "",
Prefix: "",
Delim: "-",
}) // optionally configure the bridge between your redis server.
Driver: redis.Redigo(), // redis.Radix() can be used instead.
})

// optionally configure the underline driver:
// driver := redis.Redigo()
// driver.MaxIdle = ...
// driver.IdleTimeout = ...
// driver.Wait = ...
// redis.Config {Driver: driver}

// close connection when control+C/cmd+C
iris.RegisterOnInterrupt(func() {
Expand Down
1 change: 1 addition & 0 deletions go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@ require (
github.com/kataras/golog v0.0.0-20190624001437-99c81de45f40
github.com/kataras/pio v0.0.0-20190103105442-ea782b38602d // indirect
github.com/mediocregopher/radix/v3 v3.3.0
github.com/gomodule/redigo v1.7.1-0.20190724094224-574c33c3df38
github.com/microcosm-cc/bluemonday v1.0.2
github.com/ryanuber/columnize v2.1.0+incompatible
github.com/iris-contrib/schema v0.0.1
Expand Down
2 changes: 2 additions & 0 deletions go.sum
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,8 @@ github.com/json-iterator/go v1.1.6/go.mod h1:+SdeFBvtyEkXs7REEP0seUULqWtbJapLOCV
github.com/kataras/golog v0.0.0-20190624001437-99c81de45f40/go.mod h1:PcaEvfvhGsqwXZ6S3CgCbmjcp+4UDUh2MIfF2ZEul8M=
github.com/kataras/pio v0.0.0-20190103105442-ea782b38602d/go.mod h1:NV88laa9UiiDuX9AhMbDPkGYSPugBOV6yTZB1l2K9Z0=
github.com/mediocregopher/radix/v3 v3.3.0/go.mod h1:EmfVyvspXz1uZEyPBMyGK+kjWiKQGvsUt6O3Pj+LDCQ=
github.com/gomodule/redigo v1.7.1-0.20190724094224-574c33c3df38 h1:y0Wmhvml7cGnzPa9nocn/fMraMH/lMDdeG+rkx4VgYY=
github.com/gomodule/redigo v1.7.1-0.20190724094224-574c33c3df38/go.mod h1:B4C85qUVwatsJoIUNIfCRsp7qO0iAmpGFZ4EELWSbC4=
github.com/russross/blackfriday v1.5.2/go.mod h1:JO/DiYxRf+HjHt06OyowR9PTA263kcR/rfWxYHBV53g=
github.com/ryanuber/columnize v2.1.0+incompatible/go.mod h1:sm1tb6uqfes/u+d4ooFouqFdy9/2g9QGwK3SQygK0Ts=
gopkg.in/yaml.v2 v2.2.2/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI=
Expand Down
122 changes: 105 additions & 17 deletions sessions/sessiondb/redis/database.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,27 +3,108 @@ package redis
import (
"time"

"github.com/kataras/iris/core/errors"
"github.com/kataras/iris/sessions"

"github.com/kataras/golog"
)

const (
// DefaultRedisNetwork the redis network option, "tcp".
DefaultRedisNetwork = "tcp"
// DefaultRedisAddr the redis address option, "127.0.0.1:6379".
DefaultRedisAddr = "127.0.0.1:6379"
// DefaultRedisTimeout the redis idle timeout option, time.Duration(30) * time.Second
DefaultRedisTimeout = time.Duration(30) * time.Second
// DefaultDelim ths redis delim option, "-".
DefaultDelim = "-"
)

// Config the redis configuration used inside sessions
type Config struct {
// Network protocol. Defaults to "tcp".
Network string
// Addr of the redis server. Defaults to "127.0.0.1:6379".
Addr string
// Password string .If no password then no 'AUTH'. Defaults to "".
Password string
// If Database is empty "" then no 'SELECT'. Defaults to "".
Database string
// MaxActive. Defaults to 10.
MaxActive int
// Timeout for connect, write and read, defaults to 30 seconds, 0 means no timeout.
Timeout time.Duration
// Prefix "myprefix-for-this-website". Defaults to "".
Prefix string
// Delim the delimeter for the keys on the sessiondb. Defaults to "-".
Delim string

// Driver supports `Redigo()` or `Radix()` go clients for redis.
// Configure each driver by the return value of their constructors.
//
// Defaults to `Redigo()`.
Driver Driver
}

// DefaultConfig returns the default configuration for Redis service.
func DefaultConfig() Config {
return Config{
Network: DefaultRedisNetwork,
Addr: DefaultRedisAddr,
Password: "",
Database: "",
MaxActive: 10,
Timeout: DefaultRedisTimeout,
Prefix: "",
Delim: DefaultDelim,
Driver: Redigo(),
}
}

// Database the redis back-end session database for the sessions.
type Database struct {
redis *Service
c Config
}

var _ sessions.Database = (*Database)(nil)

// New returns a new redis database.
func New(cfg ...Config) *Database {
service := newService(cfg...)
if err := service.Connect(); err != nil {
c := DefaultConfig()
if len(cfg) > 0 {
c = cfg[0]

if c.Timeout < 0 {
c.Timeout = DefaultRedisTimeout
}

if c.Network == "" {
c.Network = DefaultRedisNetwork
}

if c.Addr == "" {
c.Addr = DefaultRedisAddr
}

if c.MaxActive == 0 {
c.MaxActive = 10
}

if c.Delim == "" {
c.Delim = DefaultDelim
}

if c.Driver == nil {
c.Driver = Redigo()
}
}

if err := c.Driver.Connect(c); err != nil {
panic(err)
}

db := &Database{redis: service}
_, err := db.redis.PingPong()
db := &Database{c: c}
_, err := db.c.Driver.PingPong()
if err != nil {
golog.Debugf("error connecting to redis: %v", err)
return nil
Expand All @@ -34,17 +115,17 @@ func New(cfg ...Config) *Database {

// Config returns the configuration for the redis server bridge, you can change them.
func (db *Database) Config() *Config {
return db.redis.Config
return &db.c // 6 Aug 2019 - keep that for no breaking change.
}

// Acquire receives a session's lifetime from the database,
// if the return value is LifeTime{} then the session manager sets the life time based on the expiration duration lives in configuration.
func (db *Database) Acquire(sid string, expires time.Duration) sessions.LifeTime {
seconds, hasExpiration, found := db.redis.TTL(sid)
seconds, hasExpiration, found := db.c.Driver.TTL(sid)
if !found {
// fmt.Printf("db.Acquire expires: %s. Seconds: %v\n", expires, expires.Seconds())
// not found, create an entry with ttl and return an empty lifetime, session manager will do its job.
if err := db.redis.Set(sid, sid, int64(expires.Seconds())); err != nil {
if err := db.c.Driver.Set(sid, sid, int64(expires.Seconds())); err != nil {
golog.Debug(err)
}

Expand All @@ -62,11 +143,11 @@ func (db *Database) Acquire(sid string, expires time.Duration) sessions.LifeTime
// OnUpdateExpiration will re-set the database's session's entry ttl.
// https://redis.io/commands/expire#refreshing-expires
func (db *Database) OnUpdateExpiration(sid string, newExpires time.Duration) error {
return db.redis.UpdateTTLMany(sid, int64(newExpires.Seconds()))
return db.c.Driver.UpdateTTLMany(sid, int64(newExpires.Seconds()))
}

func (db *Database) makeKey(sid, key string) string {
return sid + db.redis.Config.Delim + key
return sid + db.c.Delim + key
}

// Set sets a key value of a specific session.
Expand All @@ -80,7 +161,7 @@ func (db *Database) Set(sid string, lifetime sessions.LifeTime, key string, valu

// fmt.Println("database.Set")
// fmt.Printf("lifetime.DurationUntilExpiration(): %s. Seconds: %v\n", lifetime.DurationUntilExpiration(), lifetime.DurationUntilExpiration().Seconds())
if err = db.redis.Set(db.makeKey(sid, key), valueBytes, int64(lifetime.DurationUntilExpiration().Seconds())); err != nil {
if err = db.c.Driver.Set(db.makeKey(sid, key), valueBytes, int64(lifetime.DurationUntilExpiration().Seconds())); err != nil {
golog.Debug(err)
}
}
Expand All @@ -92,7 +173,7 @@ func (db *Database) Get(sid string, key string) (value interface{}) {
}

func (db *Database) get(key string, outPtr interface{}) {
data, err := db.redis.Get(key)
data, err := db.c.Driver.Get(key)
if err != nil {
// not found.
return
Expand All @@ -104,7 +185,7 @@ func (db *Database) get(key string, outPtr interface{}) {
}

func (db *Database) keys(sid string) []string {
keys, err := db.redis.GetKeys(sid)
keys, err := db.c.Driver.GetKeys(sid)
if err != nil {
golog.Debugf("unable to get all redis keys of session '%s': %v", sid, err)
return nil
Expand All @@ -130,7 +211,7 @@ func (db *Database) Len(sid string) (n int) {

// Delete removes a session key value based on its key.
func (db *Database) Delete(sid string, key string) (deleted bool) {
err := db.redis.Delete(db.makeKey(sid, key))
err := db.c.Driver.Delete(db.makeKey(sid, key))
if err != nil {
golog.Error(err)
}
Expand All @@ -141,7 +222,7 @@ func (db *Database) Delete(sid string, key string) (deleted bool) {
func (db *Database) Clear(sid string) {
keys := db.keys(sid)
for _, key := range keys {
if err := db.redis.Delete(key); err != nil {
if err := db.c.Driver.Delete(key); err != nil {
golog.Debugf("unable to delete session '%s' value of key: '%s': %v", sid, key, err)
}
}
Expand All @@ -153,7 +234,7 @@ func (db *Database) Release(sid string) {
// clear all $sid-$key.
db.Clear(sid)
// and remove the $sid.
db.redis.Delete(sid)
db.c.Driver.Delete(sid)
}

// Close terminates the redis connection.
Expand All @@ -162,5 +243,12 @@ func (db *Database) Close() error {
}

func closeDB(db *Database) error {
return db.redis.CloseConnection()
return db.c.Driver.CloseConnection()
}

var (
// ErrRedisClosed an error with message 'Redis is already closed'
ErrRedisClosed = errors.New("Redis is already closed")
// ErrKeyNotFound an error with message 'Key $thekey doesn't found'
ErrKeyNotFound = errors.New("Key '%s' doesn't found")
)
34 changes: 34 additions & 0 deletions sessions/sessiondb/redis/driver.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
package redis

// Driver is the interface which each supported redis client
// should support in order to be used in the redis session database.
type Driver interface {
Connect(c Config) error
PingPong() (bool, error)
CloseConnection() error
Set(key string, value interface{}, secondsLifetime int64) error
Get(key string) (interface{}, error)
TTL(key string) (seconds int64, hasExpiration bool, found bool)
UpdateTTL(key string, newSecondsLifeTime int64) error
UpdateTTLMany(prefix string, newSecondsLifeTime int64) error
GetAll() (interface{}, error)
GetKeys(prefix string) ([]string, error)
Delete(key string) error
}

var (
_ Driver = (*RedigoDriver)(nil)
_ Driver = (*RadixDriver)(nil)
)

// Redigo returns the driver for the redigo go redis client.
// Which is the default one.
// You can customize further any specific driver's properties.
func Redigo() *RedigoDriver {
return &RedigoDriver{}
}

// Radix returns the driver for the radix go redis client.
func Radix() *RadixDriver {
return &RadixDriver{}
}
Loading

0 comments on commit 7f64919

Please sign in to comment.