mirror of
https://github.com/kataras/iris.git
synced 2026-01-23 11:56:00 +00:00
Sessions are now in full sync with the registered database, on acquire(init), set, get, delete, clear, visit, len, release(destroy) as requested by almost everyone. https://github.com/kataras/iris/issues/969
Former-commit-id: 49fcdb93106a78f0a24ad3fb4d8725e35e98451a
This commit is contained in:
@@ -14,9 +14,17 @@ type Database struct {
|
||||
redis *service.Service
|
||||
}
|
||||
|
||||
var _ sessions.Database = (*Database)(nil)
|
||||
|
||||
// New returns a new redis database.
|
||||
func New(cfg ...service.Config) *Database {
|
||||
db := &Database{redis: service.New(cfg...)}
|
||||
db.redis.Connect()
|
||||
_, err := db.redis.PingPong()
|
||||
if err != nil {
|
||||
golog.Debugf("error connecting to redis: %v", err)
|
||||
return nil
|
||||
}
|
||||
runtime.SetFinalizer(db, closeDB)
|
||||
return db
|
||||
}
|
||||
@@ -26,73 +34,119 @@ func (db *Database) Config() *service.Config {
|
||||
return db.redis.Config
|
||||
}
|
||||
|
||||
// Async is DEPRECATED
|
||||
// if it was true then it could use different to update the back-end storage, now it does nothing.
|
||||
func (db *Database) Async(useGoRoutines bool) *Database {
|
||||
return db
|
||||
// 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)
|
||||
if !found {
|
||||
// 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 {
|
||||
golog.Debug(err)
|
||||
}
|
||||
|
||||
return sessions.LifeTime{} // session manager will handle the rest.
|
||||
}
|
||||
|
||||
if !hasExpiration {
|
||||
return sessions.LifeTime{}
|
||||
|
||||
}
|
||||
|
||||
return sessions.LifeTime{Time: time.Now().Add(time.Duration(seconds) * time.Second)}
|
||||
}
|
||||
|
||||
// Load loads the values to the underline.
|
||||
func (db *Database) Load(sid string) (storeDB sessions.RemoteStore) {
|
||||
// values := make(map[string]interface{})
|
||||
const delim = "_"
|
||||
|
||||
if !db.redis.Connected { //yes, check every first time's session for valid redis connection
|
||||
db.redis.Connect()
|
||||
_, err := db.redis.PingPong()
|
||||
if err != nil {
|
||||
golog.Errorf("redis database error on connect: %v", err)
|
||||
return
|
||||
}
|
||||
func makeKey(sid, key string) string {
|
||||
return sid + delim + key
|
||||
}
|
||||
|
||||
// Set sets a key value of a specific session.
|
||||
// Ignore the "immutable".
|
||||
func (db *Database) Set(sid string, lifetime sessions.LifeTime, key string, value interface{}, immutable bool) {
|
||||
valueBytes, err := sessions.DefaultTranscoder.Marshal(value)
|
||||
if err != nil {
|
||||
golog.Error(err)
|
||||
return
|
||||
}
|
||||
|
||||
// fetch the values from this session id and copy-> store them
|
||||
storeMaybe, err := db.redis.Get(sid)
|
||||
// exists
|
||||
if err == nil {
|
||||
storeB, ok := storeMaybe.([]byte)
|
||||
if !ok {
|
||||
golog.Errorf("something wrong, store should be stored as []byte but stored as %#v", storeMaybe)
|
||||
return
|
||||
}
|
||||
|
||||
storeDB, err = sessions.DecodeRemoteStore(storeB) // decode the whole value, as a remote store
|
||||
if err != nil {
|
||||
golog.Errorf(`error while trying to load session values(%s) from redis:
|
||||
the retrieved value is not a sessions.RemoteStore type, please report that as bug, that should never occur: %v`,
|
||||
sid, err)
|
||||
}
|
||||
if err = db.redis.Set(makeKey(sid, key), valueBytes, int64(lifetime.DurationUntilExpiration().Seconds())); err != nil {
|
||||
golog.Debug(err)
|
||||
}
|
||||
}
|
||||
|
||||
// Get retrieves a session value based on the key.
|
||||
func (db *Database) Get(sid string, key string) (value interface{}) {
|
||||
db.get(makeKey(sid, key), &value)
|
||||
return
|
||||
}
|
||||
|
||||
// Sync syncs the database.
|
||||
func (db *Database) Sync(p sessions.SyncPayload) {
|
||||
db.sync(p)
|
||||
}
|
||||
|
||||
func (db *Database) sync(p sessions.SyncPayload) {
|
||||
if p.Action == sessions.ActionDestroy {
|
||||
db.redis.Delete(p.SessionID)
|
||||
return
|
||||
}
|
||||
storeB, err := p.Store.Serialize()
|
||||
func (db *Database) get(key string, outPtr interface{}) {
|
||||
data, err := db.redis.Get(key)
|
||||
if err != nil {
|
||||
golog.Error("error while encoding the remote session store")
|
||||
// not found.
|
||||
return
|
||||
}
|
||||
|
||||
// not expire if zero
|
||||
seconds := 0
|
||||
|
||||
if lifetime := p.Store.Lifetime; !lifetime.IsZero() {
|
||||
seconds = int(lifetime.Sub(time.Now()).Seconds())
|
||||
if err = sessions.DefaultTranscoder.Unmarshal(data.([]byte), outPtr); err != nil {
|
||||
golog.Debugf("unable to unmarshal value of key: '%s': %v", key, err)
|
||||
}
|
||||
|
||||
db.redis.Set(p.SessionID, storeB, seconds)
|
||||
}
|
||||
|
||||
// Close shutdowns the redis connection.
|
||||
func (db *Database) keys(sid string) []string {
|
||||
keys, err := db.redis.GetKeys(sid + delim)
|
||||
if err != nil {
|
||||
golog.Debugf("unable to get all redis keys of session '%s': %v", sid, err)
|
||||
return nil
|
||||
}
|
||||
|
||||
return keys
|
||||
}
|
||||
|
||||
// Visit loops through all session keys and values.
|
||||
func (db *Database) Visit(sid string, cb func(key string, value interface{})) {
|
||||
keys := db.keys(sid)
|
||||
for _, key := range keys {
|
||||
var value interface{} // new value each time, we don't know what user will do in "cb".
|
||||
db.get(key, &value)
|
||||
cb(key, value)
|
||||
}
|
||||
}
|
||||
|
||||
// Len returns the length of the session's entries (keys).
|
||||
func (db *Database) Len(sid string) (n int) {
|
||||
return len(db.keys(sid))
|
||||
}
|
||||
|
||||
// Delete removes a session key value based on its key.
|
||||
func (db *Database) Delete(sid string, key string) (deleted bool) {
|
||||
err := db.redis.Delete(makeKey(sid, key))
|
||||
if err != nil {
|
||||
golog.Error(err)
|
||||
}
|
||||
return err == nil
|
||||
}
|
||||
|
||||
// Clear removes all session key values but it keeps the session entry.
|
||||
func (db *Database) Clear(sid string) {
|
||||
keys := db.keys(sid)
|
||||
for _, key := range keys {
|
||||
if err := db.redis.Delete(key); err != nil {
|
||||
golog.Debugf("unable to delete session '%s' value of key: '%s': %v", sid, key, err)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Release destroys the session, it clears and removes the session entry,
|
||||
// session manager will create a new session ID on the next request after this call.
|
||||
func (db *Database) Release(sid string) {
|
||||
// clear all $sid-$key.
|
||||
db.Clear(sid)
|
||||
// and remove the $sid.
|
||||
db.redis.Delete(sid)
|
||||
}
|
||||
|
||||
// Close terminates the redis connection.
|
||||
func (db *Database) Close() error {
|
||||
return closeDB(db)
|
||||
}
|
||||
|
||||
@@ -1,9 +1,10 @@
|
||||
package service
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"time"
|
||||
|
||||
"github.com/garyburd/redigo/redis"
|
||||
"github.com/gomodule/redigo/redis"
|
||||
"github.com/kataras/iris/core/errors"
|
||||
)
|
||||
|
||||
@@ -44,7 +45,7 @@ func (r *Service) CloseConnection() error {
|
||||
|
||||
// Set sets a key-value to the redis store.
|
||||
// The expiration is setted by the MaxAgeSeconds.
|
||||
func (r *Service) Set(key string, value interface{}, secondsLifetime int) (err error) {
|
||||
func (r *Service) Set(key string, value interface{}, secondsLifetime int64) (err error) {
|
||||
c := r.pool.Get()
|
||||
defer c.Close()
|
||||
if c.Err() != nil {
|
||||
@@ -81,6 +82,23 @@ func (r *Service) Get(key string) (interface{}, error) {
|
||||
return redisVal, nil
|
||||
}
|
||||
|
||||
// TTL returns the seconds to expire, if the key has expiration and error if action failed.
|
||||
// Read more at: https://redis.io/commands/ttl
|
||||
func (r *Service) TTL(key string) (seconds int64, hasExpiration bool, ok bool) {
|
||||
c := r.pool.Get()
|
||||
defer c.Close()
|
||||
redisVal, err := c.Do("TTL", r.Config.Prefix+key)
|
||||
if err != nil {
|
||||
return -2, false, false
|
||||
}
|
||||
seconds = redisVal.(int64)
|
||||
// if -1 means the key has unlimited life time.
|
||||
hasExpiration = seconds == -1
|
||||
// if -2 means key does not exist.
|
||||
ok = (c.Err() != nil || seconds == -2)
|
||||
return
|
||||
}
|
||||
|
||||
// GetAll returns all redis entries using the "SCAN" command (2.8+).
|
||||
func (r *Service) GetAll() (interface{}, error) {
|
||||
c := r.pool.Get()
|
||||
@@ -102,6 +120,48 @@ func (r *Service) GetAll() (interface{}, error) {
|
||||
return redisVal, nil
|
||||
}
|
||||
|
||||
// GetKeys returns all redis keys using the "SCAN" with MATCH command.
|
||||
// Read more at: https://redis.io/commands/scan#the-match-option.
|
||||
func (r *Service) GetKeys(prefix string) ([]string, error) {
|
||||
c := r.pool.Get()
|
||||
defer c.Close()
|
||||
if err := c.Err(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
if err := c.Send("SCAN", 0, "MATCH", r.Config.Prefix+prefix+"*", "COUNT", 9999999999); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
if err := c.Flush(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
reply, err := c.Receive()
|
||||
if err != nil || reply == nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
// it returns []interface, with two entries, the first one is "0" and the second one is a slice of the keys as []interface{uint8....}.
|
||||
|
||||
if keysInterface, ok := reply.([]interface{}); ok {
|
||||
if len(keysInterface) == 2 {
|
||||
// take the second, it must contain the slice of keys.
|
||||
if keysSliceAsBytes, ok := keysInterface[1].([]interface{}); ok {
|
||||
keys := make([]string, len(keysSliceAsBytes), len(keysSliceAsBytes))
|
||||
for i, k := range keysSliceAsBytes {
|
||||
keys[i] = fmt.Sprintf("%s", k)
|
||||
}
|
||||
|
||||
return keys, nil
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
return nil, nil
|
||||
}
|
||||
|
||||
// GetBytes returns value, err by its key
|
||||
// you can use utils.Deserialize((.GetBytes("yourkey"),&theobject{})
|
||||
//returns nil and a filled error if something wrong happens
|
||||
|
||||
Reference in New Issue
Block a user