π End-to-end encrypted cloud for everything.
Dart 2faandroidauthye2eeencryptionend-to-end-encryptionfluttergolanggoogle-photosgoogle-photos-alternativeiosopensourcephotosprivacyprivacy-toolstypescriptzero-knowledge
Initialize and verify file counts for new accounts
Neeraj Guptace51d94d26c5
diff --git a/server/pkg/controller/user/user_creation_test.go b/server/pkg/controller/user/user_creation_test.goindex a857c9ca64..ff9a5e89fd 100644--- a/server/pkg/controller/user/user_creation_test.go+++ b/server/pkg/controller/user/user_creation_test.go@@ -4,9 +4,37 @@ import ("testing""github.com/ente/museum/internal/testutil"+ "github.com/ente/museum/pkg/controller""github.com/ente/museum/pkg/repo")+func TestCreateUserInitializesFileCounts(t *testing.T) {+ testutil.WithServerRoot(t)+ db := testutil.RequireTestDB(t)+ testutil.ResetTables(t, db)+ t.Cleanup(func() { testutil.ResetTables(t, db) })+ c := &UserController{+ UserRepo: &repo.UserRepository{DB: db},+ UsageRepo: &repo.UsageRepository{DB: db},+ BillingRepo: &repo.BillingRepository{DB: db},+ MailingListsController: &controller.MailingListsController{},+ SecretEncryptionKey: testutil.SecretEncryptionKey(),+ HashingKey: testutil.HashingKey(),+ }+ userID, _, err := c.createUser(t.Context(), "[email protected]", nil)+ if err != nil {+ t.Fatal(err)+ }+ var photos, locker, version int64+ if err := db.QueryRow(`SELECT photos_file_count, locker_file_count, file_count_source_version+ FROM usage WHERE user_id = $1`, userID).Scan(&photos, &locker, &version); err != nil {+ t.Fatal(err)+ }+ if photos != 0 || locker != 0 || version != 0 {+ t.Fatalf("file count state = (%d, %d, %d), want (0, 0, 0)", photos, locker, version)+ }+}+func TestCreateUserRollsBackWhenSubscriptionCreationFails(t *testing.T) {testutil.WithServerRoot(t)db := testutil.RequireTestDB(t)diff --git a/server/pkg/repo/file.go b/server/pkg/repo/file.goindex 1a95786019..fc395fa431 100644--- a/server/pkg/repo/file.go+++ b/server/pkg/repo/file.go@@ -579,18 +579,23 @@ 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 count(distinct files.file_id)+ 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_countFROM collection_filesJOIN collections c on c.owner_id = $1 and c.collection_id = collection_files.collection_idJOIN files ONfiles.owner_id = $1 AND files.file_id = collection_files.file_id- WHERE (c.app = $2 AND collection_files.is_deleted = false);`, userID, app)+ WHERE (c.app = $2 AND collection_files.is_deleted = false)) AS source+ LEFT JOIN usage u ON u.user_id = $1`, userID, app)var fileCount int64- err := row.Scan(&fileCount)+ var counts fileCountSnapshot+ err := row.Scan(&fileCount, &counts.photos, &counts.locker, &counts.version)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.gonew file mode 100644index 0000000000..48c93054d0--- /dev/null+++ b/server/pkg/repo/file_count_observation.go@@ -0,0 +1,51 @@+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.gonew file mode 100644index 0000000000..08d3ff4931--- /dev/null+++ b/server/pkg/repo/file_count_observation_test.go@@ -0,0 +1,117 @@+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/usage.go b/server/pkg/repo/usage.goindex 6329374af9..92b86c4e0e 100644--- a/server/pkg/repo/usage.go+++ b/server/pkg/repo/usage.go@@ -5,6 +5,7 @@ import ("database/sql""errors"+ "github.com/ente/museum/ente""github.com/ente/stacktrace""github.com/lib/pq")@@ -43,7 +44,8 @@ func (repo *UsageRepository) GetUsage(userID int64) (int64, error) {}func (repo *UsageRepository) CreateTx(ctx context.Context, tx *sql.Tx, userID int64) error {- _, err := tx.ExecContext(ctx, `INSERT INTO usage(user_id, storage_consumed) VALUES ($1, 0)`, userID)+ _, err := tx.ExecContext(ctx, `INSERT INTO usage(user_id, storage_consumed, photos_file_count, locker_file_count)+ VALUES ($1, 0, 0, 0)`, userID)return stacktrace.Propagate(err, "failed to insert usage")}@@ -115,16 +117,21 @@ func (repo *UsageRepository) GetLockerUsage(ctx context.Context, userIDs []int64}countQuery := `- 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;+ 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;`sizeQuery := `@@ -151,13 +158,18 @@ func (repo *UsageRepository) GetLockerUsage(ctx context.Context, userIDs []int64for rows.Next() {var ownerID, fileCount int64- if scanErr := rows.Scan(&ownerID, &fileCount); scanErr != nil {+ 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))