forked from mtusi2026/mtusi2026lab4
feat: implement lab4 persistent attachments and replicated API
This commit is contained in:
@@ -0,0 +1,99 @@
|
||||
package storage
|
||||
|
||||
import (
|
||||
"context"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
|
||||
"mtusi2026lab2/internal/model"
|
||||
)
|
||||
|
||||
type SessionService struct {
|
||||
db *AuthStore
|
||||
cache *SessionCache
|
||||
}
|
||||
|
||||
func NewSessionService(
|
||||
db *AuthStore,
|
||||
cache *SessionCache,
|
||||
) *SessionService {
|
||||
return &SessionService{
|
||||
db: db,
|
||||
cache: cache,
|
||||
}
|
||||
}
|
||||
|
||||
func (s *SessionService) CreateSession(
|
||||
ctx context.Context,
|
||||
token string,
|
||||
userID uuid.UUID,
|
||||
createdAt time.Time,
|
||||
expiresAt time.Time,
|
||||
) error {
|
||||
if err := s.db.CreateSession(
|
||||
ctx, token, userID, createdAt, expiresAt,
|
||||
); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
// Populate the profile cache best-effort after the authoritative INSERT.
|
||||
if s.cache != nil {
|
||||
user, err := s.db.GetUserByID(ctx, userID)
|
||||
if err == nil {
|
||||
cacheCtx, cancel := context.WithTimeout(context.Background(), 250*time.Millisecond)
|
||||
_ = s.cache.Set(cacheCtx, token, user, expiresAt)
|
||||
cancel()
|
||||
}
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *SessionService) GetSessionUser(ctx context.Context, token string) (model.User, error) {
|
||||
// A cheap indexed PostgreSQL check on EVERY request enforces expiry and logout,
|
||||
// even if Redis contains a stale value or its deletion fails.
|
||||
userID, err := s.db.GetActiveSessionUserID(ctx, token)
|
||||
if err != nil {
|
||||
return model.User{}, err
|
||||
}
|
||||
if s.cache != nil {
|
||||
cacheCtx, cancel := context.WithTimeout(ctx, 250*time.Millisecond)
|
||||
cached, hit, err := s.cache.Get(cacheCtx, token)
|
||||
cancel()
|
||||
if err == nil && hit && cached.ID == userID {
|
||||
return cached, nil
|
||||
}
|
||||
}
|
||||
user, err := s.db.GetUserByID(ctx, userID)
|
||||
if err != nil {
|
||||
return model.User{}, err
|
||||
}
|
||||
if s.cache != nil {
|
||||
cacheCtx, cancel := context.WithTimeout(ctx, 250*time.Millisecond)
|
||||
// Conservative short TTL on read-through; session lifetime is still checked in PostgreSQL.
|
||||
_ = s.cache.Set(cacheCtx, token, user, time.Now().Add(30*time.Second))
|
||||
cancel()
|
||||
}
|
||||
return user, nil
|
||||
}
|
||||
|
||||
func (s *SessionService) RevokeSession(
|
||||
ctx context.Context,
|
||||
token string,
|
||||
) error {
|
||||
if err := s.db.RevokeSession(ctx, token); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if s.cache != nil {
|
||||
cacheCtx, cancel := context.WithTimeout(
|
||||
context.Background(), 250*time.Millisecond,
|
||||
)
|
||||
defer cancel()
|
||||
|
||||
_ = s.cache.Delete(cacheCtx, token)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
Reference in New Issue
Block a user