Skip to content

Commit

Permalink
add cache for movies
Browse files Browse the repository at this point in the history
  • Loading branch information
joschahenningsen committed Nov 8, 2024
1 parent f6b98bb commit 1382046
Show file tree
Hide file tree
Showing 2 changed files with 25 additions and 10 deletions.
34 changes: 24 additions & 10 deletions server/backend/movie.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,8 @@ package backend

import (
"context"
"fmt"
"time"

pb "github.com/TUM-Dev/Campus-Backend/server/api/tumdev"
"github.com/TUM-Dev/Campus-Backend/server/model"
Expand All @@ -12,16 +14,9 @@ import (
)

func (s *CampusServer) ListMovies(ctx context.Context, req *pb.ListMoviesRequest) (*pb.ListMoviesReply, error) {
var movies []model.Movie
tx := s.db.WithContext(ctx).
Joins("File").
Order("date ASC")
if req.OldestDateAt.GetSeconds() != 0 || req.OldestDateAt.GetNanos() != 0 {
tx = tx.Where("date > ?", req.OldestDateAt.AsTime())
}
if err := tx.Find(&movies, "kino > ?", req.LastId).Error; err != nil {
log.WithError(err).Error("Error while fetching movies from database")
return nil, status.Error(codes.Internal, "Error while fetching movies from database")
movies, err := s.getMovies(ctx, req.LastId, req.OldestDateAt.AsTime())
if err != nil {
return nil, err
}
var movieResponse []*pb.Movie
for _, movie := range movies {
Expand All @@ -47,3 +42,22 @@ func (s *CampusServer) ListMovies(ctx context.Context, req *pb.ListMoviesRequest
Movies: movieResponse,
}, nil
}

func (s *CampusServer) getMovies(ctx context.Context, lastID int32, oldestDateAt time.Time) ([]model.Movie, error) {
if movies, ok := s.moviesCache.Get(fmt.Sprintf("%d-%d", lastID, oldestDateAt.Second())); ok {
return movies, nil
}
var movies []model.Movie
tx := s.db.WithContext(ctx).
Joins("File").
Order("date ASC")
if oldestDateAt.Second() != 0 || oldestDateAt.Nanosecond() != 0 {
tx = tx.Where("date > ?", oldestDateAt)
}
if err := tx.Find(&movies, "kino > ?", lastID).Error; err != nil {
log.WithError(err).Error("Error while fetching movies from database")
return nil, status.Error(codes.Internal, "Error while fetching movies from database")
}
s.moviesCache.Add(fmt.Sprintf("%d-%d", lastID, oldestDateAt.Second()), movies)
return movies, nil
}
1 change: 1 addition & 0 deletions server/backend/rpcserver.go
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ type CampusServer struct {
deviceBuf *deviceBuffer // deviceBuf stores all devices from recent request and flushes them to db
newsSourceCache *expirable.LRU[string, []model.NewsSource]
newsCache *expirable.LRU[string, []model.News]
moviesCache *expirable.LRU[string, []model.Movie]
}

// Verify that CampusServer implements the pb.CampusServer interface
Expand Down

0 comments on commit 1382046

Please sign in to comment.