Skip to content

armgit / ente

Public Imported from GitHub
0

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

Expose file count migration through admin APIs

Neeraj Guptaa4964739956b
diff --git a/server/cmd/museum/main.go b/server/cmd/museum/main.go
index 27628d5398..f346ba5d49 100644
--- a/server/cmd/museum/main.go
+++ b/server/cmd/museum/main.go
@@ -960,6 +960,7 @@ func main() {
EmergencyController: emergencyCtrl,
RemoteStoreController: remoteStoreController,
FileRepo: fileRepo,
+ UsageRepo: usageRepo,
StorageBonusRepo: storagBonusRepo,
BillingRepo: billingRepo,
BillingController: billingController,
@@ -992,6 +993,7 @@ func main() {
adminAPI.POST("/emails-from-hashes", adminHandler.GetEmailsFromHashes)
adminAPI.PUT("/user/subscription", adminHandler.UpdateSubscription)
adminAPI.POST("/queue/re-queue", adminHandler.ReQueueItem)
+ adminAPI.POST("/user/init-file-counts", adminHandler.InitializeFileCounts)
adminAPI.POST("/user/bonus", adminHandler.UpdateBonus)
userEntityController := &userEntityCtrl.Controller{Repo: userEntityRepo}
diff --git a/server/docs/file-count-initialization.md b/server/docs/file-count-initialization.md
new file mode 100644
index 0000000000..2f76b02e82
--- /dev/null
+++ b/server/docs/file-count-initialization.md
@@ -0,0 +1,63 @@
+# Initialize existing users' file counts
+
+`POST /admin/user/init-file-counts` initializes one user's paired-NULL counters.
+It uses the existing admin authentication and the server's primary database.
+Nothing runs automatically on deployment; client count reads remain source-based.
+
+`GET /admin/user?id=...` (or `?email=...`) also returns top-level
+`photosFileCount` and `lockerFileCount` from `usage`. Both are `-1` until the pair
+is initialized, including when the usage row is missing; an initialized empty
+library returns `0`. These are individual-user counts, not family totals, and
+reading them does not trigger initialization. Existing response fields are unchanged.
+
+Call only after **all count-aware writers are deployed and old processes have
+stopped**, including the stale-membership invalidation path. For the first cohort,
+submit users with `user_id < 200` one at a time, pausing between requests. The API
+accepts an explicit user ID, not a range, so cohort selection and pacing stay with
+the caller. A small ID range does not imply small libraries.
+
+Request body:
+
+```json
+{"userID": 1}
+```
+
+- HTTP 200 with `{"initialized": true}`: both counters were published.
+- HTTP 200 with `{"initialized": false}`: already initialized or the source version
+ changed; retry later if the counters are still NULL.
+- HTTP 200 with `initialized: false` and `reason`: inconsistent history; leave the
+ counters NULL and investigate. Repeating the request does not repair the data.
+- HTTP 504: the database work exceeded its 10-second budget. Stop or defer large
+ accounts if DB load or latency rises. Rerunning a request is safe, including
+ when a response is lost after publication.
+- Other errors use the normal API error handling. A missing usage row returns
+ HTTP 404 and is never created by this endpoint.
+
+Search server logs for `file count initialization`; each attempt records the
+admin, target user, result, and any error. There is no new metric or per-user
+metric label.
+
+Each attempt reads the version, distinct active owned-file counts, and
+eligibility in one SQL snapshot. It then publishes both counters only if they
+are still NULL and the version is unchanged. Counting takes no file or membership
+row locks; only publication briefly locks that user's usage row. Count-changing
+writers that commit before publication cause this attempt to be skipped; writers
+that follow it maintain the initialized counts. Storage and source version are
+unchanged by publication.
+
+Unsafe histories stay NULL:
+
+- An owned file has no active owned membership and no unrestored Trash row.
+ Trash was added later: older cleanup used missing collection references to
+ delete objects directly, so missing references do not establish Trash state.
+- An unrestored Trash row conflicts with active owned membership or file ownership.
+- An owned file has active cross-app or unsupported-app memberships.
+- An active Locker membership's actual file ownership disagrees with the legacy
+ `f_owner_id` predicate. NULL denormalized owners on old Photos rows are allowed.
+
+Do not reset source versions or write zero counts to bypass a failed check.
+Before expanding the cohort or switching reads, check the existing
+`museum_file_count_comparisons_total` match/mismatch metric and `file count mismatch`
+logs during real source reads and file activity. No observations is not successful
+validation. The trusted-client same-app assumption still applies; this endpoint
+does not add guards to AddFiles/MoveFiles.
diff --git a/server/pkg/api/admin.go b/server/pkg/api/admin.go
index 5faf880a30..33ec95fb9c 100644
--- a/server/pkg/api/admin.go
+++ b/server/pkg/api/admin.go
@@ -1,6 +1,7 @@
package api
import (
+ "context"
"errors"
"fmt"
"net/http"
@@ -44,6 +45,7 @@ type AdminHandler struct {
AuthenticatorRepo *authenticator.Repository
UserAuthRepo *repo.UserAuthRepository
FileRepo *repo.FileRepository
+ UsageRepo *repo.UsageRepository
BillingRepo *repo.BillingRepository
StorageBonusRepo *storagebonus.Repository
BillingController *controller.BillingController
@@ -510,6 +512,35 @@ func (h *AdminHandler) ReQueueItem(c *gin.Context) {
c.JSON(http.StatusOK, gin.H{})
}
+func (h *AdminHandler) InitializeFileCounts(c *gin.Context) {
+ var r ente.AdminOpsForUserRequest
+ if err := handler.BindJSON(c, &r); err != nil {
+ handler.Error(c, stacktrace.Propagate(err, "Bad request"))
+ return
+ }
+ ctx, cancel := context.WithTimeout(c.Request.Context(), 10*gTime.Second)
+ defer cancel()
+ initialized, err := h.UsageRepo.InitializeFileCounts(ctx, r.UserID)
+ logrus.WithFields(logrus.Fields{
+ "admin_id": auth.GetUserID(c.Request.Header),
+ "user_id": r.UserID,
+ "initialized": initialized,
+ }).WithError(err).Info("file count initialization")
+ if err != nil && !errors.Is(err, repo.ErrFileCountIneligible) {
+ if errors.Is(ctx.Err(), context.DeadlineExceeded) {
+ c.Status(http.StatusGatewayTimeout)
+ } else {
+ handler.Error(c, stacktrace.Propagate(err, "failed to initialize file counts"))
+ }
+ return
+ }
+ response := gin.H{"initialized": initialized}
+ if err != nil {
+ response["reason"] = err.Error()
+ }
+ c.JSON(http.StatusOK, response)
+}
+
func (h *AdminHandler) UpdateBonus(c *gin.Context) {
var r ente.SupportUpdateBonus
if err := handler.BindJSON(c, &r); err != nil {
@@ -679,6 +710,11 @@ func (h *AdminHandler) attachSubscription(ctx *gin.Context, userID int64, respon
if err == nil {
response["details"] = details
}
+ photos, locker, err := h.UsageRepo.GetFileCounts(ctx.Request.Context(), userID)
+ if err == nil {
+ response["photosFileCount"] = photos
+ response["lockerFileCount"] = locker
+ }
tokenInfos, err := h.UserAuthRepo.GetUserTokenInfo(userID)
if err == nil {
response["tokens"] = tokenInfos
diff --git a/server/pkg/api/admin_file_count_test.go b/server/pkg/api/admin_file_count_test.go
new file mode 100644
index 0000000000..9c2fc495b3
--- /dev/null
+++ b/server/pkg/api/admin_file_count_test.go
@@ -0,0 +1,53 @@
+package api
+
+import (
+ "net/http"
+ "net/http/httptest"
+ "strings"
+ "testing"
+
+ "github.com/ente/museum/internal/testutil"
+ "github.com/ente/museum/pkg/repo"
+ "github.com/gin-gonic/gin"
+ "github.com/stretchr/testify/require"
+)
+
+func TestInitializeFileCountsHandler(t *testing.T) {
+ db := testutil.RequireTestDB(t)
+ t.Cleanup(func() { testutil.ResetTables(t, db) })
+ for _, tt := range []struct {
+ name string
+ sql string
+ status int
+ response string
+ }{
+ {"initialize", "", http.StatusOK, `{"initialized":true}`},
+ {"already_ready", `UPDATE usage SET photos_file_count = 0, locker_file_count = 0`,
+ http.StatusOK, `{"initialized":false}`},
+ {"ineligible", `INSERT INTO files(owner_id, file_decryption_header, thumbnail_decryption_header,
+ metadata_decryption_header, encrypted_metadata, updation_time)
+ VALUES (1, 'header', 'header', 'header', 'metadata', 1)`,
+ http.StatusOK, `{"initialized":false,"reason":"file counts are ineligible: untrashed file without an owned membership"}`},
+ {"missing_usage", `DELETE FROM usage`, http.StatusNotFound, `{}`},
+ } {
+ t.Run(tt.name, func(t *testing.T) {
+ testutil.ResetTables(t, db)
+ testutil.InsertUser(t, db, testutil.UserFixture{UserID: 1, Email: "[email protected]", CreationTime: 1})
+ testutil.InsertUsage(t, db, 1, 0)
+ if tt.sql != "" {
+ _, err := db.Exec(tt.sql)
+ require.NoError(t, err)
+ }
+ h := &AdminHandler{UsageRepo: &repo.UsageRepository{DB: db}}
+ router := gin.New()
+ router.POST("/admin/user/init-file-counts", h.InitializeFileCounts)
+ request := httptest.NewRequest(http.MethodPost, "/admin/user/init-file-counts", strings.NewReader(`{"userID":1}`))
+ request.Header.Set("Content-Type", "application/json")
+ request.Header.Set("X-Auth-User-ID", "9")
+ recorder := httptest.NewRecorder()
+ router.ServeHTTP(recorder, request)
+ require.Equal(t, tt.status, recorder.Code, recorder.Body.String())
+ require.JSONEq(t, tt.response, recorder.Body.String())
+ })
+ }
+}
diff --git a/server/pkg/repo/usage.go b/server/pkg/repo/usage.go
index 92b86c4e0e..64e3bcc139 100644
--- a/server/pkg/repo/usage.go
+++ b/server/pkg/repo/usage.go
@@ -43,6 +43,18 @@ func (repo *UsageRepository) GetUsage(userID int64) (int64, error) {
return usage, stacktrace.Propagate(err, "")
}
+// GetFileCounts returns the stored counts, or -1 for both until initialized.
+func (repo *UsageRepository) GetFileCounts(ctx context.Context, userID int64) (int64, int64, error) {
+ var photos, locker int64
+ err := repo.DB.QueryRowContext(ctx, `SELECT photos_file_count, locker_file_count
+ FROM usage WHERE user_id = $1
+ AND photos_file_count IS NOT NULL AND locker_file_count IS NOT NULL`, userID).Scan(&photos, &locker)
+ if errors.Is(err, sql.ErrNoRows) {
+ return -1, -1, nil
+ }
+ return photos, locker, stacktrace.Propagate(err, "")
+}
+
func (repo *UsageRepository) CreateTx(ctx context.Context, tx *sql.Tx, userID int64) error {
_, err := tx.ExecContext(ctx, `INSERT INTO usage(user_id, storage_consumed, photos_file_count, locker_file_count)
VALUES ($1, 0, 0, 0)`, userID)
diff --git a/server/pkg/repo/usage_file_count_test.go b/server/pkg/repo/usage_file_count_test.go
index 45ff224c34..c07d6a117a 100644
--- a/server/pkg/repo/usage_file_count_test.go
+++ b/server/pkg/repo/usage_file_count_test.go
@@ -8,6 +8,33 @@ import (
"github.com/ente/museum/pkg/repo/public"
)
+func TestGetFileCountsReturnsStoredCountsOrUninitialized(t *testing.T) {
+ _, db, userID := setupCollectionMembershipTest(t)
+ usageRepo := &UsageRepository{DB: db}
+ for _, tt := range []struct {
+ name string
+ sql string
+ photos, locker int64
+ }{
+ {"uninitialized", "", -1, -1},
+ {"empty", `UPDATE usage SET photos_file_count = 0, locker_file_count = 0 WHERE user_id = $1`, 0, 0},
+ {"ready", `UPDATE usage SET photos_file_count = 23, locker_file_count = 7 WHERE user_id = $1`, 23, 7},
+ {"missing", `DELETE FROM usage WHERE user_id = $1`, -1, -1},
+ } {
+ t.Run(tt.name, func(t *testing.T) {
+ if tt.sql != "" {
+ if _, err := db.Exec(tt.sql, userID); err != nil {
+ t.Fatal(err)
+ }
+ }
+ photos, locker, err := usageRepo.GetFileCounts(t.Context(), userID)
+ if err != nil || photos != tt.photos || locker != tt.locker {
+ t.Fatalf("GetFileCounts() = (%d, %d, %v), want (%d, %d, nil)", photos, locker, err, tt.photos, tt.locker)
+ }
+ })
+ }
+}
+
func TestTrashAndRestoreMaintainReadyLockerCount(t *testing.T) {
repository, db, userID := setupCollectionMembershipTest(t)
setReadyFileCounts(t, db, userID, 0, 1)
diff --git a/server/tools/init-file-counts/README.md b/server/tools/init-file-counts/README.md
deleted file mode 100644
index 682527f8a9..0000000000
--- a/server/tools/init-file-counts/README.md
+++ /dev/null
@@ -1,59 +0,0 @@
-# Initialize existing users' file counts
-
-This operator-run command fills both NULL file-count columns in existing `usage`
-rows. It does not run on server startup, change API reads, repair source data,
-or modify storage usage. New accounts already start with initialized counters.
-
-Run only after **all count-aware writers are deployed and old processes have
-stopped**, including the stale-membership invalidation path. Use the primary DB.
-
-Build from `server/`:
-
-```sh
-go build -o init-file-counts ./tools/init-file-counts
-```
-
-Set the usual `PGHOST`, `PGPORT`, `PGDATABASE`, `PGUSER`, and TLS/authentication
-settings used by `psql`. Do not put passwords on the command line. The command
-does not read Museum's configuration or run schema migrations.
-
-For the first cohort, run one instance:
-
-```sh
-./init-file-counts -before-user-id 200
-```
-
-Both ID bounds are exclusive. Only paired-NULL rows qualify. The command uses
-one database connection, processes one user at a time, allows 10 seconds per
-attempt, and pauses one second between users. Override `-timeout` or `-pause`
-when needed. `-after-user-id` selects a later range; rerunning a range skips
-already initialized users. Stop with Ctrl-C/SIGTERM if DB load or query latency
-rises. A small ID range does not imply small libraries.
-
-Each attempt reads the version, distinct active owned-file counts, and
-eligibility in one SQL snapshot. It then publishes both counters only if they
-are still NULL and the version is unchanged. Counting takes no file or membership
-row locks; only publication briefly locks that user's usage row. Count-changing
-writers that commit before publication cause this attempt to be skipped; writers
-that follow it maintain the initialized counts. Publication does not change the
-source version.
-
-Unsafe histories stay NULL and are logged with a reason:
-
-- An owned file has no active owned membership and no unrestored Trash row.
- Trash was added later: older cleanup used missing collection references to
- delete objects directly, so missing references do not establish Trash state.
-- An unrestored Trash row conflicts with active owned membership or file ownership.
-- An owned file has active cross-app or unsupported-app memberships.
-- An active Locker membership's actual file ownership disagrees with the legacy
- `f_owner_id` predicate. NULL denormalized owners on old Photos rows are allowed.
-
-Timeouts and version conflicts are also skipped for a later pass. Other database
-errors stop the command. Missing usage rows are never created. Do not reset a
-source version or write zero counts to get a user past a failed check.
-
-API reads remain source-based. Before expanding the cohort or switching reads,
-check the existing `museum_file_count_comparisons_total` match/mismatch metric
-and `file count mismatch` logs during real source reads and file activity.
-No observations is not a successful validation. The trusted-client same-app
-assumption still applies; this command does not add guards to AddFiles/MoveFiles.
diff --git a/server/tools/init-file-counts/main.go b/server/tools/init-file-counts/main.go
deleted file mode 100644
index 64c611b4d8..0000000000
--- a/server/tools/init-file-counts/main.go
+++ /dev/null
@@ -1,79 +0,0 @@
-package main
-
-import (
- "context"
- "database/sql"
- "errors"
- "flag"
- "fmt"
- "log"
- "os"
- "os/signal"
- "syscall"
- "time"
-
- "github.com/ente/museum/pkg/repo"
- _ "github.com/lib/pq"
-)
-
-func main() {
- if err := run(); err != nil && !errors.Is(err, context.Canceled) {
- log.Fatal(err)
- }
-}
-
-func run() error {
- after := flag.Int64("after-user-id", 0, "exclusive lower user ID bound")
- before := flag.Int64("before-user-id", 0, "exclusive upper user ID bound (required)")
- timeout := flag.Duration("timeout", 10*time.Second, "maximum time per user")
- pause := flag.Duration("pause", time.Second, "pause between users")
- flag.Parse()
- if *after < 0 || *before <= *after || *timeout <= 0 || *pause < 0 || flag.NArg() != 0 {
- return fmt.Errorf("require 0 <= after-user-id < before-user-id, positive timeout and nonnegative pause")
- }
- if os.Getenv("PGDATABASE") == "" {
- return fmt.Errorf("PGDATABASE must identify the primary database; connection settings use PG* environment variables")
- }
- ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM)
- defer stop()
- db, err := sql.Open("postgres", "application_name=init-file-counts")
- if err != nil {
- return err
- }
- defer db.Close()
- db.SetMaxOpenConns(1)
- usageRepo := &repo.UsageRepository{DB: db}
-
- for lastUserID := *after; ; {
- attemptCtx, cancel := context.WithTimeout(ctx, *timeout)
- var userID int64
- err := db.QueryRowContext(attemptCtx, `SELECT user_id FROM usage
- WHERE user_id > $1 AND user_id < $2
- AND photos_file_count IS NULL AND locker_file_count IS NULL
- ORDER BY user_id LIMIT 1`, lastUserID, *before).Scan(&userID)
- if err != nil {
- cancel()
- if errors.Is(err, sql.ErrNoRows) {
- return nil
- }
- return err
- }
- lastUserID = userID
- initialized, err := usageRepo.InitializeFileCounts(attemptCtx, userID)
- timedOut := errors.Is(attemptCtx.Err(), context.DeadlineExceeded)
- cancel()
- if err != nil {
- if !timedOut && !errors.Is(err, repo.ErrFileCountIneligible) {
- return fmt.Errorf("user %d: %w", userID, err)
- }
- log.Printf("user_id=%d skipped: %v", userID, err)
- } else {
- log.Printf("user_id=%d initialized=%t", userID, initialized)
- }
- select {
- case <-ctx.Done():
- return ctx.Err()
- case <-time.After(*pause):
- }
- }
-}