84 lines
2.2 KiB
Go
84 lines
2.2 KiB
Go
package sessions
|
|
|
|
import (
|
|
"context"
|
|
"fmt"
|
|
"log"
|
|
"math/rand"
|
|
"time"
|
|
|
|
"sunshine.industries/some-automoderation/rooms"
|
|
|
|
"github.com/redis/go-redis/v9"
|
|
)
|
|
|
|
type SessionData struct {
|
|
SessionId int `redis:"session_id"`
|
|
RoomId string `redis:"room_id"`
|
|
PersonId rooms.PersonId `redis:"person_id"`
|
|
}
|
|
|
|
type SessionManagement interface {
|
|
Get(sessionId int) SessionData
|
|
Save(ctx context.Context, roomName string, personId rooms.PersonId) (int, error)
|
|
Remove(ctx context.Context, sessionId int) error
|
|
}
|
|
|
|
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(context.TODO(), 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(ctx context.Context, roomName string, personId rooms.PersonId) (int, error) {
|
|
randId := rand.Int()
|
|
newSession := SessionData{
|
|
SessionId: randId,
|
|
RoomId: roomName,
|
|
PersonId: personId,
|
|
}
|
|
err := redisSM.Rdb.HSet(ctx, sessionIdToKey(randId), newSession).Err()
|
|
redisSM.Rdb.Expire(ctx, sessionIdToKey(randId), 24 * time.Hour)
|
|
|
|
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
|
|
}
|
|
|
|
func (redisSM RedisSM) Remove(ctx context.Context, sessionId int) error {
|
|
err := redisSM.Rdb.Del(ctx, sessionIdToKey(sessionId)).Err()
|
|
return err
|
|
}
|
|
|
|
type DummySM struct{}
|
|
|
|
func (d DummySM) Get(sessionId int) SessionData {
|
|
log.Printf("get dummy session by %d", sessionId)
|
|
return SessionData{}
|
|
}
|
|
func (d DummySM) Save(ctx context.Context, roomName string, personId rooms.PersonId) (int, error) {
|
|
log.Printf("save dummy session with %s %d", roomName, personId)
|
|
return 1, nil
|
|
}
|
|
func (d DummySM) Remove(ctx context.Context, sessionId int) error {
|
|
log.Printf("deleting session %d", sessionId)
|
|
return nil
|
|
}
|