some-automoderation/sessions/sessions_manager.go

71 lines
1.7 KiB
Go

package sessions
import (
"context"
"fmt"
"log"
"math/rand"
"github.com/redis/go-redis/v9"
)
type SessionData struct {
SessionId int `redis:"session_id"`
RoomId string `redis:"room_id"`
PersonId int `redis:"person_id"`
}
type SessionManagement interface {
Get(sessionId int) SessionData
Save(roomName string, personId int) (int, error)
}
var ctx = context.Background()
const sessionPrefix = "session"
func sessionIdToKey(sessionId int) string {
return fmt.Sprintf("%s:%d", sessionPrefix, sessionId)
}
type RedisSM struct {
Rdb *redis.Client
}
func (redisSM RedisSM) Get(sessionId int) SessionData {
var foundSession SessionData
redisKey := sessionIdToKey(sessionId)
err := redisSM.Rdb.HGetAll(ctx, redisKey).Scan(&foundSession)
if err != nil {
log.Printf("> error reading %s : %s", redisKey, err)
return SessionData{}
}
log.Printf("> successfully found %d %+v", sessionId, foundSession)
return foundSession
}
func (redisSM RedisSM) Save(roomName string, personId int) (int, error) {
randId := rand.Int()
newSession := SessionData{
SessionId: randId,
RoomId: roomName,
PersonId: personId,
}
err := redisSM.Rdb.HSet(ctx, sessionIdToKey(randId), newSession).Err()
if err != nil {
log.Printf("> error! saving session %+v %s", newSession, err)
return 0, fmt.Errorf("error saving new session: %+v with %s", newSession, err)
}
return randId, nil
}
type DummySM struct{}
func (d DummySM) Get(sessionId int) SessionData {
log.Printf("get dummy session by %d", sessionId)
return SessionData{}
}
func (d DummySM) Save(roomName string, personId int) (int, error) {
log.Printf("save dummy session with %s %d", roomName, personId)
return 1, nil
}