| new file mode 100644 |
| index 000000000..2885eeb7b |
| --- /dev/null |
| +++ b/internal/console/opstore_test.go |
| @@ -0,0 +1,828 @@ |
| +package console |
| + |
| +import ( |
| + "database/sql" |
| + "fmt" |
| + "math" |
| + "os" |
| + "path/filepath" |
| + "strings" |
| + "testing" |
| + "time" |
| +) |
| + |
| +// opNow is the fixed clock every operator store test reads from. |
| +var opNow = time.Date(2026, 10, 25, 12, 0, 0, 0, time.UTC) |
| + |
| +func openOpStore(t *testing.T) *Store { |
| + t.Helper() |
| + s, err := Open(filepath.Join(t.TempDir(), "console.db")) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + t.Cleanup(func() { s.Close() }) |
| + return s |
| +} |
| + |
| +func opMust(t *testing.T, err error) { |
| + t.Helper() |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| +} |
| + |
| +func opUser(t *testing.T, s *Store, address string, at time.Time) { |
| + t.Helper() |
| + if _, err := s.EnsureUser(address, at); err != nil { |
| + t.Fatal(err) |
| + } |
| +} |
| + |
| +func TestMigrateOperatorPagesIsIdempotent(t *testing.T) { |
| + path := filepath.Join(t.TempDir(), "console.db") |
| + for i := 0; i < 2; i++ { |
| + s, err := Open(path) |
| + if err != nil { |
| + t.Fatalf("open %d: %v", i+1, err) |
| + } |
| + opMust(t, s.Close()) |
| + } |
| + s, err := Open(path) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + defer s.Close() |
| + want := map[string]string{ |
| + "audit_by_time": "audit", |
| + "audit_by_account": "audit", |
| + "audit_by_action": "audit", |
| + "sessions_by_time": "sessions", |
| + "users_by_created": "users", |
| + "users_by_last_seen": "users", |
| + "memberships_by_address": "memberships", |
| + "apps_by_creator": "apps", |
| + } |
| + for index, table := range want { |
| + rows, err := s.db.Query(`SELECT name FROM pragma_index_list(?)`, table) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + found := false |
| + for rows.Next() { |
| + var n string |
| + opMust(t, rows.Scan(&n)) |
| + if n == index { |
| + found = true |
| + } |
| + } |
| + opMust(t, rows.Close()) |
| + if !found { |
| + t.Errorf("index %s missing on %s", index, table) |
| + } |
| + } |
| + var n int |
| + opMust(t, s.db.QueryRow(`SELECT COUNT(*) FROM pragma_table_info('users') WHERE name = 'last_seen'`).Scan(&n)) |
| + if n != 1 { |
| + t.Fatalf("users.last_seen columns = %d, want 1", n) |
| + } |
| +} |
| + |
| +// opPlanCase is one row of the query-plan witness: a statement the operator |
| +// reads run, arguments of the shape they pass, the plan lines that must |
| +// appear (each a substring of some line) and the ones that must not. |
| +type opPlanCase struct { |
| + name string |
| + sql string |
| + args []any |
| + want []string |
| + notWant []string |
| + // mergeSorts is how many "USE TEMP B-TREE FOR ORDER BY" lines a MERGE |
| + // (UNION) may carry, one per half; 0 everywhere else. |
| + mergeSorts int |
| +} |
| + |
| +// opPlanForbidden holds for every operator query: no per-row subquery and |
| +// no whole-result sort. |
| +var opPlanForbidden = []string{"CORRELATED", "USE TEMP B-TREE FOR ORDER BY"} |
| + |
| +var opQueryPlans = []opPlanCase{ |
| + {name: "people total", sql: opSQLPeopleTotal, |
| + want: []string{"SCAN users USING COVERING INDEX"}}, |
| + {name: "people matching", sql: opSQLPeopleMatching, args: []any{`%exam%`}, |
| + want: []string{"SCAN users USING COVERING INDEX"}}, |
| + // The UNION runs as a MERGE whose two halves are each sorted by |
| + // address: those two sorts hold only the addresses in the window (the |
| + // spec's allowance for the UNION's own temp B-tree) and are the only |
| + // sorts any operator query is allowed. |
| + {name: "active", sql: opSQLActive, args: []any{int64(1)}, mergeSorts: 2, |
| + want: []string{"MERGE (UNION)", "SEARCH users USING INDEX users_by_last_seen (last_seen>?)", |
| + "SEARCH sessions USING COVERING INDEX sessions_by_time (created_at>?)"}, |
| + notWant: []string{"SCAN users", "SCAN sessions"}}, |
| + {name: "new people", sql: opSQLNewPeople, args: []any{int64(1), int64(2)}, |
| + want: []string{"SEARCH users USING COVERING INDEX users_by_created (created_at>? AND created_at<?)"}, |
| + notWant: []string{"SCAN users"}}, |
| + {name: "per day", sql: opSQLPerDay, args: []any{int64(1), int64(2)}, |
| + want: []string{"SEARCH users USING COVERING INDEX users_by_created (created_at>? AND created_at<?)"}, |
| + notWant: []string{"SCAN users"}}, |
| + {name: "new accounts", sql: opSQLNewAccounts, args: []any{int64(1), int64(2)}, |
| + want: []string{"SCAN accounts"}}, |
| + {name: "apps", sql: opSQLApps, args: []any{int64(1), int64(2)}, |
| + want: []string{"SCAN apps"}}, |
| + {name: "deploys", sql: opSQLDeploys, args: []any{int64(1), "promote", "rollback"}, |
| + want: []string{"SEARCH audit USING INDEX audit_by_time (created_at>?)"}, |
| + notWant: []string{"SCAN audit", "audit_by_action"}}, |
| + {name: "newest people", sql: opSQLNewestPeople, args: []any{50}, |
| + want: []string{"SCAN users USING INDEX users_by_created", |
| + "SEARCH memberships USING INDEX memberships_by_address (address=?)", |
| + "SEARCH accounts USING INTEGER PRIMARY KEY (rowid=?)", |
| + "SEARCH apps USING INDEX apps_by_creator (created_by=?)"}, |
| + notWant: []string{"SCAN memberships", "SCAN apps", "SCAN accounts"}}, |
| + {name: "people page", sql: opSQLPeoplePage, args: []any{"", "%%", 50, 0}, |
| + want: []string{"SCAN users USING INDEX users_by_created", |
| + "SEARCH memberships USING INDEX memberships_by_address (address=?)", |
| + "SEARCH accounts USING INTEGER PRIMARY KEY (rowid=?)", |
| + "SEARCH apps USING INDEX apps_by_creator (created_by=?)"}, |
| + notWant: []string{"SCAN memberships", "SCAN apps", "SCAN accounts"}}, |
| + {name: "people page searched", sql: opSQLPeoplePage, args: []any{"exam", `%exam%`, 50, 0}, |
| + want: []string{"SCAN users", |
| + "SEARCH memberships USING INDEX memberships_by_address (address=?)", |
| + "SEARCH apps USING INDEX apps_by_creator (created_by=?)"}, |
| + notWant: []string{"SCAN memberships", "SCAN apps"}}, |
| + {name: "accounts total", sql: opSQLAccountsTotal, args: []any{"", "%%"}, |
| + want: []string{"SCAN accounts"}}, |
| + {name: "accounts page", sql: opSQLAccountsPage, args: []any{"", "%%", 50, 0}, |
| + want: []string{"SCAN accounts", |
| + "SEARCH account_plans USING INTEGER PRIMARY KEY (rowid=?)", |
| + "SEARCH apps USING INDEX sqlite_autoindex_apps_1 (account_id=?)", |
| + "SEARCH memberships USING COVERING INDEX sqlite_autoindex_memberships_1 (account_id=?)"}, |
| + notWant: []string{"SCAN apps", "SCAN memberships", "SCAN account_plans"}}, |
| + {name: "account by sqid", sql: opSQLAccountBySqid, args: []any{"abcd"}, |
| + want: []string{"SEARCH accounts USING INDEX sqlite_autoindex_accounts_1 (sqid=?)"}}, |
| + {name: "touch last seen", sql: opSQLTouchLastSeen, args: []any{int64(2), "ann@example.com", int64(2)}, |
| + want: []string{"SEARCH users USING INDEX sqlite_autoindex_users_1 (address=?)"}}, |
| + {name: "feed all", sql: opSQLFeedAll, args: []any{50}, |
| + want: []string{"SCAN audit", "SEARCH accounts USING INTEGER PRIMARY KEY (rowid=?)"}, |
| + notWant: []string{"audit USING INDEX", "SCAN accounts"}}, |
| + {name: "feed before", sql: opSQLFeedBefore, args: []any{int64(71), 50}, |
| + want: []string{"SEARCH audit USING INTEGER PRIMARY KEY (rowid<?)", "SEARCH accounts USING INTEGER PRIMARY KEY (rowid=?)"}, |
| + notWant: []string{"SCAN audit", "SCAN accounts"}}, |
| + {name: "feed account", sql: opSQLFeedAccount, args: []any{int64(7), int64(math.MaxInt64), 50}, |
| + want: []string{"SEARCH audit USING INDEX audit_by_account (account_id=? AND id<?)"}, |
| + notWant: []string{"SCAN audit", "SCAN accounts"}}, |
| + {name: "feed account actions", sql: opSQLFeedAccountActions, args: []any{int64(7), int64(math.MaxInt64), `["promote","rollback"]`, 50}, |
| + want: []string{"SEARCH audit USING INDEX audit_by_account (account_id=? AND id<?)"}, |
| + notWant: []string{"SCAN audit", "audit_by_action", "SCAN accounts"}}, |
| + {name: "feed account other", sql: opSQLFeedAccountOther, args: []any{int64(7), int64(math.MaxInt64), `["promote","rollback"]`, 50}, |
| + want: []string{"SEARCH audit USING INDEX audit_by_account (account_id=? AND id<?)"}, |
| + notWant: []string{"SCAN audit", "audit_by_action", "SCAN accounts"}}, |
| + {name: "feed action", sql: opSQLFeedAction, args: []any{"promote", int64(math.MaxInt64), 50}, |
| + want: []string{"SEARCH audit USING INDEX audit_by_action (action=? AND id<?)"}, |
| + notWant: []string{"SCAN audit", "SCAN accounts"}}, |
| + {name: "feed other", sql: opSQLFeedOther, args: []any{`["promote","rollback"]`, 50}, |
| + want: []string{"SCAN audit"}, |
| + notWant: []string{"audit USING INDEX", "SCAN accounts"}}, |
| + {name: "feed other before", sql: opSQLFeedOtherBefore, args: []any{int64(71), `["promote","rollback"]`, 50}, |
| + want: []string{"SEARCH audit USING INTEGER PRIMARY KEY (rowid<?)"}, |
| + notWant: []string{"SCAN audit", "SCAN accounts"}}, |
| +} |
| + |
| +// opSQLByName names every statement constant in opstore.go; the fragments |
| +// the statements are built from map to "" and need no row of their own. |
| +var opSQLByName = map[string]string{ |
| + "opSQLPeopleTotal": opSQLPeopleTotal, "opSQLPeopleMatching": opSQLPeopleMatching, |
| + "opSQLActive": opSQLActive, "opSQLNewPeople": opSQLNewPeople, "opSQLNewAccounts": opSQLNewAccounts, |
| + "opSQLApps": opSQLApps, "opSQLDeploys": opSQLDeploys, "opSQLPerDay": opSQLPerDay, |
| + "opSQLNewestPeople": opSQLNewestPeople, "opSQLPeoplePage": opSQLPeoplePage, |
| + "opSQLAccountsTotal": opSQLAccountsTotal, "opSQLAccountsPage": opSQLAccountsPage, |
| + "opSQLAccountBySqid": opSQLAccountBySqid, "opSQLTouchLastSeen": opSQLTouchLastSeen, |
| + "opSQLFeedAll": opSQLFeedAll, "opSQLFeedBefore": opSQLFeedBefore, "opSQLFeedAccount": opSQLFeedAccount, |
| + "opSQLFeedAccountActions": opSQLFeedAccountActions, "opSQLFeedAccountOther": opSQLFeedAccountOther, |
| + "opSQLFeedAction": opSQLFeedAction, "opSQLFeedOther": opSQLFeedOther, "opSQLFeedOtherBefore": opSQLFeedOtherBefore, |
| + "opSQLPersonColumns": "", "opSQLPersonJoins": "", "opSQLFeedColumns": "", |
| +} |
| + |
| +// opPlan is the EXPLAIN QUERY PLAN detail lines of one statement. |
| +func opPlan(db sqlHandle, query string, args ...any) ([]string, error) { |
| + rows, err := db.Query("EXPLAIN QUERY PLAN "+query, args...) |
| + if err != nil { |
| + return nil, err |
| + } |
| + defer rows.Close() |
| + var out []string |
| + for rows.Next() { |
| + var id, parent, unused int |
| + var detail string |
| + if err := rows.Scan(&id, &parent, &unused, &detail); err != nil { |
| + return nil, err |
| + } |
| + out = append(out, detail) |
| + } |
| + return out, rows.Err() |
| +} |
| + |
| +// opPlanProblems checks one witness row against the plan the database |
| +// would run, returning what is wrong with it. |
| +func opPlanProblems(db sqlHandle, c opPlanCase) ([]string, []string, error) { |
| + plan, err := opPlan(db, c.sql, c.args...) |
| + if err != nil { |
| + return nil, nil, err |
| + } |
| + var problems []string |
| + has := func(s string) bool { |
| + for _, line := range plan { |
| + if strings.Contains(line, s) { |
| + return true |
| + } |
| + } |
| + return false |
| + } |
| + for _, w := range c.want { |
| + if !has(w) { |
| + problems = append(problems, "missing "+w) |
| + } |
| + } |
| + sorts := 0 |
| + for _, line := range plan { |
| + if strings.Contains(line, "USE TEMP B-TREE FOR ORDER BY") { |
| + sorts++ |
| + } |
| + } |
| + if sorts > 0 && (sorts > c.mergeSorts || !has("MERGE (UNION)")) { |
| + problems = append(problems, "has USE TEMP B-TREE FOR ORDER BY") |
| + } |
| + for _, w := range append(append([]string(nil), opPlanForbidden...), c.notWant...) { |
| + if w != "USE TEMP B-TREE FOR ORDER BY" && has(w) { |
| + problems = append(problems, "has "+w) |
| + } |
| + } |
| + return plan, problems, nil |
| +} |
| + |
| +// TestOperatorQueryPlans is the witness that every statement the operator |
| +// reads run takes its intended access pattern, on a store migrated by Open. |
| +func TestOperatorQueryPlans(t *testing.T) { |
| + s := openOpStore(t) |
| + for _, c := range opQueryPlans { |
| + plan, problems, err := opPlanProblems(s.db, c) |
| + if err != nil { |
| + t.Errorf("%s: %v", c.name, err) |
| + continue |
| + } |
| + if len(problems) > 0 { |
| + t.Errorf("%s: %s\nplan:\n %s", c.name, strings.Join(problems, "; "), strings.Join(plan, "\n ")) |
| + } |
| + } |
| + // Every opSQL constant in opstore.go has a row. |
| + src, err := os.ReadFile("opstore.go") |
| + opMust(t, err) |
| + covered := map[string]bool{} |
| + for _, c := range opQueryPlans { |
| + covered[c.sql] = true |
| + } |
| + for _, line := range strings.Split(string(src), "\n") { |
| + line = strings.TrimSpace(line) |
| + if !strings.HasPrefix(line, "opSQL") || !strings.Contains(line, "=") { |
| + continue |
| + } |
| + name := strings.TrimSpace(strings.SplitN(line, "=", 2)[0]) |
| + stmt, known := opSQLByName[name] |
| + if !known { |
| + t.Errorf("%s is not in opSQLByName", name) |
| + } else if stmt != "" && !covered[stmt] { |
| + t.Errorf("%s has no row in opQueryPlans", name) |
| + } |
| + } |
| + |
| + // The check bites. Rewritten in the earlier per-user EXISTS form, the |
| + // active count is refused for its correlated subquery. |
| + exists := opPlanCase{name: "active, per-user EXISTS", sql: `SELECT COUNT(*) FROM users |
| +WHERE last_seen >= ?1 OR EXISTS (SELECT 1 FROM sessions WHERE sessions.address = users.address AND sessions.created_at >= ?1)`, |
| + args: []any{int64(1)}} |
| + if _, problems, err := opPlanProblems(s.db, exists); err != nil || !opHas(problems, "has CORRELATED") { |
| + t.Errorf("the EXISTS form was not refused: %v %v", problems, err) |
| + } |
| + // Without sessions_by_time, the active count's sessions half scans. |
| + _, err = s.db.Exec(`DROP INDEX sessions_by_time`) |
| + opMust(t, err) |
| + if _, problems, err := opPlanProblems(s.db, opQueryPlans[2]); err != nil || !opHas(problems, "has SCAN sessions") { |
| + t.Errorf("dropping sessions_by_time was not caught: %v %v", problems, err) |
| + } |
| +} |
| + |
| +func opHas(list []string, s string) bool { |
| + for _, l := range list { |
| + if l == s { |
| + return true |
| + } |
| + } |
| + return false |
| +} |
| + |
| +func TestTouchLastSeenNeverMovesBack(t *testing.T) { |
| + s := openOpStore(t) |
| + opUser(t, s, "ann@example.com", opNow.Add(-24*time.Hour)) |
| + opMust(t, s.TouchLastSeen("ann@example.com", opNow)) |
| + opMust(t, s.TouchLastSeen("ann@example.com", opNow.Add(-time.Hour))) |
| + var seen int64 |
| + opMust(t, s.db.QueryRow(`SELECT last_seen FROM users WHERE address = 'ann@example.com'`).Scan(&seen)) |
| + if seen != opNow.Unix() { |
| + t.Fatalf("last_seen = %d, want %d", seen, opNow.Unix()) |
| + } |
| + opMust(t, s.TouchLastSeen("nobody@example.com", opNow)) |
| + var n int |
| + opMust(t, s.db.QueryRow(`SELECT COUNT(*) FROM users`).Scan(&n)) |
| + if n != 1 { |
| + t.Fatalf("users = %d after touching an unknown address, want 1", n) |
| + } |
| +} |
| + |
| +func TestOperatorCountsWindows(t *testing.T) { |
| + s := openOpStore(t) |
| + people := []struct { |
| + addr string |
| + ago time.Duration |
| + }{ |
| + {"a@example.com", time.Hour}, |
| + {"b@example.com", 6 * 24 * time.Hour}, |
| + {"c@example.com", 8 * 24 * time.Hour}, |
| + {"d@example.com", 13 * 24 * time.Hour}, |
| + {"e@example.com", 20 * 24 * time.Hour}, |
| + } |
| + for _, p := range people { |
| + opUser(t, s, p.addr, opNow.Add(-p.ago)) |
| + } |
| + acctA, acctB := testAccountID(), testAccountID() |
| + opMust(t, s.CreateAccount(acctA, "aaaa", "shop", "a@example.com", opNow.Add(-2*24*time.Hour))) |
| + opMust(t, s.CreateAccount(acctB, "bbbb", "notes", "c@example.com", opNow.Add(-10*24*time.Hour))) |
| + for _, app := range []string{"shop", "blog", "gone"} { |
| + if _, err := s.CreateAppIn(acctA, app, "a@example.com", opNow.Add(-3*24*time.Hour)); err != nil { |
| + t.Fatal(err) |
| + } |
| + } |
| + opMust(t, s.TrashAppRow(acctA, "gone", opNow.Add(-time.Hour))) |
| + opMust(t, s.RecordEvent(acctA, "shop", "a@example.com", "promote", "promoted v1 to stable", opNow.Add(-2*time.Hour))) |
| + opMust(t, s.RecordEvent(acctA, "shop", "a@example.com", "promote", "promoted v2 to stable", opNow.Add(-time.Hour))) |
| + opMust(t, s.RecordEvent(acctA, "blog", "a@example.com", "rollback", "rolled back stable to v1", opNow.Add(-time.Hour))) |
| + opMust(t, s.RecordEvent(acctA, "blog", "a@example.com", "promote", "promoted v0 to stable", opNow.Add(-24*time.Hour))) |
| + opMust(t, s.RecordEvent(acctA, "blog", "a@example.com", "rename", "renamed", opNow.Add(-time.Hour))) |
| + opMust(t, s.TouchLastSeen("a@example.com", opNow.Add(-time.Hour))) |
| + opMust(t, s.TouchLastSeen("b@example.com", opNow.Add(-5*24*time.Hour))) |
| + if _, err := s.CreateSessionMethod("c@example.com", "", MethodKeymail, opNow.Add(-3*24*time.Hour)); err != nil { |
| + t.Fatal(err) |
| + } |
| + |
| + got, err := s.OperatorCounts(opNow) |
| + opMust(t, err) |
| + want := OperatorCounts{People: 5, Active30: 3, Active7: 3, ActiveToday: 1, |
| + NewPeople7: 2, NewPeoplePrev7: 2, NewAccounts7: 1, NewAccountsPrev7: 1, |
| + Apps: 2, NewApps7: 2, DeploysToday: 3, DeployApps: 2} |
| + if got != want { |
| + t.Fatalf("OperatorCounts =\n %+v\nwant\n %+v", got, want) |
| + } |
| +} |
| + |
| +func TestNewPeoplePerDayFillsZeroDaysAndIgnoresFuture(t *testing.T) { |
| + s := openOpStore(t) |
| + midnight := time.Date(2026, 10, 25, 0, 0, 0, 0, time.UTC) |
| + opUser(t, s, "t1@example.com", midnight) |
| + opUser(t, s, "t2@example.com", opNow.Add(-time.Hour)) |
| + opUser(t, s, "t3@example.com", opNow) |
| + opUser(t, s, "old@example.com", midnight.Add(-29*24*time.Hour+time.Minute)) |
| + opUser(t, s, "older@example.com", midnight.Add(-29*24*time.Hour-time.Minute)) |
| + opUser(t, s, "future@example.com", opNow.Add(time.Hour)) |
| + days, err := s.NewPeoplePerDay(opNow, 30) |
| + opMust(t, err) |
| + if len(days) != 30 { |
| + t.Fatalf("%d entries, want 30", len(days)) |
| + } |
| + if days[0].N != 1 || days[29].N != 3 { |
| + t.Fatalf("first %d, last %d, want 1 and 3", days[0].N, days[29].N) |
| + } |
| + for i := 1; i < 29; i++ { |
| + if days[i].N != 0 { |
| + t.Fatalf("day %d = %d, want 0", i, days[i].N) |
| + } |
| + if !days[i].Day.Equal(midnight.Add(time.Duration(i-29) * 24 * time.Hour)) { |
| + t.Fatalf("day %d is %v", i, days[i].Day) |
| + } |
| + } |
| + if !days[29].Day.Equal(midnight) || days[29].Day.Location() != time.UTC { |
| + t.Fatalf("last day %v, want %v UTC", days[29].Day, midnight) |
| + } |
| +} |
| + |
| +func TestNewestPeopleAndPeoplePage(t *testing.T) { |
| + s := openOpStore(t) |
| + for i, a := range []string{"ann@example.com", "bob@keymail.dev", "cy@keymail.dev", "di@keymail.dev", "ed@keymail.dev"} { |
| + opUser(t, s, a, opNow.Add(time.Duration(i-10)*time.Hour)) |
| + } |
| + acct := testAccountID() |
| + opMust(t, s.CreateAccount(acct, "aaaa", "shop", "ed@keymail.dev", opNow.Add(-time.Hour))) |
| + if _, err := s.CreateAppIn(acct, "shop", "ed@keymail.dev", opNow); err != nil { |
| + t.Fatal(err) |
| + } |
| + opMust(t, s.TouchLastSeen("ed@keymail.dev", opNow)) |
| + newest, err := s.NewestPeople(2) |
| + opMust(t, err) |
| + if len(newest) != 2 || newest[0].Address != "ed@keymail.dev" || newest[1].Address != "di@keymail.dev" { |
| + t.Fatalf("NewestPeople(2) = %+v", newest) |
| + } |
| + ed := newest[0] |
| + if ed.Accounts != 1 || ed.FirstAccount != "shop" || ed.Apps != 1 || !ed.LastSeen.Equal(opNow) || |
| + !ed.Joined.Equal(opNow.Add(-6*time.Hour)) { |
| + t.Fatalf("ed = %+v", ed) |
| + } |
| + if !newest[1].LastSeen.IsZero() { |
| + t.Fatalf("di was never seen, LastSeen = %v", newest[1].LastSeen) |
| + } |
| + page, total, err := s.PeoplePage("", 0, 2) |
| + opMust(t, err) |
| + if total != 5 || len(page) != 2 || page[0].Address != "ed@keymail.dev" { |
| + t.Fatalf("PeoplePage = %+v, %d", page, total) |
| + } |
| + page, total, err = s.PeoplePage("", 4, 2) |
| + opMust(t, err) |
| + if total != 5 || len(page) != 1 || page[0].Address != "ann@example.com" { |
| + t.Fatalf("PeoplePage offset 4 = %+v, %d", page, total) |
| + } |
| + page, total, err = s.PeoplePage("exam", 0, 50) |
| + opMust(t, err) |
| + if total != 1 || len(page) != 1 || page[0].Address != "ann@example.com" { |
| + t.Fatalf("PeoplePage(exam) = %+v, %d", page, total) |
| + } |
| +} |
| + |
| +func TestNewestPeopleBreaksTiesByAddress(t *testing.T) { |
| + s := openOpStore(t) |
| + for _, a := range []string{"zed@example.com", "amy@example.com", "max@example.com"} { |
| + opUser(t, s, a, opNow) |
| + } |
| + got, err := s.NewestPeople(3) |
| + opMust(t, err) |
| + if len(got) != 3 || got[0].Address != "amy@example.com" || got[1].Address != "max@example.com" || got[2].Address != "zed@example.com" { |
| + t.Fatalf("NewestPeople = %+v", got) |
| + } |
| +} |
| + |
| +func TestPeopleAndAccountsSearchIsLiteral(t *testing.T) { |
| + s := openOpStore(t) |
| + for _, a := range []string{"a%b@example.com", "ab@example.com", "o'brien@example.com"} { |
| + opUser(t, s, a, opNow) |
| + } |
| + long := strings.Repeat("x", 2000) |
| + for _, tc := range []struct { |
| + q string |
| + want int |
| + }{{"%", 1}, {"_", 0}, {"o'brien", 1}, {`\`, 0}, {long, 0}} { |
| + page, total, err := s.PeoplePage(tc.q, 0, 50) |
| + if err != nil { |
| + t.Fatalf("PeoplePage(%.20q): %v", tc.q, err) |
| + } |
| + if total != tc.want || len(page) != tc.want { |
| + t.Fatalf("PeoplePage(%.20q) = %d rows, total %d, want %d", tc.q, len(page), total, tc.want) |
| + } |
| + } |
| + page, _, err := s.PeoplePage("%", 0, 50) |
| + opMust(t, err) |
| + if page[0].Address != "a%b@example.com" { |
| + t.Fatalf("%% matched %q", page[0].Address) |
| + } |
| + |
| + opMust(t, s.CreateAccount(testAccountID(), "pct1", "50% off", "ab@example.com", opNow)) |
| + opMust(t, s.CreateAccount(testAccountID(), "plain", "500 off", "ab@example.com", opNow)) |
| + opMust(t, s.CreateAccount(testAccountID(), "quote", "o'brien's", "ab@example.com", opNow)) |
| + for _, tc := range []struct { |
| + q string |
| + want int |
| + }{{"%", 1}, {"_", 0}, {"o'brien", 1}, {`\`, 0}, {long, 0}, {"pct", 1}} { |
| + page, total, err := s.AccountsPage(tc.q, 0, 50) |
| + if err != nil { |
| + t.Fatalf("AccountsPage(%.20q): %v", tc.q, err) |
| + } |
| + if total != tc.want || len(page) != tc.want { |
| + t.Fatalf("AccountsPage(%.20q) = %d rows, total %d, want %d", tc.q, len(page), total, tc.want) |
| + } |
| + } |
| + page2, _, err := s.AccountsPage("%", 0, 50) |
| + opMust(t, err) |
| + if page2[0].Name != "50% off" { |
| + t.Fatalf("%% matched %q", page2[0].Name) |
| + } |
| +} |
| + |
| +func TestAccountsPageColumns(t *testing.T) { |
| + s := openOpStore(t) |
| + older, newer, gone := testAccountID(), testAccountID(), testAccountID() |
| + opMust(t, s.CreateAccount(older, "aaaa", "shop", "ann@example.com", opNow.Add(-48*time.Hour))) |
| + opMust(t, s.CreateAccount(newer, "bbbb", "notes", "ann@example.com", opNow.Add(-time.Hour))) |
| + opMust(t, s.CreateAccount(gone, "cccc", "old", "ann@example.com", opNow.Add(-time.Hour))) |
| + opMust(t, s.DeleteAccount(gone, opNow)) |
| + opMust(t, s.AddMember(older, "bob@example.com", RoleMember, opNow)) |
| + for _, app := range []string{"shop", "blog", "gone"} { |
| + if _, err := s.CreateAppIn(older, app, "ann@example.com", opNow); err != nil { |
| + t.Fatal(err) |
| + } |
| + } |
| + opMust(t, s.TrashAppRow(older, "gone", opNow)) |
| + _, err := s.SetAccountPlan(older, "personal", nil, "operator", nil, "", "ann@example.com", opNow) |
| + opMust(t, err) |
| + page, total, err := s.AccountsPage("", 0, 50) |
| + opMust(t, err) |
| + if total != 2 || len(page) != 2 { |
| + t.Fatalf("AccountsPage = %+v, %d", page, total) |
| + } |
| + if page[0].Sqid != "bbbb" || page[0].Plan != "" || page[0].Apps != 0 || page[0].Members != 1 { |
| + t.Fatalf("newest = %+v", page[0]) |
| + } |
| + if page[1].Sqid != "aaaa" || page[1].Plan != "personal" || page[1].Apps != 2 || page[1].Members != 2 || |
| + !page[1].Created.Equal(opNow.Add(-48*time.Hour)) || page[1].ID != older || page[1].Name != "shop" { |
| + t.Fatalf("older = %+v", page[1]) |
| + } |
| + op, err := s.OperatorAccountBySqid("cccc") |
| + opMust(t, err) |
| + if op == nil || !op.Deleted || op.ID != gone || op.Name != "old" { |
| + t.Fatalf("OperatorAccountBySqid(deleted) = %+v", op) |
| + } |
| + op, err = s.OperatorAccountBySqid("aaaa") |
| + opMust(t, err) |
| + if op == nil || op.Deleted || op.ID != older { |
| + t.Fatalf("OperatorAccountBySqid(live) = %+v", op) |
| + } |
| + op, err = s.OperatorAccountBySqid("zzzz") |
| + if op != nil || err != nil { |
| + t.Fatalf("OperatorAccountBySqid(none) = %+v, %v", op, err) |
| + } |
| +} |
| + |
| +func TestOperatorReadsSurviveMissingAndDeletedAccounts(t *testing.T) { |
| + s := openOpStore(t) |
| + opUser(t, s, "loner@example.com", opNow.Add(-2*time.Hour)) |
| + opUser(t, s, "left@example.com", opNow.Add(-time.Hour)) |
| + gone := testAccountID() |
| + opMust(t, s.CreateAccount(gone, "gone", "closed shop", "left@example.com", opNow.Add(-time.Hour))) |
| + opMust(t, s.RecordEvent(gone, "", "left@example.com", "account-created", "created", opNow.Add(-time.Hour))) |
| + opMust(t, s.DeleteAccount(gone, opNow)) |
| + // A membership row left on a deleted account (DeleteAccount removes |
| + // them; an older console may not have) still names no first account. |
| + _, err := s.db.Exec(`INSERT INTO memberships (account_id, address, role, added_at) VALUES (?, ?, ?, ?)`, |
| + gone, "left@example.com", RoleOwner, opNow.Unix()) |
| + opMust(t, err) |
| + opMust(t, s.RecordEvent(0, "", "loner@example.com", "signin", "signed in", opNow)) |
| + |
| + people, err := s.NewestPeople(10) |
| + opMust(t, err) |
| + if len(people) != 2 { |
| + t.Fatalf("NewestPeople = %+v", people) |
| + } |
| + for _, p := range people { |
| + if p.Accounts != 0 || p.FirstAccount != "" || p.Apps != 0 { |
| + t.Fatalf("%s = %+v, want no accounts", p.Address, p) |
| + } |
| + } |
| + c, err := s.OperatorCounts(opNow) |
| + opMust(t, err) |
| + if c.People != 2 { |
| + t.Fatalf("People = %d, want 2", c.People) |
| + } |
| + feed, err := s.ActivityFeed(ActivityFilter{}, 0, 10) |
| + opMust(t, err) |
| + if len(feed) != 2 { |
| + t.Fatalf("feed = %+v", feed) |
| + } |
| + if feed[0].Action != "signin" || feed[0].AccountName != "" || feed[0].AccountSqid != "" { |
| + t.Fatalf("account-less row = %+v", feed[0]) |
| + } |
| + if feed[1].AccountName != "closed shop" || feed[1].AccountSqid != "gone" { |
| + t.Fatalf("deleted account's row = %+v", feed[1]) |
| + } |
| +} |
| + |
| +func TestActivityFeedFiltersAndPages(t *testing.T) { |
| + s := openOpStore(t) |
| + a, b := testAccountID(), testAccountID() |
| + opMust(t, s.CreateAccount(a, "aaaa", "shop", "ann@example.com", opNow)) |
| + opMust(t, s.CreateAccount(b, "bbbb", "notes", "ann@example.com", opNow)) |
| + actions := []string{"promote", "rename", "rollback"} |
| + for i := 1; i <= 120; i++ { |
| + acct := a |
| + if i%2 == 0 { |
| + acct = b |
| + } |
| + opMust(t, s.RecordEvent(acct, "shop", "ann@example.com", actions[i%3], fmt.Sprintf("row %d", i), opNow.Add(time.Duration(i)*time.Second))) |
| + } |
| + ids := func(rows []FeedRow) []int64 { |
| + var out []int64 |
| + for _, r := range rows { |
| + out = append(out, r.ID) |
| + } |
| + return out |
| + } |
| + page, err := s.ActivityFeed(ActivityFilter{}, 0, 50) |
| + opMust(t, err) |
| + if len(page) != 50 || page[0].ID != 120 || page[49].ID != 71 { |
| + t.Fatalf("first page = %v", ids(page)) |
| + } |
| + if page[0].Detail != "row 120" || page[0].AccountSqid != "bbbb" || page[0].AccountName != "notes" || |
| + page[0].App != "shop" || page[0].Address != "ann@example.com" || page[0].Action != "promote" || |
| + !page[0].At.Equal(opNow.Add(120*time.Second)) { |
| + t.Fatalf("row 120 = %+v", page[0]) |
| + } |
| + page, err = s.ActivityFeed(ActivityFilter{}, 71, 50) |
| + opMust(t, err) |
| + if len(page) != 50 || page[0].ID != 70 || page[49].ID != 21 { |
| + t.Fatalf("second page = %v", ids(page)) |
| + } |
| + check := func(f ActivityFilter, before int64, limit int, keep func(id int64, acct int64, action string) bool) { |
| + t.Helper() |
| + got, err := s.ActivityFeed(f, before, limit) |
| + opMust(t, err) |
| + var want []int64 |
| + for i := int64(120); i >= 1 && len(want) < limit; i-- { |
| + if before > 0 && i >= before { |
| + continue |
| + } |
| + acct := a |
| + if i%2 == 0 { |
| + acct = b |
| + } |
| + if keep(i, acct, actions[i%3]) { |
| + want = append(want, i) |
| + } |
| + } |
| + if fmt.Sprint(ids(got)) != fmt.Sprint(want) { |
| + t.Fatalf("ActivityFeed(%+v, %d, %d) = %v, want %v", f, before, limit, ids(got), want) |
| + } |
| + } |
| + deploys := func(action string) bool { return action == "promote" || action == "rollback" } |
| + check(ActivityFilter{AccountID: a}, 0, 50, func(_, acct int64, _ string) bool { return acct == a }) |
| + check(ActivityFilter{AccountID: a}, 60, 50, func(_, acct int64, _ string) bool { return acct == a }) |
| + check(ActivityFilter{Actions: deployActions}, 0, 50, func(_, _ int64, act string) bool { return deploys(act) }) |
| + check(ActivityFilter{Actions: deployActions}, 90, 50, func(_, _ int64, act string) bool { return deploys(act) }) |
| + check(ActivityFilter{Actions: []string{"rename", "rename"}}, 0, 50, func(_, _ int64, act string) bool { return act == "rename" }) |
| + check(ActivityFilter{Exclude: deployActions}, 0, 50, func(_, _ int64, act string) bool { return !deploys(act) }) |
| + check(ActivityFilter{Exclude: deployActions}, 100, 20, func(_, _ int64, act string) bool { return !deploys(act) }) |
| + check(ActivityFilter{AccountID: b, Actions: deployActions}, 0, 50, func(_, acct int64, act string) bool { return acct == b && deploys(act) }) |
| + check(ActivityFilter{AccountID: b, Exclude: deployActions}, 0, 50, func(_, acct int64, act string) bool { return acct == b && !deploys(act) }) |
| + check(ActivityFilter{AccountID: -1}, 0, 50, func(_, _ int64, _ string) bool { return false }) |
| +} |
| + |
| +func TestGatedStoreOpensWithTheNewSchema(t *testing.T) { |
| + cx := newClaimCase(t) |
| + if err := cx.st.TouchLastSeen(claimFxOwner, time.Now()); err != nil { |
| + t.Fatal(err) |
| + } |
| +} |
| + |
| +// opSeedScale writes the scale fixture in one transaction: 20,000 people, |
| +// 60,000 sessions over 30 days, 2,000 accounts with their memberships, 8,000 |
| +// apps and 200,000 audit rows, 50 of them of a rare kind. |
| +func opSeedScale(t *testing.T, s *Store, now time.Time) (account int64) { |
| + t.Helper() |
| + db, ok := s.db.(*sql.DB) |
| + if !ok { |
| + t.Fatalf("store handle is %T", s.db) |
| + } |
| + tx, err := db.Begin() |
| + opMust(t, err) |
| + defer tx.Rollback() |
| + exec := func(stmt *sql.Stmt, args ...any) { |
| + if _, err := stmt.Exec(args...); err != nil { |
| + t.Fatal(err) |
| + } |
| + } |
| + prep := func(q string) *sql.Stmt { |
| + st, err := tx.Prepare(q) |
| + opMust(t, err) |
| + return st |
| + } |
| + day := int64(24 * 60 * 60) |
| + n := now.Unix() |
| + users := prep(`INSERT INTO users (address, created_at, last_seen) VALUES (?, ?, ?)`) |
| + for i := 0; i < 20000; i++ { |
| + seen := int64(0) |
| + if i%3 == 0 { |
| + seen = n - int64(i%40)*day |
| + } |
| + exec(users, fmt.Sprintf("p%05d@example.com", i), n-int64(i)*900, seen) |
| + } |
| + sessions := prep(`INSERT INTO sessions (token_hash, address, created_at, expires_at) VALUES (?, ?, ?, ?)`) |
| + for i := 0; i < 60000; i++ { |
| + at := n - int64(i)*43 |
| + exec(sessions, fmt.Sprintf("h%06d", i), fmt.Sprintf("p%05d@example.com", (i*7)%20000), at, at+30*day) |
| + } |
| + accounts := prep(`INSERT INTO accounts (id, sqid, name, created_at) VALUES (?, ?, ?, ?)`) |
| + members := prep(`INSERT INTO memberships (account_id, address, role, added_at) VALUES (?, ?, ?, ?)`) |
| + for i := 0; i < 2000; i++ { |
| + id := int64(1000 + i) |
| + exec(accounts, id, fmt.Sprintf("s%04d", i), fmt.Sprintf("shop %d", i), n-int64(2000-i)*3600) |
| + for j := 0; j < 10; j++ { |
| + exec(members, id, fmt.Sprintf("p%05d@example.com", (i*10+j)%20000), RoleMember, n-int64(j)) |
| + } |
| + } |
| + for i := 0; i < 8000; i++ { |
| + if _, err := insertAppRow(tx, newAppRow{AccountID: int64(1000 + i%2000), App: fmt.Sprintf("app%04d", i), |
| + CreatedBy: fmt.Sprintf("p%05d@example.com", (i*3)%20000), CreatedAt: n - int64(i)*600}); err != nil { |
| + t.Fatal(err) |
| + } |
| + } |
| + audit := prep(`INSERT INTO audit (account_id, app, address, action, detail, created_at) VALUES (?, ?, ?, ?, ?, ?)`) |
| + kinds := []string{"promote", "rollback", "signin", "rename", "domain-add", "invite-sent"} |
| + for i := 0; i < 200000; i++ { |
| + action := kinds[i%len(kinds)] |
| + if i%4000 == 0 { |
| + action = "account-deleted" |
| + } |
| + exec(audit, int64(1000+i%2000), fmt.Sprintf("app%04d", i%8000), fmt.Sprintf("p%05d@example.com", i%20000), |
| + action, "detail", n-int64(200000-i)*10) |
| + } |
| + opMust(t, tx.Commit()) |
| + return 1000 + 7 |
| +} |
| + |
| +// opCountsScaleBudget is OperatorCounts' own budget at scale. Its active |
| +// counts deduplicate every address signed in during the window: 60,000 |
| +// sessions for the 30-day count, which this SQLite does as a MERGE of two |
| +// sorted halves in about 40 ms on its own (reading the same 60,000 index |
| +// entries without the dedup takes 2 ms). The other reads keep 20 ms. |
| +const opCountsScaleBudget = 100 * time.Millisecond |
| + |
| +// TestOperatorCountsAtScale times every operator read on a production-sized |
| +// store. Each is printed; under CI each must answer within 20 ms, except |
| +// OperatorCounts (opCountsScaleBudget). |
| +func TestOperatorCountsAtScale(t *testing.T) { |
| + s := openOpStore(t) |
| + acct := opSeedScale(t, s, opNow) |
| + var rare int |
| + opMust(t, s.db.QueryRow(`SELECT COUNT(*) FROM audit WHERE action = 'account-deleted'`).Scan(&rare)) |
| + if rare != 50 { |
| + t.Fatalf("rare kind has %d rows, want 50", rare) |
| + } |
| + exclude := []string{"promote", "rollback", "signin", "account-deleted", "invite-sent"} |
| + reads := []struct { |
| + name string |
| + run func() (int, error) |
| + }{ |
| + {"OperatorCounts", func() (int, error) { |
| + c, err := s.OperatorCounts(opNow) |
| + return c.People, err |
| + }}, |
| + {"NewPeoplePerDay", func() (int, error) { d, err := s.NewPeoplePerDay(opNow, 30); return len(d), err }}, |
| + {"NewestPeople", func() (int, error) { p, err := s.NewestPeople(10); return len(p), err }}, |
| + {"PeoplePage", func() (int, error) { p, _, err := s.PeoplePage("", 0, 50); return len(p), err }}, |
| + {"PeoplePage search", func() (int, error) { p, _, err := s.PeoplePage("p19", 0, 50); return len(p), err }}, |
| + {"AccountsPage", func() (int, error) { p, _, err := s.AccountsPage("", 0, 50); return len(p), err }}, |
| + {"feed all", func() (int, error) { f, err := s.ActivityFeed(ActivityFilter{}, 0, 50); return len(f), err }}, |
| + {"feed all, older", func() (int, error) { f, err := s.ActivityFeed(ActivityFilter{}, 100000, 50); return len(f), err }}, |
| + {"feed account", func() (int, error) { |
| + f, err := s.ActivityFeed(ActivityFilter{AccountID: acct}, 0, 50) |
| + return len(f), err |
| + }}, |
| + {"feed deploys", func() (int, error) { |
| + f, err := s.ActivityFeed(ActivityFilter{Actions: deployActions}, 0, 50) |
| + return len(f), err |
| + }}, |
| + {"feed deploys, account", func() (int, error) { |
| + f, err := s.ActivityFeed(ActivityFilter{AccountID: acct, Actions: deployActions}, 0, 50) |
| + return len(f), err |
| + }}, |
| + {"feed rare kind", func() (int, error) { |
| + f, err := s.ActivityFeed(ActivityFilter{Actions: []string{"account-deleted"}}, 0, 50) |
| + return len(f), err |
| + }}, |
| + {"feed rare kind, account", func() (int, error) { |
| + f, err := s.ActivityFeed(ActivityFilter{AccountID: 1000, Actions: []string{"account-deleted"}}, 0, 50) |
| + return len(f), err |
| + }}, |
| + {"feed other", func() (int, error) { |
| + f, err := s.ActivityFeed(ActivityFilter{Exclude: exclude}, 0, 50) |
| + return len(f), err |
| + }}, |
| + {"feed other, account", func() (int, error) { |
| + f, err := s.ActivityFeed(ActivityFilter{AccountID: acct, Exclude: exclude}, 0, 50) |
| + return len(f), err |
| + }}, |
| + } |
| + for _, r := range reads { |
| + // The first call warms the page cache, as a running console's is. |
| + if _, err := r.run(); err != nil { |
| + t.Fatalf("%s: %v", r.name, err) |
| + } |
| + start := time.Now() |
| + got, err := r.run() |
| + took := time.Since(start) |
| + if err != nil { |
| + t.Fatalf("%s: %v", r.name, err) |
| + } |
| + if got == 0 { |
| + t.Errorf("%s returned nothing", r.name) |
| + } |
| + t.Logf("%-24s %8.2f ms (%d)", r.name, float64(took.Microseconds())/1000, got) |
| + budget := 20 * time.Millisecond |
| + if r.name == "OperatorCounts" { |
| + budget = opCountsScaleBudget |
| + } |
| + if perfEnforce() && took > budget { |
| + t.Errorf("%s took %v, over %v", r.name, took, budget) |
| + } |
| + } |
| +} |