Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: [#493] optimize session #644

Merged
merged 15 commits into from
Sep 16, 2024
2 changes: 1 addition & 1 deletion contracts/session/manager.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ package session

type Manager interface {
// BuildSession constructs a new session with the given handler and session ID.
BuildSession(handler Driver, sessionID ...string) Session
BuildSession(handler Driver, sessionID ...string) (Session, error)
// Driver retrieves the session driver by name.
Driver(name ...string) (Driver, error)
// Extend extends the session manager with a custom driver.
Expand Down
2 changes: 2 additions & 0 deletions contracts/session/session.go
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,8 @@ type Session interface {
Remove(key string) any
// Save saves the session.
Save() error
// SetDriver sets the session driver
SetDriver(driver Driver) Session
// SetID sets the ID of the session.
SetID(id string) Session
// SetName sets the name of the session.
Expand Down
20 changes: 15 additions & 5 deletions mocks/session/Manager.go

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

48 changes: 48 additions & 0 deletions mocks/session/Session.go

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

7 changes: 7 additions & 0 deletions session/errors.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
package session

import "errors"

var (
ErrDriverNotSet = errors.New("session driver is not set")
)
37 changes: 19 additions & 18 deletions session/manager.go
Original file line number Diff line number Diff line change
Expand Up @@ -25,36 +25,30 @@ func NewManager(config config.Config, json foundation.Json) *Manager {
drivers: make(map[string]sessioncontract.Driver),
json: json,
sessionPool: sync.Pool{New: func() any {
return &Session{
attributes: make(map[string]any),
}
return NewSession("", nil, json)
},
},
}
manager.extendDefaultDrivers()
return manager
}

func (m *Manager) AcquireSession() *Session {
session := m.sessionPool.Get().(*Session)
return session
}

func (m *Manager) BuildSession(handler sessioncontract.Driver, sessionID ...string) sessioncontract.Session {
func (m *Manager) BuildSession(handler sessioncontract.Driver, sessionID ...string) (sessioncontract.Session, error) {
if handler == nil {
panic("session driver cannot be nil")
return nil, ErrDriverNotSet
}
session := m.AcquireSession()
session.setDriver(handler)
session.setJson(m.json)
session.SetName(m.config.GetString("session.cookie"))

session := m.acquireSession()
session.SetDriver(handler).
SetName(m.config.GetString("session.cookie"))

if len(sessionID) > 0 {
session.SetID(sessionID[0])
} else {
session.SetID("")
}

return session
return session, nil
}

func (m *Manager) Driver(name ...string) (sessioncontract.Driver, error) {
Expand Down Expand Up @@ -86,9 +80,16 @@ func (m *Manager) Extend(driver string, handler func() sessioncontract.Driver) e
}

func (m *Manager) ReleaseSession(session sessioncontract.Session) {
s := session.(*Session)
s.reset()
m.sessionPool.Put(s)
session.Flush().
SetDriver(nil).
SetName("").
SetID("")
m.sessionPool.Put(session)
}

func (m *Manager) acquireSession() sessioncontract.Session {
session := m.sessionPool.Get().(sessioncontract.Session)
return session
}

func (m *Manager) getDefaultDriver() string {
Expand Down
19 changes: 18 additions & 1 deletion session/manager_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -85,6 +85,10 @@ func (s *ManagerTestSuite) TestExtend() {
s.Nil(err)
s.NotNil(driver)
s.Equal("*session.CustomDriver", fmt.Sprintf("%T", driver))

// driver already exists
err = s.manager.Extend("test", NewCustomDriver)
s.Errorf(err, "driver [%s] already exists", "test")
}

func (s *ManagerTestSuite) TestBuildSession() {
Expand All @@ -94,9 +98,22 @@ func (s *ManagerTestSuite) TestBuildSession() {
s.Equal("*driver.File", fmt.Sprintf("%T", driver))

s.mockConfig.On("GetString", "session.cookie").Return("test_cookie").Once()
session := s.manager.BuildSession(driver)
session, err := s.manager.BuildSession(driver)
session.Put("name", "goravel")

s.Nil(err)
s.NotNil(session)
s.Equal("test_cookie", session.GetName())
s.Equal("goravel", session.Get("name"))

s.manager.ReleaseSession(session)
s.Empty(session.GetName())
s.Empty(session.All())

// driver is nil
session, err = s.manager.BuildSession(nil)
s.ErrorIs(err, ErrDriverNotSet)
s.Nil(session)
}

func (s *ManagerTestSuite) TestGetDefaultDriver() {
Expand Down
8 changes: 7 additions & 1 deletion session/middleware/start_session.go
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,13 @@
}

// Build session
s := session.SessionFacade.BuildSession(driver)
s, err := session.SessionFacade.BuildSession(driver)
if err != nil {
color.Red().Println(err)
req.Next()
return

Check warning on line 33 in session/middleware/start_session.go

View check run for this annotation

Codecov / codecov/patch

session/middleware/start_session.go#L31-L33

Added lines #L31 - L33 were not covered by tests
}

s.SetID(req.Cookie(s.GetName()))

// Start session
Expand Down
47 changes: 29 additions & 18 deletions session/session.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@

"github.com/goravel/framework/contracts/foundation"
sessioncontract "github.com/goravel/framework/contracts/session"
"github.com/goravel/framework/support/color"
supportmaps "github.com/goravel/framework/support/maps"
"github.com/goravel/framework/support/str"
)
Expand Down Expand Up @@ -155,6 +156,10 @@
return err
}

if err = s.validateDriver(); err != nil {
return err
}

if err = s.driver.Write(s.GetID(), string(data)); err != nil {
return err
}
Expand All @@ -164,6 +169,11 @@
return nil
}

func (s *Session) SetDriver(driver sessioncontract.Driver) sessioncontract.Session {
s.driver = driver
return s
}

func (s *Session) SetID(id string) sessioncontract.Session {
if s.isValidID(id) {
s.id = id
Expand Down Expand Up @@ -210,15 +220,25 @@
}
}

func (s *Session) validateDriver() error {
if s.driver == nil {
return ErrDriverNotSet
}
return nil
}

func (s *Session) migrate(destroy ...bool) error {
shouldDestroy := false
if len(destroy) > 0 {
shouldDestroy = destroy[0]
}

if shouldDestroy {
err := s.driver.Destroy(s.GetID())
if err != nil {
if err := s.validateDriver(); err != nil {
return err
}

if err := s.driver.Destroy(s.GetID()); err != nil {
return err
}
}
Expand All @@ -229,12 +249,19 @@
}

func (s *Session) readFromHandler() map[string]any {
if err := s.validateDriver(); err != nil {
color.Red().Println(err)
return nil

Check warning on line 254 in session/session.go

View check run for this annotation

Codecov / codecov/patch

session/session.go#L253-L254

Added lines #L253 - L254 were not covered by tests
}

value, err := s.driver.Read(s.GetID())
if err != nil {
color.Red().Println(err)
return nil
}
var data map[string]any
if err := s.json.Unmarshal([]byte(value), &data); err != nil {
color.Red().Println(err)
return nil
}
return data
Expand Down Expand Up @@ -272,22 +299,6 @@
s.Put("_flash.old", old)
}

func (s *Session) reset() {
s.id = ""
s.name = ""
s.attributes = make(map[string]any)
s.driver = nil
s.started = false
}

func (s *Session) setDriver(driver sessioncontract.Driver) {
s.driver = driver
}

func (s *Session) setJson(json foundation.Json) {
s.json = json
}

// toStringSlice converts an interface slice to a string slice.
func toStringSlice(anySlice []any) []string {
strSlice := make([]string, len(anySlice))
Expand Down
8 changes: 8 additions & 0 deletions session/session_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -162,6 +162,10 @@ func (s *SessionTestSuite) TestMigrate() {
s.driver.On("Destroy", oldID).Return(nil).Once()
s.Nil(s.session.migrate(true))
s.NotEqual(oldID, s.session.GetID())

// when driver is nil
s.session.SetDriver(nil)
s.ErrorIs(s.session.migrate(true), ErrDriverNotSet)
}

func (s *SessionTestSuite) TestMissing() {
Expand Down Expand Up @@ -297,6 +301,10 @@ func (s *SessionTestSuite) TestSave() {

s.Equal(errors.New("error"), s.session.Save())
s.True(s.session.started)

// when driver is nil
s.session.SetDriver(nil)
s.ErrorIs(s.session.Save(), ErrDriverNotSet)
}

func (s *SessionTestSuite) TestSetID() {
Expand Down
Loading