gopgsession

package module
v0.1.2 Latest Latest
Warning

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

Go to latest
Published: Jul 31, 2024 License: MIT Imports: 13 Imported by: 0

README

go-pg-session

go-pg-session is a distributed session management library that uses PostgreSQL's LISTEN/NOTIFY mechanism to handle session updates across multiple nodes. It leverages the pgln library to quickly recover from disconnections, ensuring robust and reliable session management.

⭐️ Star This Project ⭐️

If you find this project helpful, please give it a star on GitHub! Your support is greatly appreciated.

Features

  • Distributed Session Management: Uses PostgreSQL LISTEN/NOTIFY for real-time session updates.
  • Quick Recovery: Utilizes the pgln library to handle disconnections efficiently.
  • Session Caching: In-memory caching of sessions with LRU eviction policy.
  • Session Expiration: Automatically expires sessions based on configured durations.
  • Periodic Cleanup: Periodically cleans up expired sessions.
  • Efficient Last Access Update: Accumulates last access times and updates them in batches at a predefined interval, reducing performance hits during session retrieval.
  • Highly Configurable: Various settings can be customized via a configuration structure.

Installation

To install the package, run:

go get github.com/tzahifadida/go-pg-session

Usage

Configuration

Create a configuration using the Config struct. You can use the DefaultConfig function to get a default configuration and modify it as needed.

Config Fields
  • MaxSessions: Maximum number of sessions allowed per user.
  • MaxAttributeLength: Maximum length of session attributes.
  • SessionExpiration: Duration after which a session expires.
  • InactivityDuration: Duration of inactivity after which a session expires.
  • CleanupInterval: Interval at which expired sessions are cleaned up.
  • CacheSize: Size of the in-memory cache for sessions.
  • TablePrefix: Prefix for the table names used in the database.
  • SchemaName: Name of the schema used in the database.
  • CreateSchemaIfMissing: Flag to create the schema if it is missing.
  • LastAccessUpdateInterval: Interval for updating the last access time of sessions.
  • LastAccessUpdateBatchSize: Batch size for updating last access times.
cfg := gopgsession.DefaultConfig()
cfg.MaxSessions = 10
cfg.SessionExpiration = 24 * time.Hour // 1 day
cfg.CreateSchemaIfMissing = true
Initialization

Initialize a SessionManager with the configuration and a PostgreSQL connection string.

pgxConnectionString := "postgres://username:password@localhost/dbname?sslmode=disable"
sessionManager, err := gopgsession.NewSessionManager(cfg, pgxConnectionString)
if err != nil {
    log.Fatalf("Failed to initialize session manager: %v", err)
}
Creating a Session

Create a session for a user with initial attributes.

ctx := context.Background()
userID := uuid.New()
attributes := map[string]interface{}{
    "role": "admin",
    "preferences": map[string]string{
        "theme": "dark",
    },
}

sessionID, err := sessionManager.CreateSession(ctx, userID, attributes)
if err != nil {
    log.Fatalf("Failed to create session: %v", err)
}

log.Printf("Created session with ID: %s", sessionID)
Retrieving a Session

Retrieve a session by its ID.

session, err := sessionManager.GetSession(ctx, sessionID, true)
if err != nil {
    log.Fatalf("Failed to retrieve session: %v", err)
}

log.Printf("Retrieved session for user ID: %s", session.UserID)
Updating a Session Attribute

Update an attribute in a session.

err = session.UpdateAttribute("preferences", map[string]string{"theme": "light"})
if err != nil {
    log.Fatalf("Failed to update session attribute: %v", err)
}

err = sessionManager.UpdateSession(ctx, session)
if err != nil {
    log.Fatalf("Failed to update session: %v", err)
}
Deleting a Session

Delete a session by its ID.

err = sessionManager.DeleteSession(ctx, sessionID)
if err != nil {
    log.Fatalf("Failed to delete session: %v", err)
}

log.Printf("Deleted session with ID: %s", sessionID)
Shutdown

Shutdown the session manager gracefully.

ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()

err = sessionManager.Shutdown(ctx)
if err != nil {
    log.Fatalf("Failed to shutdown session manager: %v", err)
}

log.Println("Session manager shutdown successfully")

Exported Functions and Configuration

NewSessionManager

Initializes a new SessionManager with the given configuration and PostgreSQL connection string.

func NewSessionManager(cfg *Config, pgxConnectionString string) (*SessionManager, error)
CreateSession

Creates a new session for the specified user with given attributes.

func (sm *SessionManager) CreateSession(ctx context.Context, userID uuid.UUID, attributes map[string]interface{}) (uuid.UUID, error)
GetSession

Retrieves a session by its ID. Optionally updates the last access time.

func (sm *SessionManager) GetSession(ctx context.Context, sessionID uuid.UUID, updateSessionAccess bool) (*Session, error)
UpdateSession

Updates the session in the database with any changed attributes.

