Skip to content

armgit / ente

Public Imported from GitHub
0

πŸ’š End-to-end encrypted cloud for everything.

Initialize file counts on demand

Neeraj Guptadf124006e78a
diff --git a/server/cmd/museum/main.go b/server/cmd/museum/main.go
index 0b914cc19a..48bf877c1e 100644
--- a/server/cmd/museum/main.go
+++ b/server/cmd/museum/main.go
@@ -238,11 +238,14 @@ func main() {
LockController: lockController,
NotificationHistoryRepo: notificationHistoryRepo,
}
+ fileCountInitializer := controller.NewFileCountInitializer(usageRepo, trashRepo, lockController)
+ usageRepo.QueueFileCountInitialization = fileCountInitializer.Enqueue
+ go fileCountInitializer.Run()
userCache := cache2.NewUserCache()
userCacheCtrl := &usercache.Controller{UserCache: userCache, FileRepo: fileRepo,
UsageRepo: usageRepo, TrashRepo: trashRepo,
- StoreBonusRepo: storagBonusRepo}
+ StoreBonusRepo: storagBonusRepo, QueueFileCountInitialization: fileCountInitializer.Enqueue}
offerController := offer.NewOfferController(*userRepo, discordController, storagBonusRepo, userCacheCtrl)
plans := billing.GetPlans()
defaultPlan := billing.GetDefaultPlans(plans)
@@ -298,8 +301,6 @@ func main() {
FileRepo: fileRepo,
UploadResultCache: make(map[int64]bool),
}
- fileCountInitializer := &controller.FileCountInitializer{UsageRepo: usageRepo, TrashRepo: trashRepo, LockController: lockController}
-
accessCtrl := access.NewAccessController(accessCollectionRepo, accessFileRepo)
commentsRepo := &socialrepo.CommentsRepository{DB: db}
reactionsRepo := &socialrepo.ReactionsRepository{DB: db}
@@ -1108,7 +1109,7 @@ func main() {
setupAndStartCrons(
userAuthRepo, collectionLinkRepo, fileLinkRepo, pasteRepo, twoFactorRepo, passkeysRepo, fileController, taskLockingRepo, emailNotificationCtrl,
trashController, pushController, objectController, dataCleanupController, storageBonusCtrl, emergencyCtrl,
- embeddingController, healthCheckHandler, castDb, inactiveUserOrchestrator, spaceDripController, fileCountInitializer)
+ embeddingController, healthCheckHandler, castDb, inactiveUserOrchestrator, spaceDripController)
primaryDBCollector := sqlstats.NewStatsCollector("prod_db", db)
latencySensitiveDBCollector := sqlstats.NewStatsCollector("latency_sensitive_db", latencySensitiveDB)
@@ -1298,8 +1299,7 @@ func setupAndStartCrons(userAuthRepo *repo.UserAuthRepository, collectionLinkRep
healthCheckHandler *api.HealthCheckHandler,
castDb castRepo.Repository,
inactiveUserOrchestrator *user.InactiveUserOrchestrator,
- spaceDripController *spacecontroller.SpaceDripController,
- fileCountInitializer *controller.FileCountInitializer) {
+ spaceDripController *spacecontroller.SpaceDripController) {
if viper.GetBool("jobs.cron.skip") {
log.Info("Skipping cron jobs")
return
@@ -1425,8 +1425,6 @@ func setupAndStartCrons(userAuthRepo *repo.UserAuthRepository, collectionLinkRep
pushController.ClearExpiredTokens()
})
- schedule(c, "@every 1m", fileCountInitializer.ProcessBatch)
-
c.Start()
}
diff --git a/server/pkg/controller/usage_file_count_init.go b/server/pkg/controller/usage_file_count_init.go
index c42023f7ce..e325de5c97 100644
--- a/server/pkg/controller/usage_file_count_init.go
+++ b/server/pkg/controller/usage_file_count_init.go
@@ -4,7 +4,7 @@ import (
"context"
"errors"
"strconv"
- "sync/atomic"
+ "sync"
"time"
"github.com/ente/museum/pkg/controller/lock"
@@ -17,99 +17,97 @@ type FileCountInitializer struct {
UsageRepo *repo.UsageRepository
TrashRepo *repo.TrashRepository
LockController *lock.LockController
- afterUserID int64
- resumeAt time.Time
- running atomic.Bool
+ queue chan int64
+ mu sync.Mutex
+ attemptedAt map[int64]time.Time
+ lastPrunedAt time.Time
}
const (
- fileCountInitializationBatchSize = 50
+ fileCountInitializationQueueSize = 100
+ fileCountInitializationRetry = time.Hour
fileCountInitializationLock = "file_count_initialization"
)
-func (c *FileCountInitializer) ProcessBatch() {
- if !c.running.CompareAndSwap(false, true) {
- return
- }
- defer c.running.Store(false)
- if time.Now().Before(c.resumeAt) {
- return
+func NewFileCountInitializer(usageRepo *repo.UsageRepository, trashRepo *repo.TrashRepository, lockController *lock.LockController) *FileCountInitializer {
+ return &FileCountInitializer{
+ UsageRepo: usageRepo,
+ TrashRepo: trashRepo,
+ LockController: lockController,
+ queue: make(chan int64, fileCountInitializationQueueSize),
+ attemptedAt: make(map[int64]time.Time),
+ lastPrunedAt: time.Now(),
}
+}
- ctx := context.Background()
- userIDs, err := c.UsageRepo.GetFileCountInitializationCandidates(ctx, c.afterUserID, fileCountInitializationBatchSize)
- if err != nil {
- log.WithError(err).Error("Failed to fetch file count initialization candidates")
+func (c *FileCountInitializer) Enqueue(userID int64) {
+ now := time.Now()
+ c.mu.Lock()
+ defer c.mu.Unlock()
+ if attemptedAt, ok := c.attemptedAt[userID]; ok && (attemptedAt.IsZero() || now.Sub(attemptedAt) < fileCountInitializationRetry) {
return
}
- if len(userIDs) == 0 {
- c.afterUserID = 0
- c.resumeAt = time.Now().Add(24 * time.Hour)
- return
+ select {
+ case c.queue <- userID:
+ c.attemptedAt[userID] = time.Time{}
+ default:
}
+}
- initialized, deferred, ineligible, contended := 0, 0, 0, 0
- var retryAfterUserID int64
- for _, userID := range userIDs {
- previousUserID := c.afterUserID
- c.afterUserID = userID
- lockID := fileCountInitializationLock + ":" + strconv.FormatInt(userID, 10)
- if !c.LockController.TryLock(lockID, timeUtil.MicrosecondsAfterHours(3)) {
- if contended == 0 {
- retryAfterUserID = previousUserID
- }
- contended++
- continue
+func (c *FileCountInitializer) Run() {
+ for userID := range c.queue {
+ retry := c.initializeUser(userID)
+ now := time.Now()
+ c.mu.Lock()
+ if retry {
+ delete(c.attemptedAt, userID)
+ } else {
+ c.attemptedAt[userID] = now
}
- updated, err := func() (bool, error) {
- defer c.LockController.ReleaseLock(lockID)
- updated, err := c.UsageRepo.InitializeFileCounts(ctx, userID)
- if errors.Is(err, repo.ErrFileCountIneligible) {
- fileIDs, cleanupErr := c.TrashRepo.GetStaleDeletedFileIDs(ctx, userID)
- if cleanupErr != nil {
- log.WithError(cleanupErr).WithField("user_id", userID).Error("Failed to find stale deleted file memberships")
- }
- for _, fileID := range fileIDs {
- if cleanupErr := c.TrashRepo.CleanUpDeletedFilesFromCollection(ctx, []int64{fileID}, userID); cleanupErr != nil {
- log.WithError(cleanupErr).WithFields(log.Fields{
- "user_id": userID,
- "file_id": fileID,
- }).Error("Failed to clean stale deleted file membership")
- }
+ if now.Sub(c.lastPrunedAt) >= fileCountInitializationRetry {
+ for id, attemptedAt := range c.attemptedAt {
+ if !attemptedAt.IsZero() && now.Sub(attemptedAt) >= fileCountInitializationRetry {
+ delete(c.attemptedAt, id)
}
}
- return updated, err
- }()
- if errors.Is(err, repo.ErrFileCountIneligible) {
- ineligible++
- log.WithError(err).WithField("user_id", userID).Warn("File count initialization ineligible")
- continue
+ c.lastPrunedAt = now
}
- if err != nil {
- log.WithError(err).WithField("user_id", userID).Error("Failed to initialize file counts")
- if contended > 0 {
- c.afterUserID = retryAfterUserID
- }
- return
+ c.mu.Unlock()
+ }
+}
+
+func (c *FileCountInitializer) initializeUser(userID int64) bool {
+ lockID := fileCountInitializationLock + ":" + strconv.FormatInt(userID, 10)
+ if !c.LockController.TryLock(lockID, timeUtil.MicrosecondsAfterHours(3)) {
+ return false
+ }
+ defer c.LockController.ReleaseLock(lockID)
+
+ ctx := context.Background()
+ initialized, err := c.UsageRepo.InitializeFileCounts(ctx, userID)
+ if errors.Is(err, repo.ErrFileCountIneligible) {
+ fileIDs, cleanupErr := c.TrashRepo.GetStaleDeletedFileIDs(ctx, userID)
+ if cleanupErr != nil {
+ log.WithError(cleanupErr).WithField("user_id", userID).Error("Failed to find stale deleted file memberships")
}
- if updated {
- initialized++
- } else {
- deferred++
+ cleaned := false
+ for _, fileID := range fileIDs {
+ if cleanupErr := c.TrashRepo.CleanUpDeletedFilesFromCollection(ctx, []int64{fileID}, userID); cleanupErr != nil {
+ log.WithError(cleanupErr).WithFields(log.Fields{
+ "user_id": userID,
+ "file_id": fileID,
+ }).Error("Failed to clean stale deleted file membership")
+ } else {
+ cleaned = true
+ }
}
+ log.WithError(err).WithField("user_id", userID).Warn("File count initialization ineligible")
+ return cleaned
}
- if contended > 0 {
- c.afterUserID = retryAfterUserID
- } else if len(userIDs) < fileCountInitializationBatchSize {
- c.afterUserID = 0
- c.resumeAt = time.Now().Add(24 * time.Hour)
+ if err != nil {
+ log.WithError(err).WithField("user_id", userID).Error("Failed to initialize file counts")
+ } else if initialized {
+ log.WithField("user_id", userID).Info("Initialized file counts")
}
- log.WithFields(log.Fields{
- "attempted": len(userIDs),
- "initialized": initialized,
- "deferred": deferred,
- "ineligible": ineligible,
- "contended": contended,
- "last_user_id": userIDs[len(userIDs)-1],
- }).Info("Processed file count initialization batch")
+ return false
}
diff --git a/server/pkg/controller/usage_file_count_init_test.go b/server/pkg/controller/usage_file_count_init_test.go
new file mode 100644
index 0000000000..0f06537de2
--- /dev/null
+++ b/server/pkg/controller/usage_file_count_init_test.go
@@ -0,0 +1,34 @@
+package controller
+
+import (
+ "testing"
+ "time"
+)
+
+func TestFileCountInitializationQueueDeduplicatesAndRetries(t *testing.T) {
+ initializer := &FileCountInitializer{
+ queue: make(chan int64, 1),
+ attemptedAt: make(map[int64]time.Time),
+ }
+ initializer.Enqueue(1)
+ initializer.Enqueue(1)
+ initializer.Enqueue(2)
+ if len(initializer.queue) != 1 || <-initializer.queue != 1 {
+ t.Fatal("duplicate or full enqueue changed the queued user")
+ }
+
+ initializer.Enqueue(2)
+ if len(initializer.queue) != 1 || <-initializer.queue != 2 {
+ t.Fatal("a user dropped from a full queue was not retried")
+ }
+ initializer.attemptedAt[2] = time.Now()
+ initializer.Enqueue(2)
+ if len(initializer.queue) != 0 {
+ t.Fatal("recently attempted user was queued again")
+ }
+ initializer.attemptedAt[2] = time.Now().Add(-fileCountInitializationRetry)
+ initializer.Enqueue(2)
+ if len(initializer.queue) != 1 || <-initializer.queue != 2 {
+ t.Fatal("retry window did not expire")
+ }
+}
diff --git a/server/pkg/controller/user/account_deletion_summary.go b/server/pkg/controller/user/account_deletion_summary.go
index 1133d1807b..5bc7461daa 100644
--- a/server/pkg/controller/user/account_deletion_summary.go
+++ b/server/pkg/controller/user/account_deletion_summary.go
@@ -16,7 +16,7 @@ func (c *UserController) GetAccountDeletionSummary(ctx context.Context, userID i
g := new(errgroup.Group)
g.Go(func() error {
- count, err := c.FileRepo.GetFileCountForUser(userID, ente.Photos)
+ count, err := c.UserCacheController.GetUserFileCountWithCache(ctx, userID, ente.Photos)
if err != nil {
return stacktrace.Propagate(err, "failed to get photos file count")
}
@@ -24,7 +24,7 @@ func (c *UserController) GetAccountDeletionSummary(ctx context.Context, userID i
return nil
})
g.Go(func() error {
- count, err := c.FileRepo.GetFileCountForUser(userID, ente.Locker)
+ count, err := c.UserCacheController.GetUserFileCountWithCache(ctx, userID, ente.Locker)
if err != nil {
return stacktrace.Propagate(err, "failed to get locker file count")
}
diff --git a/server/pkg/controller/user/user_details.go b/server/pkg/controller/user/user_details.go
index 5938ea3b6d..957cc8fa54 100644
--- a/server/pkg/controller/user/user_details.go
+++ b/server/pkg/controller/user/user_details.go
@@ -97,7 +97,7 @@ func (c *UserController) GetDetailsV2(ctx *gin.Context, userID int64, fetchMemor
if fetchMemoryCount {
g.Go(func() error {
- fCount, err := c.UserCacheController.GetUserFileCountWithCache(userID, app)
+ fCount, err := c.UserCacheController.GetUserFileCountWithCache(ctx, userID, app)
if err == nil {
fileCount = fCount
}
diff --git a/server/pkg/controller/usercache/controller.go b/server/pkg/controller/usercache/controller.go
index 9c0ca3d230..325010c417 100644
--- a/server/pkg/controller/usercache/controller.go
+++ b/server/pkg/controller/usercache/controller.go
@@ -11,11 +11,12 @@ import (
// Avoid adding any direct dependencies to the other controller.
type Controller struct {
- FileRepo *repo.FileRepository
- UsageRepo *repo.UsageRepository
- TrashRepo *repo.TrashRepository
- StoreBonusRepo *storagebonus.Repository
- UserCache *cache.UserCache
+ FileRepo *repo.FileRepository
+ UsageRepo *repo.UsageRepository
+ TrashRepo *repo.TrashRepository
+ StoreBonusRepo *storagebonus.Repository
+ UserCache *cache.UserCache
+ QueueFileCountInitialization func(int64)
}
func (c *Controller) GetActiveStorageBonus(ctx context.Context, userID int64) (*bonus.ActiveStorageBonus, error) {
diff --git a/server/pkg/controller/usercache/count.go b/server/pkg/controller/usercache/count.go
index 942258dc5f..da625cdc46 100644
--- a/server/pkg/controller/usercache/count.go
+++ b/server/pkg/controller/usercache/count.go
@@ -1,13 +1,32 @@
package usercache
import (
+ "context"
+
"github.com/ente/museum/ente"
"github.com/ente/museum/ente/cache"
"github.com/ente/stacktrace"
"github.com/sirupsen/logrus"
)
-func (c *Controller) GetUserFileCountWithCache(userID int64, app ente.App) (int64, error) {
+func (c *Controller) GetUserFileCountWithCache(ctx context.Context, userID int64, app ente.App) (int64, error) {
+ _, photos, locker, err := c.UsageRepo.GetStoredFileCounts(ctx, userID)
+ if err != nil {
+ return 0, stacktrace.Propagate(err, "")
+ }
+ count := int64(-1)
+ switch app {
+ case ente.Photos:
+ count = photos
+ case ente.Locker:
+ count = locker
+ }
+ if count >= 0 {
+ return count, nil
+ }
+ if (app == ente.Photos || app == ente.Locker) && c.QueueFileCountInitialization != nil {
+ c.QueueFileCountInitialization(userID)
+ }
if count, ok := c.UserCache.GetFileCount(userID, app); ok {
// Cache hit, update the cache asynchronously
go func() {
diff --git a/server/pkg/controller/usercache/count_test.go b/server/pkg/controller/usercache/count_test.go
new file mode 100644
index 0000000000..c77ade2234
--- /dev/null
+++ b/server/pkg/controller/usercache/count_test.go
@@ -0,0 +1,45 @@
+package usercache
+
+import (
+ "testing"
+
+ "github.com/ente/museum/ente"
+ "github.com/ente/museum/ente/cache"
+ "github.com/ente/museum/internal/testutil"
+ "github.com/ente/museum/pkg/repo"
+)
+
+func TestGetUserFileCountUsesStoredCountOrQueuesInitialization(t *testing.T) {
+ db := testutil.RequireTestDB(t)
+ testutil.ResetTables(t, db)
+ t.Cleanup(func() { testutil.ResetTables(t, db) })
+ userID := testutil.InsertUser(t, db, testutil.UserFixture{Email: "[email protected]", CreationTime: 1})
+ testutil.InsertUsage(t, db, userID, 0)
+ if _, err := db.Exec(`UPDATE usage SET photos_file_count = 9, locker_file_count = 0 WHERE user_id = $1`, userID); err != nil {
+ t.Fatal(err)
+ }
+
+ queued := 0
+ userCache := cache.NewUserCache()
+ userCache.SetFileCount(userID, &cache.FileCountCache{Count: 41}, ente.Photos)
+ controller := &Controller{
+ FileRepo: &repo.FileRepository{DB: db},
+ UsageRepo: &repo.UsageRepository{DB: db},
+ TrashRepo: &repo.TrashRepository{DB: db},
+ UserCache: userCache,
+ QueueFileCountInitialization: func(int64) { queued++ },
+ }
+ count, err := controller.GetUserFileCountWithCache(t.Context(), userID, ente.Photos)
+ if err != nil || count != 9 || queued != 0 {
+ t.Fatalf("ready count = (%d, %v), queued %d; want (9, nil), queued 0", count, err, queued)
+ }
+
+ if _, err := db.Exec(`UPDATE usage SET photos_file_count = NULL, locker_file_count = NULL WHERE user_id = $1`, userID); err != nil {
+ t.Fatal(err)
+ }
+ controller.UserCache = cache.NewUserCache()
+ count, err = controller.GetUserFileCountWithCache(t.Context(), userID, ente.Photos)
+ if err != nil || count != 0 || queued != 1 {
+ t.Fatalf("legacy count = (%d, %v), queued %d; want (0, nil), queued 1", count, err, queued)
+ }
+}
diff --git a/server/pkg/repo/file.go b/server/pkg/repo/file.go
index fc395fa431..22b81f1fc8 100644
--- a/server/pkg/repo/file.go
+++ b/server/pkg/repo/file.go
@@ -579,23 +579,18 @@ func (repo *FileRepository) GetSize(userID int64, fileIDs []int64) (int64, error
}
func (repo *FileRepository) GetFileCountForUser(userID int64, app ente.App) (int64, error) {
- row := repo.DB.QueryRow(`SELECT source.file_count,
- u.photos_file_count, u.locker_file_count, u.file_count_source_version
- FROM (SELECT count(distinct files.file_id) AS file_count
+ row := repo.DB.QueryRow(`SELECT count(distinct files.file_id) AS file_count
FROM collection_files
JOIN collections c on c.owner_id = $1 and c.collection_id = collection_files.collection_id
JOIN files ON
files.owner_id = $1 AND files.file_id = collection_files.file_id
- WHERE (c.app = $2 AND collection_files.is_deleted = false)) AS source
- LEFT JOIN usage u ON u.user_id = $1`, userID, app)
+ WHERE (c.app = $2 AND collection_files.is_deleted = false)`, userID, app)
var fileCount int64
- var counts fileCountSnapshot
- err := row.Scan(&fileCount, &counts.photos, &counts.locker, &counts.version)
+ err := row.Scan(&fileCount)
if err != nil {
return -1, stacktrace.Propagate(err, "")
}
- counts.observe("file_count", userID, app, fileCount)
return fileCount, nil
}
diff --git a/server/pkg/repo/file_count_observation.go b/server/pkg/repo/file_count_observation.go
deleted file mode 100644
index 48c93054d0..0000000000
--- a/server/pkg/repo/file_count_observation.go
+++ /dev/null
@@ -1,51 +0,0 @@
-package repo
-
-import (
- "database/sql"
-
- "github.com/ente/museum/ente"
- "github.com/prometheus/client_golang/prometheus"
- "github.com/prometheus/client_golang/prometheus/promauto"
- "github.com/sirupsen/logrus"
-)
-
-var fileCountComparisons = promauto.NewCounterVec(prometheus.CounterOpts{
- Name: "museum_file_count_comparisons_total",
- Help: "Same-snapshot comparisons of source and initialized file counts.",
-}, []string{"reader", "app", "result"})
-
-// Read with the source count in one statement so concurrent writes cannot cause
-// false mismatches. NULL counters are not initialized and must not be compared.
-type fileCountSnapshot struct {
- photos sql.NullInt64
- locker sql.NullInt64
- version sql.NullInt64
-}
-
-func (counts fileCountSnapshot) observe(reader string, userID int64, app ente.App, sourceCount int64) {
- if !counts.photos.Valid || !counts.locker.Valid {
- return
- }
- var counter int64
- switch app {
- case ente.Photos:
- counter = counts.photos.Int64
- case ente.Locker:
- counter = counts.locker.Int64
- default:
- return
- }
- result := "match"
- if counter != sourceCount {
- result = "mismatch"
- logrus.WithFields(logrus.Fields{
- "user_id": userID,
- "reader": reader,
- "app": app,
- "source_count": sourceCount,
- "counter_count": counter,
- "file_count_source_version": counts.version.Int64,
- }).Warn("file count mismatch")
- }
- fileCountComparisons.WithLabelValues(reader, string(app), result).Inc()
-}
diff --git a/server/pkg/repo/file_count_observation_test.go b/server/pkg/repo/file_count_observation_test.go
deleted file mode 100644
index 08d3ff4931..0000000000
--- a/server/pkg/repo/file_count_observation_test.go
+++ /dev/null
@@ -1,117 +0,0 @@
-package repo
-
-import (
- "fmt"
- "testing"
-
- "github.com/ente/museum/ente"
- "github.com/ente/museum/internal/testutil"
- promtest "github.com/prometheus/client_golang/prometheus/testutil"
-)
-
-func TestGetFileCountForUserObservesCounts(t *testing.T) {
- for _, app := range []ente.App{ente.Photos, ente.Locker} {
- for _, tt := range []struct {
- name string
- counter any
- sourceCount int64
- missingUsage bool
- matches float64
- mismatches float64
- }{
- {name: "legacy", sourceCount: 1},
- {name: "match", counter: 1, sourceCount: 1, matches: 1},
- {name: "mismatch", counter: 9, sourceCount: 1, mismatches: 1},
- {name: "empty_mismatch", counter: 2, mismatches: 1},
- {name: "missing_usage", sourceCount: 1, missingUsage: true},
- } {
- t.Run(string(app)+"/"+tt.name, func(t *testing.T) {
- db := setupFileUsageTest(t)
- userID := testutil.InsertUser(t, db, testutil.UserFixture{Email: "[email protected]", CreationTime: 1})
- if !tt.missingUsage {
- var photos, locker any
- if tt.counter != nil {
- photos, locker = tt.counter, 0
- if app == ente.Locker {
- photos, locker = 0, tt.counter
- }
- }
- if _, err := db.Exec(`INSERT INTO usage(user_id, storage_consumed, photos_file_count, locker_file_count)
- VALUES ($1, 0, $2, $3)`, userID, photos, locker); err != nil {
- t.Fatal(err)
- }
- }
- if tt.sourceCount > 0 {
- fileID := insertObjectTestFile(t, db, userID)
- for range 2 {
- collectionID := insertObjectTestCollection(t, db, userID)
- if _, err := db.Exec(`UPDATE collections SET app = $2 WHERE collection_id = $1`, collectionID, app); err != nil {
- t.Fatal(err)
- }
- linkObjectTestFileToCollection(t, db, collectionID, fileID, userID)
- }
- }
- fileCountComparisons.Reset()
- count, err := (&FileRepository{DB: db}).GetFileCountForUser(userID, app)
- if err != nil || count != tt.sourceCount {
- t.Fatalf("GetFileCountForUser() = (%d, %v), want %d", count, err, tt.sourceCount)
- }
- assertFileCountComparisons(t, "file_count", app, tt.matches, tt.mismatches)
- })
- }
- }
-}
-
-func TestGetLockerUsageObservesMixedFamily(t *testing.T) {
- db := setupFileUsageTest(t)
- userIDs := make([]int64, 4)
- for i := range userIDs {
- userID := testutil.InsertUser(t, db, testutil.UserFixture{Email: fmt.Sprintf("member-%[email protected]", i), CreationTime: 1})
- userIDs[i] = userID
- if i < 3 {
- testutil.InsertUsage(t, db, userID, 0)
- }
- if i == 0 {
- setReadyFileCounts(t, db, userID, 0, 0)
- continue
- }
- if i == 1 {
- setReadyFileCounts(t, db, userID, 0, 9)
- }
- fileID := insertObjectTestFile(t, db, userID)
- collectionID := insertObjectTestCollection(t, db, userID)
- if _, err := db.Exec(`UPDATE collections SET app = 'locker' WHERE collection_id = $1`, collectionID); err != nil {
- t.Fatal(err)
- }
- linkObjectTestFileToCollection(t, db, collectionID, fileID, userID)
- insertObjectTestKey(t, db, fileID, ente.FILE, fmt.Sprintf("object-%d", i), 100, []string{"b2-eu-cen"})
- }
- fileCountComparisons.Reset()
- usage, err := (&UsageRepository{DB: db}).GetLockerUsage(t.Context(), userIDs)
- if err != nil {
- t.Fatal(err)
- }
- if usage.TotalFileCount != 3 || usage.TotalUsage != 300 || len(usage.Users) != 4 {
- t.Fatalf("unexpected family usage: %+v", usage)
- }
- for i, user := range usage.Users {
- wantCount := int64(1)
- if i == 0 {
- wantCount = 0
- }
- if user.UserID != userIDs[i] || user.FileCount != wantCount || user.Usage != wantCount*100 {
- t.Fatalf("unexpected member usage: %+v", user)
- }
- }
- assertFileCountComparisons(t, "locker_usage", ente.Locker, 1, 1)
-}
-
-func assertFileCountComparisons(t *testing.T, reader string, app ente.App, matches, mismatches float64) {
- t.Helper()
- for result, want := range map[string]float64{"match": matches, "mismatch": mismatches} {
- got := promtest.ToFloat64(fileCountComparisons.WithLabelValues(reader, string(app), result))
- if got != want {
- t.Errorf("%s/%s/%s comparisons = %g, want %g", reader, app, result, got, want)
- }
- }
-}
diff --git a/server/pkg/repo/file_count_read_test.go b/server/pkg/repo/file_count_read_test.go
new file mode 100644
index 0000000000..0167e67e78
--- /dev/null
+++ b/server/pkg/repo/file_count_read_test.go
@@ -0,0 +1,46 @@
+package repo
+
+import (
+ "fmt"
+ "testing"
+
+ "github.com/ente/museum/ente"
+ "github.com/ente/museum/internal/testutil"
+)
+
+func TestGetLockerUsageUsesStoredAndLegacyCountsPerUser(t *testing.T) {
+ db := setupFileUsageTest(t)
+ readyUserID := testutil.InsertUser(t, db, testutil.UserFixture{Email: "[email protected]", CreationTime: 1})
+ legacyUserID := testutil.InsertUser(t, db, testutil.UserFixture{Email: "[email protected]", CreationTime: 1})
+ testutil.InsertUsage(t, db, readyUserID, 0)
+ testutil.InsertUsage(t, db, legacyUserID, 0)
+ setReadyFileCounts(t, db, readyUserID, 0, 9)
+
+ for _, userID := range []int64{readyUserID, legacyUserID} {
+ fileID := insertObjectTestFile(t, db, userID)
+ collectionID := insertObjectTestCollection(t, db, userID)
+ if _, err := db.Exec(`UPDATE collections SET app = 'locker' WHERE collection_id = $1`, collectionID); err != nil {
+ t.Fatal(err)
+ }
+ linkObjectTestFileToCollection(t, db, collectionID, fileID, userID)
+ insertObjectTestKey(t, db, fileID, ente.FILE, fmt.Sprintf("object-%d", userID), 100, []string{"b2-eu-cen"})
+ }
+
+ var queued []int64
+ usage, err := (&UsageRepository{
+ DB: db,
+ QueueFileCountInitialization: func(userID int64) { queued = append(queued, userID) },
+ }).GetLockerUsage(t.Context(), []int64{readyUserID, legacyUserID})
+ if err != nil {
+ t.Fatal(err)
+ }
+ if usage.TotalFileCount != 10 || usage.TotalUsage != 200 {
+ t.Fatalf("family usage = %+v, want 10 files and 200 bytes", usage)
+ }
+ if len(usage.Users) != 2 || usage.Users[0].FileCount != 9 || usage.Users[1].FileCount != 1 {
+ t.Fatalf("member usage = %+v, want stored then legacy count", usage.Users)
+ }
+ if len(queued) != 1 || queued[0] != legacyUserID {
+ t.Fatalf("queued users = %v, want [%d]", queued, legacyUserID)
+ }
+}
diff --git a/server/pkg/repo/usage.go b/server/pkg/repo/usage.go
index bfe51afe60..f383e92d5e 100644
--- a/server/pkg/repo/usage.go
+++ b/server/pkg/repo/usage.go
@@ -5,14 +5,14 @@ import (
"database/sql"
"errors"
- "github.com/ente/museum/ente"
"github.com/ente/stacktrace"
"github.com/lib/pq"
)
type UsageRepository struct {
- DB *sql.DB
- UserRepo *UserRepository
+ DB *sql.DB
+ UserRepo *UserRepository
+ QueueFileCountInitialization func(int64)
}
type LockerUsage struct {
@@ -133,23 +133,63 @@ func (repo *UsageRepository) GetLockerUsage(ctx context.Context, userIDs []int64
}
}
- countQuery := `
- WITH counts AS (
- SELECT c.owner_id, COUNT(DISTINCT cf.file_id) AS file_count
- FROM collections c
- JOIN collection_files cf ON c.collection_id = cf.collection_id
- WHERE c.app = 'locker'
- AND c.owner_id = ANY($1)
- AND cf.f_owner_id = c.owner_id
- AND cf.is_deleted = false
- GROUP BY c.owner_id
- )
- SELECT requested.user_id, COALESCE(counts.file_count, 0),
- u.photos_file_count, u.locker_file_count, u.file_count_source_version
- FROM unnest($1::bigint[]) AS requested(user_id)
- LEFT JOIN counts ON counts.owner_id = requested.user_id
- LEFT JOIN usage u ON u.user_id = requested.user_id;
- `
+ rows, err := repo.DB.QueryContext(ctx, `SELECT requested.user_id, u.locker_file_count
+ FROM unnest($1::bigint[]) AS requested(user_id)
+ LEFT JOIN usage AS u ON u.user_id = requested.user_id`, pq.Array(userIDs))
+ if err != nil {
+ return nil, stacktrace.Propagate(err, "")
+ }
+ var uninitializedUserIDs []int64
+ for rows.Next() {
+ var userID int64
+ var fileCount sql.NullInt64
+ if err := rows.Scan(&userID, &fileCount); err != nil {
+ rows.Close()
+ return nil, stacktrace.Propagate(err, "")
+ }
+ if fileCount.Valid {
+ userMap[userID].FileCount = fileCount.Int64
+ } else {
+ uninitializedUserIDs = append(uninitializedUserIDs, userID)
+ }
+ }
+ if err := rows.Close(); err != nil {
+ return nil, stacktrace.Propagate(err, "")
+ }
+ if err := rows.Err(); err != nil {
+ return nil, stacktrace.Propagate(err, "")
+ }
+ if repo.QueueFileCountInitialization != nil {
+ for _, userID := range uninitializedUserIDs {
+ repo.QueueFileCountInitialization(userID)
+ }
+ }
+
+ if len(uninitializedUserIDs) > 0 {
+ rows, err = repo.DB.QueryContext(ctx, `SELECT c.owner_id, COUNT(DISTINCT cf.file_id)
+ FROM collections AS c
+ JOIN collection_files AS cf ON c.collection_id = cf.collection_id
+ WHERE c.app = 'locker' AND c.owner_id = ANY($1)
+ AND cf.f_owner_id = c.owner_id AND cf.is_deleted = FALSE
+ GROUP BY c.owner_id`, pq.Array(uninitializedUserIDs))
+ if err != nil {
+ return nil, stacktrace.Propagate(err, "")
+ }
+ for rows.Next() {
+ var userID, fileCount int64
+ if err := rows.Scan(&userID, &fileCount); err != nil {
+ rows.Close()
+ return nil, stacktrace.Propagate(err, "")
+ }
+ userMap[userID].FileCount = fileCount
+ }
+ if err := rows.Close(); err != nil {
+ return nil, stacktrace.Propagate(err, "")
+ }
+ if err := rows.Err(); err != nil {
+ return nil, stacktrace.Propagate(err, "")
+ }
+ }
sizeQuery := `
SELECT
@@ -167,28 +207,6 @@ func (repo *UsageRepository) GetLockerUsage(ctx context.Context, userIDs []int64
GROUP BY unique_files.owner_id;
`
- rows, err := repo.DB.QueryContext(ctx, countQuery, pq.Array(userIDs))
- if err != nil {
- return nil, stacktrace.Propagate(err, "")
- }
- defer rows.Close()
-
- for rows.Next() {
- var ownerID, fileCount int64
- var counts fileCountSnapshot
- if scanErr := rows.Scan(&ownerID, &fileCount, &counts.photos, &counts.locker, &counts.version); scanErr != nil {
- return nil, stacktrace.Propagate(scanErr, "")
- }
- counts.observe("locker_usage", ownerID, ente.Locker, fileCount)
- if user, exists := userMap[ownerID]; exists {
- user.FileCount = fileCount
- }
- }
- if err := rows.Err(); err != nil {
- return nil, stacktrace.Propagate(err, "")
- }
- rows.Close()
-
rows, err = repo.DB.QueryContext(ctx, sizeQuery, pq.Array(userIDs))
if err != nil {
return nil, stacktrace.Propagate(err, "")
diff --git a/server/pkg/repo/usage_file_count_init.go b/server/pkg/repo/usage_file_count_init.go
index 0a841e5221..020882383a 100644
--- a/server/pkg/repo/usage_file_count_init.go
+++ b/server/pkg/repo/usage_file_count_init.go
@@ -26,28 +26,6 @@ func (repo *UsageRepository) InitializeFileCounts(ctx context.Context, userID in
return repo.publishInitialFileCounts(ctx, userID, counts)
}
-func (repo *UsageRepository) GetFileCountInitializationCandidates(ctx context.Context, afterUserID int64, limit int) ([]int64, error) {
- rows, err := repo.DB.QueryContext(ctx, `SELECT usage.user_id FROM usage
- JOIN users ON users.user_id = usage.user_id AND users.encrypted_email IS NOT NULL
- WHERE usage.user_id > $1 AND usage.storage_consumed > 0
- AND photos_file_count IS NULL AND locker_file_count IS NULL
- ORDER BY usage.user_id LIMIT $2`, afterUserID, limit)
- if err != nil {
- return nil, err
- }
- defer rows.Close()
-
- var userIDs []int64
- for rows.Next() {
- var userID int64
- if err := rows.Scan(&userID); err != nil {
- return nil, err
- }
- userIDs = append(userIDs, userID)
- }
- return userIDs, rows.Err()
-}
-
type fileCountInitSnapshot struct {
photos, locker, version int64
uninitialized bool