package jobstore import ( "bytes" "context" "database/sql" "errors" "fmt" "os" "os/exec" "path/filepath" "runtime" "strings" "testing" "time" ) // openStore opens the store in dir and closes it when the test ends. Each // test makes dir with t.TempDir before this, so the store closes before // its directory is removed, which Windows requires. func openStore(t *testing.T, dir string) *Store { t.Helper() s, err := Open(context.Background(), dir) if err != nil { t.Fatal(err) } t.Cleanup(func() { if err := s.Close(); err != nil { t.Error(err) } }) return s } // reopen closes s and opens its directory again. func reopen(t *testing.T, s *Store) *Store { t.Helper() if err := s.Close(); err != nil { t.Fatal(err) } return openStore(t, filepath.Dir(s.path)) } // fill writes n rows of 3,000 bytes, about a page each, to s's content // table, after those it has. func fill(t *testing.T, s *Store, n int) { t.Helper() ctx := context.Background() err := s.update(ctx, false, func(tx *sql.Tx) error { for range n { if _, err := tx.ExecContext(ctx, `INSERT INTO content (seq, job) VALUES ((SELECT COALESCE(max(seq), 0) + 1 FROM content), ?)`, bytes.Repeat([]byte("x"), 3000)); err != nil { return err } } return nil }) if err != nil { t.Fatal(err) } } // rows returns the number of rows in s's content table. func rows(t *testing.T, s *Store) int { t.Helper() var n int if err := s.conn.QueryRowContext(context.Background(), "SELECT count(*) FROM content").Scan(&n); err != nil { t.Fatal(err) } return n } // The store is created in, and reopened from, a directory whose name // SQLite's URIs would otherwise misread; reopening keeps what was written // and does not create the schema again. func TestOpenFindsItsFileInAnyDirectory(t *testing.T) { names := []string{"plain", "with space #1 100%"} if runtime.GOOS != "windows" { names = append(names, "what?") } for _, name := range names { t.Run(name, func(t *testing.T) { dir := filepath.Join(t.TempDir(), name) if err := os.Mkdir(dir, 0o700); err != nil { t.Fatal(err) } s := openStore(t, dir) fill(t, s, 1) s = reopen(t, s) if _, err := os.Stat(filepath.Join(dir, FileName)); err != nil { t.Errorf("the database is not in its directory: %v", err) } if n := rows(t, s); n != 1 { t.Errorf("%d rows after reopening, want 1", n) } }) } } // Every open, not only the one that creates the file, keeps the log's index // in memory, with no -shm file, and holds the file in exclusive locking // mode. func TestEveryOpenKeepsTheLogIndexInMemory(t *testing.T) { ctx := context.Background() dir := t.TempDir() s := openStore(t, dir) for open := 1; open <= 3; open++ { fill(t, s, 1) if _, err := os.Stat(filepath.Join(dir, FileName+"-shm")); !errors.Is(err, os.ErrNotExist) { t.Errorf("open %d: a -shm file exists (%v)", open, err) } var locking, journal string if err := s.conn.QueryRowContext(ctx, "PRAGMA locking_mode").Scan(&locking); err != nil { t.Fatal(err) } if err := s.conn.QueryRowContext(ctx, "PRAGMA journal_mode").Scan(&journal); err != nil { t.Fatal(err) } if locking != "exclusive" || journal != "wal" { t.Errorf("open %d: locking mode %q and journal mode %q, want exclusive and wal", open, locking, journal) } s = reopen(t, s) } } // secondOpenEnv names, in a child process, the directory it opens while // its parent holds the store. const secondOpenEnv = "JOBSTORE_TEST_SECOND_OPEN" // A second Open of a directory fails at once while a store holds it. The // second runs in a child process, the test binary run again, so that the // lock is the file system's, not one SQLite keeps within a process. func TestSecondOpenFailsAtOnce(t *testing.T) { if dir := os.Getenv(secondOpenEnv); dir != "" { started := time.Now() s, err := Open(context.Background(), dir) took := time.Since(started) switch { case err == nil: _ = s.Close() fmt.Println("second open: succeeded") case took > 5*time.Second: fmt.Printf("second open: failed only after %v: %v\n", took, err) default: fmt.Println("second open: failed:", err) } os.Exit(0) } dir := t.TempDir() s := openStore(t, dir) fill(t, s, 1) cmd := exec.Command(os.Args[0], "-test.run=^TestSecondOpenFailsAtOnce$", "-test.count=1") cmd.Env = append(os.Environ(), secondOpenEnv+"="+dir) out, err := cmd.CombinedOutput() if err != nil { t.Fatalf("child process: %v\n%s", err, out) } if !bytes.Contains(out, []byte("second open: failed:")) || !bytes.Contains(out, []byte(s.path)) { t.Fatalf("child process said %q, want a failed open naming %s, within 5 s", out, s.path) } t.Logf("child process: %s", bytes.TrimSpace(out)) // The refused open left the store working, and closing it frees the // directory. fill(t, s, 1) if n := rows(t, reopen(t, s)); n != 2 { t.Errorf("%d rows after reopening, want 2", n) } } // A damaged page anywhere in the file, a damaged header, and a schema newer // than the binary's each fail Open with an error naming the file. func TestOpenRefusesADamagedFile(t *testing.T) { tests := []struct { name string // open runs while the store is open, closed once it has closed. open func(t *testing.T, s *Store) closed func(t *testing.T, path string) want string }{ {name: "a page in the middle", closed: damageMiddlePage, want: "malformed"}, {name: "the header", closed: func(t *testing.T, path string) { overwrite(t, path, 0, 100) }, want: "not a database"}, {name: "a newer schema", open: setNextVersion, want: "schema version 2, newer than this binary's 1"}, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { dir := t.TempDir() s := openStore(t, dir) fill(t, s, 40) if tt.open != nil { tt.open(t, s) } if err := s.Close(); err != nil { t.Fatal(err) } if _, err := os.Stat(s.path + "-wal"); !errors.Is(err, os.ErrNotExist) { t.Fatalf("the log outlived Close (%v), and a page in it would hide the damage", err) } if tt.closed != nil { tt.closed(t, s.path) } again, err := Open(context.Background(), dir) if err == nil { _ = again.Close() t.Fatal("Open succeeded") } if !strings.Contains(err.Error(), s.path) || !strings.Contains(err.Error(), tt.want) { t.Errorf("Open: %v, want it to name %s and say %q", err, s.path, tt.want) } }) } } // damageMiddlePage overwrites the page in the middle of the file at path. func damageMiddlePage(t *testing.T, path string) { t.Helper() info, err := os.Stat(path) if err != nil { t.Fatal(err) } const pageSize = 4096 if pages := info.Size() / pageSize; pages < 20 { t.Fatalf("the file has %d pages, too few to damage one in the middle", pages) } overwrite(t, path, info.Size()/pageSize/2*pageSize, pageSize) } // overwrite fills n bytes of the file at path from off with a pattern no // page or header holds. func overwrite(t *testing.T, path string, off, n int64) { t.Helper() f, err := os.OpenFile(path, os.O_WRONLY, 0) if err != nil { t.Fatal(err) } defer f.Close() if _, err := f.WriteAt(bytes.Repeat([]byte{0xA5}, int(n)), off); err != nil { t.Fatal(err) } } // setNextVersion stamps the open store with the schema version after this // binary's. func setNextVersion(t *testing.T, s *Store) { t.Helper() next := fmt.Sprintf("PRAGMA user_version = %d", len(schemaSteps)+1) if _, err := s.conn.ExecContext(context.Background(), next); err != nil { t.Fatal(err) } }