func (sm *SessionManager) UpdateSession(ctx context.Context, session *Session) error
DeleteSession

Deletes a session by its ID.

func (sm *SessionManager) DeleteSession(ctx context.Context, sessionID uuid.UUID) error
Shutdown

Shuts down the session manager gracefully, ensuring all ongoing operations are completed.

func (sm *SessionManager) Shutdown(ctx context.Context) error

Contributing

Contributions are welcome! Feel free to open issues or submit pull requests.

License

This project is licensed under the MIT License.


For more details and examples, please refer to the session_test.go file in the repository.

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type Config

type Config struct {
	// MaxSessions is the maximum number of concurrent sessions allowed per user.
	// When this limit is reached, the oldest session will be removed.
	MaxSessions int `json:"maxSessions"`

	// MaxAttributeLength is the maximum length (in bytes) allowed for a single session attribute value.
	MaxAttributeLength int `json:"maxAttributeLength"`

	// SessionExpiration is the duration after which a session expires if not accessed.
	SessionExpiration time.Duration `json:"sessionExpiration"`

	// InactivityDuration is the duration of inactivity after which a session is considered expired.
	InactivityDuration time.Duration `json:"inactivityDuration"`

	// CleanupInterval is the time interval between cleanup operations for expired sessions.
	CleanupInterval time.Duration `json:"cleanupInterval"`

	// CacheSize is the maximum number of sessions to keep in the in-memory cache.
	CacheSize int `json:"cacheSize"`

	// TablePrefix is the prefix to be used for all database tables created by the SessionManager.
	// This allows multiple SessionManager instances to coexist in the same database.
	TablePrefix string `json:"tablePrefix"`

	// SchemaName is the name of the PostgreSQL schema to use for session tables.
	// If empty, the default schema (usually "public") will be used.
	SchemaName string `json:"schemaName"`

	// CreateSchemaIfMissing, if true, will create the specified schema if it doesn't exist.
	CreateSchemaIfMissing bool `json:"createSchemaIfMissing"`

	// LastAccessUpdateInterval is the time interval between batch updates of session last access times.
	LastAccessUpdateInterval time.Duration `json:"lastAccessUpdateInterval"`

	// LastAccessUpdateBatchSize is the maximum number of sessions to update in a single batch operation.
	LastAccessUpdateBatchSize int `json:"lastAccessUpdateBatchSize"`
}

Config holds the configuration options for the SessionManager.

func DefaultConfig

func DefaultConfig() *Config

DefaultConfig returns a Config struct with default values.

type Session

type Session struct {
	ID           uuid.UUID `db:"id"`
	UserID       uuid.UUID `db:"user_id"`
	LastAccessed time.Time `db:"last_accessed"`
	ExpiresAt    time.Time `db:"expires_at"`
	UpdatedAt    time.Time `db:"updated_at"`
	// contains filtered or unexported fields
}

func (*Session) GetAttribute

func (s *Session) GetAttribute(key string) (interface{}, bool)

GetAttribute returns the value of a specific attribute.

func (*Session) GetAttributes

func (s *Session) GetAttributes() map[string]interface{}

GetAttributes returns all attributes of the session.

func (*Session) UpdateAttribute

func (s *Session) UpdateAttribute(key string, value interface{}) error

UpdateAttribute updates or adds an attribute to the session.

type SessionManager

type SessionManager struct {
	Config *Config
	// contains filtered or unexported fields
}

SessionManager manages sessions in a PostgreSQL database with caching capabilities.

func NewSessionManager

func NewSessionManager(cfg *Config, pgxConnectionString string) (*SessionManager, error)

NewSessionManager creates a new SessionManager with the given configuration and connection string.

func (*SessionManager) CreateSession

func (sm *SessionManager) CreateSession(ctx context.Context, userID uuid.UUID, attributes map[string]interface{}) (uuid.UUID, error)

CreateSession creates a new session for the given user with the provided attributes.

func (*SessionManager) DeleteAllUserSessions

func (sm *SessionManager) DeleteAllUserSessions(ctx context.Context, userID uuid.UUID) error

DeleteAllUserSessions deletes all sessions for a given user.

func (*SessionManager) DeleteSession

func (sm *SessionManager) DeleteSession(ctx context.Context, sessionID uuid.UUID) error

DeleteSession deletes a session by its ID.

func (*SessionManager) GetSession

func (sm *SessionManager) GetSession(ctx context.Context, sessionID uuid.UUID, updateSessionAccess bool) (*Session, error)

GetSession retrieves a session by its ID and optionally updates its last access time.

func (*SessionManager) Shutdown

func (sm *SessionManager) Shutdown(ctx context.Context) error

Shutdown gracefully shuts down the SessionManager.

func (*SessionManager) UpdateSession

func (sm *SessionManager) UpdateSession(ctx context.Context, session *Session) error

UpdateSession updates the session in the database with any changes made to its attributes.

Jump to

Keyboard shortcuts

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