diff --git a/CLAUDE.md b/CLAUDE.md index 87a3b17..c04e602 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -148,6 +148,9 @@ main. A change is done when the gate passes and the docs under `docs/` (or doc comment. Write it for API readers; notes for Go readers go after a blank `//` line. - Dependencies are at their latest stable release when added or bumped. + The one exception is `modernc.org/libc`, which stays at the exact version + `modernc.org/sqlite` requires and moves only with it (owner, 2026-12-01; + design.md, Stack choices). - Commit on main, land a branch, push, tag or release only when the owner asks. Releases are `vX.Y.Z` tags on `main`; `release.yml` refuses a tag whose commit is not on `main`. diff --git a/docs/design.md b/docs/design.md index 6cd803f..15d3ad2 100644 --- a/docs/design.md +++ b/docs/design.md @@ -297,6 +297,11 @@ client ─HTTPS─▶ Caddy ─▶ server ── validate ──▶ printqueue ( and in the file a name with a dot or a nested table is an unknown key. - `go.mod`'s go line is the latest Go release, with no separate toolchain line. +- **Stack choices (owner, 2026-12-01):** + - `modernc.org/libc` is the one module held below its latest release. It + stays at the exact version `modernc.org/sqlite` requires, since the + driver is C transpiled to Go against that libc and works with it alone, + and moves only with the driver. - **Packaging.** The daemon serves no TLS itself and binds 127.0.0.1 by default; a reverse proxy in front terminates HTTPS and sets `X-Real-IP`. - The release tarballs are built for linux amd64, armv6, armv7 and arm64. diff --git a/docs/development.md b/docs/development.md index b22ddd5..cb73ddc 100644 --- a/docs/development.md +++ b/docs/development.md @@ -99,6 +99,7 @@ internal/pkg/raster/ Image decoding, scaling and dithering internal/pkg/safehttp/ SSRF-guarded image fetching internal/pkg/printer/ TCP printer client (port 9100) and status queries internal/pkg/printqueue/ Job queue, worker and status history +internal/pkg/jobstore/ The job store on disk: one SQLite database, through modernc.org/sqlite configs/ Example configuration examples/ Example jobs, such as the block calibration receipt packaging/ systemd unit diff --git a/go.mod b/go.mod index 80fcb7f..3eb2a41 100644 --- a/go.mod +++ b/go.mod @@ -16,12 +16,14 @@ require ( golang.org/x/image v0.48.0 golang.org/x/sync v0.25.0 golang.org/x/text v0.44.0 + modernc.org/sqlite v1.64.0 ) require ( github.com/BurntSushi/toml v1.6.0 // indirect github.com/bahlo/generic-list-go v0.2.0 // indirect github.com/buger/jsonparser v1.6.1 // indirect + github.com/dustin/go-humanize v1.1.0 // indirect github.com/fsnotify/fsnotify v1.9.0 // indirect github.com/gofiber/schema v1.10.2 // indirect github.com/gofiber/utils/v2 v2.6.5 // indirect @@ -32,9 +34,11 @@ require ( github.com/mattn/go-colorable v0.1.16 // indirect github.com/mattn/go-isatty v0.0.24 // indirect github.com/molecule-man/go-brrr v1.3.1 // indirect + github.com/ncruces/go-strftime v1.1.0 // indirect github.com/pb33f/go-yaml v0.2.0 // indirect github.com/pb33f/ordered-map/v2 v2.3.2 // indirect github.com/philhofer/fwd v1.2.1 // indirect + github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec // indirect github.com/sagikazarmark/locafero v0.11.0 // indirect github.com/sourcegraph/conc v0.3.1-0.20240121214520-5f936abd7ae8 // indirect github.com/spf13/afero v1.15.0 // indirect @@ -54,6 +58,9 @@ require ( golang.org/x/tools v0.53.0 // indirect golang.org/x/vuln v1.10.0 // indirect honnef.co/go/tools v0.8.2 // indirect + modernc.org/libc v1.80.1 // indirect + modernc.org/mathutil v1.7.1 // indirect + modernc.org/memory v1.12.1 // indirect ) tool ( diff --git a/go.sum b/go.sum index b7c9b84..b08e5c3 100644 --- a/go.sum +++ b/go.sum @@ -5,6 +5,8 @@ github.com/bahlo/generic-list-go v0.2.0/go.mod h1:2KvAjgMlE5NNynlg/5iLrrCCZ2+5xW github.com/buger/jsonparser v1.6.1 h1:I0phFv0PlbLHnM7TZAVjZ2MJ2/eWRTDyuO7GLR98IEs= github.com/buger/jsonparser v1.6.1/go.mod h1:6RYKKt7H4d4+iWqouImQ9R2FZql3VbhNgx27UK13J/0= github.com/cpuguy83/go-md2man/v2 v2.0.6/go.mod h1:oOW0eioCTA6cOiMLiUPZOpcVxMig6NIQQ7OS05n1F4g= +github.com/dustin/go-humanize v1.1.0 h1:dbKTrvD0klcbBV/h4AWJdMuZogJACoMlvWIWZ5b2xWg= +github.com/dustin/go-humanize v1.1.0/go.mod h1:hc1CvRkJMsgxqjmjMQF3QNRAZBwY8AXBAzKYoSX9sFI= github.com/frankban/quicktest v1.14.6 h1:7Xjx+VpznH+oBnejlPUj8oUpdxnVs4f8XU8WnHkI4W8= github.com/frankban/quicktest v1.14.6/go.mod h1:4ptaffx2x8+WTWXmUCuVU6aPUX1/Mz7zb5vbUoiM6w0= github.com/fsnotify/fsnotify v1.9.0 h1:2Ml+OJNzbYCTzsxtv8vKSFD9PbJjmhYF14k/jKC7S9k= @@ -31,10 +33,14 @@ github.com/google/go-cmdtest v0.4.1-0.20220921163831-55ab3332a786 h1:rcv+Ippz6RA github.com/google/go-cmdtest v0.4.1-0.20220921163831-55ab3332a786/go.mod h1:apVn/GCasLZUVpAJ6oWAuyP7Ne7CEsQbTnc0plM3m+o= github.com/google/go-cmp v0.7.0 h1:wk8382ETsv4JYUZwIsn6YpYiWiBsYLSJiTsyBybVuN8= github.com/google/go-cmp v0.7.0/go.mod h1:pXiqmnSA92OHEEa9HXL2W4E7lf9JzCmGVUdgjX3N/iU= +github.com/google/pprof v0.0.0-20261016150608-1facf8f91b50 h1:PlNWJRxu5APSV0pWqfIsZ0qt9OOGHSWfZQ4zvx+WgWs= +github.com/google/pprof v0.0.0-20261016150608-1facf8f91b50/go.mod h1:yUo1AMMpsPIDFGuwDK8nLcf8+vvAd5l2O6JDZ6hpwrM= github.com/google/renameio v0.1.0 h1:GOZbcHa3HfsPKPlmyPyN2KEohoMXOhdMbHrvbpl2QaA= github.com/google/renameio v0.1.0/go.mod h1:KWCgfxg9yswjAJkECMjeO8J8rahYeXnNhOm40UhjYkI= github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0= github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo= +github.com/hashicorp/golang-lru/v2 v2.0.7 h1:a+bsQ5rvGLjzHuww6tVxozPZFVghXaHOwFs4luLUK2k= +github.com/hashicorp/golang-lru/v2 v2.0.7/go.mod h1:QeFd9opnmA6QUJc5vARoKUSoFhyfM2/ZepoAG6RGpeM= github.com/inconshreveable/mousetrap v1.1.0 h1:wN+x4NVGpMsO7ErUn/mUI3vEoE6Jt13X2s0bqwp9tc8= github.com/inconshreveable/mousetrap v1.1.0/go.mod h1:vpF70FUmC8bwa3OWnCshd2FqLfsEA9PFc4w1p2J65bw= github.com/invopop/jsonschema v0.14.0 h1:MHQqLhvpNUZfw+hM3AZDYK7jxO8FZoQeQM77g8iyZjg= @@ -53,6 +59,8 @@ github.com/mattn/go-isatty v0.0.24 h1:tGZZoVgT/KiqK1c8ocVLeDS8BSWMRd47J3Lbz7vsRe github.com/mattn/go-isatty v0.0.24/go.mod h1:nMCL3Zebbrt45jsMDgnfIwz6ydEQApk5oEI3HqDio6A= github.com/molecule-man/go-brrr v1.3.1 h1:EwaJUzRIlp/dFmIpzq4J17CA5Zi5OHo2vOGmu09hF1w= github.com/molecule-man/go-brrr v1.3.1/go.mod h1:7ybW6/7gA3oKY45jOfVNjSJDtrr6ea4tzbsTkjmQDC4= +github.com/ncruces/go-strftime v1.1.0 h1:vtPmPWMkb539RGV9WpWT9EwJGvrOCKvMNI4obWL47Hk= +github.com/ncruces/go-strftime v1.1.0/go.mod h1:yVaq7iwCN09vHRrKBrrflXT0M9tTMG2KmZ9Fj7xeG/g= github.com/pb33f/go-yaml v0.2.0 h1:t9fYMVk2BGlBIu6L07gryB+gOWt8rjEJO7e/jdBSqCo= github.com/pb33f/go-yaml v0.2.0/go.mod h1:QvWdkHP5VjFYAeHMQUkaPQqREaQnBNOXmWzAjNrnSdo= github.com/pb33f/ordered-map/v2 v2.3.2 h1:wDyaZ2Pv9QLh64X4utCeD5Zoi9nIv2aW3lwv172O5PQ= @@ -65,6 +73,8 @@ github.com/pingcap/errors v0.11.4 h1:lFuQV/oaUMGcD2tqt+01ROSmJs75VG1ToEOkZIZ4nE4 github.com/pingcap/errors v0.11.4/go.mod h1:Oi8TUi2kEtXXLMJk9l1cGmz20kV3TaQ0usTwv5KuLY8= github.com/pkg/errors v0.9.1 h1:FEBLx1zS214owpjy7qsBeixbURkuhQAwrK5UwLGTwt4= github.com/pkg/errors v0.9.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0= +github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec h1:W09IVJc94icq4NjY3clb7Lk8O1qJ8BdBEF8z0ibU0rE= +github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec/go.mod h1:qqbHyh8v60DhA7CoWK5oRCqLrMHRGoxYCSS9EjAz6Eo= github.com/rogpeppe/go-internal v1.14.1 h1:UQB4HGPB6osV0SQTLymcB4TgvyWu6ZyliaW0tI/otEQ= github.com/rogpeppe/go-internal v1.14.1/go.mod h1:MaRKkUm5W0goXpeCfT7UZI6fk/L7L7so1lCWt35ZSgc= github.com/russross/blackfriday/v2 v2.1.0/go.mod h1:+Rmxgy9KzJVeS9/2gXHxylqXiyQDYRxCVz55jmeOWTM= @@ -135,3 +145,31 @@ gopkg.in/yaml.v2 v2.4.0 h1:D8xgwECY7CYvx+Y2n4sBz93Jn9JRvxdiyyo8CTfuKaY= gopkg.in/yaml.v2 v2.4.0/go.mod h1:RDklbk79AGWmwhnvt/jBztapEOGDOx6ZbXqjP6csGnQ= honnef.co/go/tools v0.8.2 h1:+jPbCzuYxYrcoOvCecYUFDj+XJQRmzIhJmlbpps21Zk= honnef.co/go/tools v0.8.2/go.mod h1:xG1Q4n+mg3bKZrO6RWFA9jFlkqplflmDRHGeuexiLDs= +modernc.org/cc/v4 v4.30.6-0.20261101114202-1b9d1a076f6b h1:WE5SLOURcNd8s6uPR/n4WV4weQxxYKi5OpEZkfNVvdE= +modernc.org/cc/v4 v4.30.6-0.20261101114202-1b9d1a076f6b/go.mod h1:OnovgIhbbMXMu1aISnJ0wvVD1KnW+cAUJkIrAWh+kVI= +modernc.org/ccgo/v4 v4.38.1 h1:wdxJVBuFT8JufZnnQyS6Bbz3NOWhViD0xJOGR96Bpd4= +modernc.org/ccgo/v4 v4.38.1/go.mod h1:kOpEkJRbFwBvjUWwn4j1j9B7iFHbl1+orhgTMCDkDBk= +modernc.org/fileutil v1.4.0 h1:j6ZzNTftVS054gi281TyLjHPp6CPHr2KCxEXjEbD6SM= +modernc.org/fileutil v1.4.0/go.mod h1:EqdKFDxiByqxLk8ozOxObDSfcVOv/54xDs/DUHdvCUU= +modernc.org/gc/v2 v2.6.5 h1:nyqdV8q46KvTpZlsw66kWqwXRHdjIlJOhG6kxiV/9xI= +modernc.org/gc/v2 v2.6.5/go.mod h1:YgIahr1ypgfe7chRuJi2gD7DBQiKSLMPgBQe9oIiito= +modernc.org/gc/v3 v3.2.0 h1:/Y3LGDMQaoYf55PebP1qsZ5FDGgAZyG1RYKEHeQzh1o= +modernc.org/gc/v3 v3.2.0/go.mod h1:HFK/6AGESC7Ex+EZJhJ2Gni6cTaYpSMmU/cT9RmlfYY= +modernc.org/goabi0 v0.2.0 h1:HvEowk7LxcPd0eq6mVOAEMai46V+i7Jrj13t4AzuNks= +modernc.org/goabi0 v0.2.0/go.mod h1:CEFRnnJhKvWT1c1JTI3Avm+tgOWbkOu5oPA8eH8LnMI= +modernc.org/libc v1.80.1 h1:ejn7HtTV3GknNKbklqWQ1nvUrfX8mTxs1D+xp/JQwy4= +modernc.org/libc v1.80.1/go.mod h1:pvo25Rs3OJEbDqhUV9jdEGevxeLJrJeDmNid/AcQV1g= +modernc.org/mathutil v1.7.1 h1:GCZVGXdaN8gTqB1Mf/usp1Y/hSqgI2vAGGP4jZMCxOU= +modernc.org/mathutil v1.7.1/go.mod h1:4p5IwJITfppl0G4sUEDtCr4DthTaT47/N3aT6MhfgJg= +modernc.org/memory v1.12.1 h1:nFMiWrpStgZczNl6XI9GnIk/rWhYIyHGUaR04pGbp9g= +modernc.org/memory v1.12.1/go.mod h1:/JP4VbVC+K5sU2wZi9bHoq2MAkCnrt2r98UGeSK7Mjw= +modernc.org/opt v0.2.0 h1:tGyef5ApycA7FSEOMraay9SaTk5zmbx7Tu+cJs4QKZg= +modernc.org/opt v0.2.0/go.mod h1:03fq9lsNfvkYSfxrfUhZCWPk1lm4cq4N+Bh//bEtgns= +modernc.org/sortutil v1.2.1 h1:+xyoGf15mM3NMlPDnFqrteY07klSFxLElE2PVuWIJ7w= +modernc.org/sortutil v1.2.1/go.mod h1:7ZI3a3REbai7gzCLcotuw9AC4VZVpYMjDzETGsSMqJE= +modernc.org/sqlite v1.64.0 h1:xCoLcRc2g33gLkmaRrcsJLitr4TRMQGGb3H4HYs3mbM= +modernc.org/sqlite v1.64.0/go.mod h1:Jzjh1mt4s0HuQ0KvtB1LIuHiGRmU2D5pgj8dUhW7/SE= +modernc.org/strutil v1.2.1 h1:UneZBkQA+DX2Rp35KcM69cSsNES9ly8mQWD71HKlOA0= +modernc.org/strutil v1.2.1/go.mod h1:EHkiggD70koQxjVdSBM3JKM7k6L0FbGE5eymy9i3B9A= +modernc.org/token v1.1.0 h1:Xl7Ap9dKaEs5kLoOQeQmPWevfnk/DM5qcLcYlA8ys6Y= +modernc.org/token v1.1.0/go.mod h1:UGzOrNV1mAFSEB63lOFHIpNRUVMvYTc6yu1SMY/XTDM= diff --git a/internal/pkg/jobstore/mode_test.go b/internal/pkg/jobstore/mode_test.go new file mode 100644 index 0000000..26b66d4 --- /dev/null +++ b/internal/pkg/jobstore/mode_test.go @@ -0,0 +1,25 @@ +//go:build unix + +package jobstore + +import ( + "os" + "path/filepath" + "testing" +) + +// The database and its log can be read by the daemon's user only. +func TestFilesAreTheOwnersAlone(t *testing.T) { + dir := t.TempDir() + s := openStore(t, dir) + fill(t, s, 1) + for _, name := range []string{FileName, FileName + "-wal"} { + info, err := os.Stat(filepath.Join(dir, name)) + if err != nil { + t.Fatal(err) + } + if mode := info.Mode().Perm(); mode != 0o600 { + t.Errorf("%s has mode %#o, want 0600", name, mode) + } + } +} diff --git a/internal/pkg/jobstore/open.go b/internal/pkg/jobstore/open.go new file mode 100644 index 0000000..f004c23 --- /dev/null +++ b/internal/pkg/jobstore/open.go @@ -0,0 +1,315 @@ +// Package jobstore keeps print jobs in a SQLite database on disk, so that +// they outlive the process. +// +// The database is one file, FileName, with SQLite's write-ahead log beside +// it. A Store holds one connection for its life, in exclusive locking +// mode, so no other process can open the file while it is open. Commits +// are lazy unless a caller asks for a sync: they survive a crash of the +// process at once, and a power cut once a later synced commit, or the +// kernel's writeback, has reached the disk. +package jobstore + +import ( + "context" + "database/sql" + "database/sql/driver" + "errors" + "fmt" + "io/fs" + "net/url" + "os" + "path/filepath" + "strconv" + "strings" + "sync" + + "modernc.org/sqlite" +) + +// FileName is the database's name in the state directory. SQLite keeps its +// write-ahead log beside it, in FileName+"-wal"; the two belong together. +const FileName = "jobs.db" + +// pragmas are run, in this order, on every connection as it opens, by +// connector. The driver's own _pragma list runs its pragmas sorted by +// name, which would put locking_mode after the first read. +// +// Exclusive locking comes first: set before the database is first read, it +// keeps the log's index in the process's memory, so SQLite makes no -shm +// file and maps nothing, and the connection keeps the file locked until it +// closes. auto_vacuum takes effect only before the first table exists. +// Commits are lazy (synchronous NORMAL) unless a caller asks for a sync, +// temporary tables stay in memory, the log is cut back to 4 MiB after a +// checkpoint, and deleted rows are overwritten where that costs no extra +// writes. +var pragmas = []string{ + "locking_mode(EXCLUSIVE)", + "auto_vacuum(NONE)", + "journal_mode(WAL)", + "synchronous(NORMAL)", + "temp_store(MEMORY)", + "journal_size_limit(4194304)", + "secure_delete(FAST)", +} + +// schemaSteps[i] takes the database from user_version i to i+1, so +// len(schemaSteps) is the version this binary writes. +// +// jobs holds what a job is, written once; deliveries one row per printer a +// job goes to, whose state changes; content the job as JSON, apart, so +// that a status update never rewrites it; and refs the source and +// reference of each unique job, for the duplicate check, in the order they +// were kept, which kept counts, pruned apart from the jobs. Times are Unix +// nanoseconds. Jobs, deliveries and contents are looked up by sequence +// number only, so they have no indexes to update; refs has one, on its +// source and reference. +var schemaSteps = []string{ + `CREATE TABLE jobs ( + seq INTEGER PRIMARY KEY, + id TEXT NOT NULL, + source TEXT NOT NULL, + ref TEXT NOT NULL, + sequence TEXT NOT NULL, + created_at INTEGER NOT NULL +); +CREATE TABLE deliveries ( + seq INTEGER PRIMARY KEY, + job_seq INTEGER NOT NULL, + printer TEXT NOT NULL, + state TEXT NOT NULL, + attempts INTEGER NOT NULL, + error TEXT NOT NULL, + started_at INTEGER, + sent_at INTEGER, + finished_at INTEGER +); +CREATE TABLE content ( + seq INTEGER PRIMARY KEY, + job BLOB NOT NULL +); +CREATE TABLE refs ( + kept INTEGER PRIMARY KEY, + source TEXT NOT NULL, + ref TEXT NOT NULL, + id TEXT NOT NULL, + UNIQUE (source, ref) +);`, +} + +// Store keeps print jobs in a SQLite database. It is safe for concurrent +// use. +type Store struct { + path string + db *sql.DB + + // mu serialises all work on conn. A transaction and the synchronous + // setting belong to the connection, so one call must never run inside + // another's transaction. + mu sync.Mutex + conn *sql.Conn + closed bool +} + +// Open opens the job store in dir, creating it if it is missing, and +// returns it locked to this process: a second Open of the same directory, +// from any process, fails at once. It checks the whole file and refuses a +// damaged one, or one written by a newer binary. Every error names the +// file. Close releases it. +func Open(ctx context.Context, dir string) (*Store, error) { + path, err := filepath.Abs(filepath.Join(dir, FileName)) + if err != nil { + return nil, fmt.Errorf("opening the job store in %s: %w", dir, err) + } + s, err := open(ctx, path) + if err != nil { + return nil, fmt.Errorf("opening the job store %s: %w", path, err) + } + return s, nil +} + +// open opens the database at path, as Open describes. +func open(ctx context.Context, path string) (*Store, error) { + s, err := connect(ctx, path) + if err != nil { + return nil, err + } + if err := s.prepare(ctx); err != nil { + return nil, errors.Join(err, s.Close()) + } + return s, nil +} + +// connect creates the database at path if it is missing and returns a +// Store on its connection, which has run the pragmas and nothing else. +func connect(ctx context.Context, path string) (*Store, error) { + // SQLite gives its log the database file's mode, so creating the file + // first, readable by its owner only, covers both. A file that exists + // is left unopened: closing any descriptor of it would drop the locks + // a connection in this process holds on it. + f, err := os.OpenFile(path, os.O_RDWR|os.O_CREATE|os.O_EXCL, 0o600) + switch { + case err == nil: + if err := f.Close(); err != nil { + return nil, err + } + case !errors.Is(err, fs.ErrExist): + return nil, err + } + // fdatasync leaves out the file's times, which a commit need not wait + // for. On a platform without it, SQLite syncs its usual way. + if _, err := sqlite.Fdatasync(true); err != nil && !errors.Is(err, sqlite.ErrFdatasyncUnavailable) { + return nil, err + } + base, err := sqlite.NewConnector(dsn(path)) + if err != nil { + return nil, err + } + db := sql.OpenDB(connector{base}) + db.SetMaxOpenConns(1) + db.SetMaxIdleConns(1) + db.SetConnMaxLifetime(0) + db.SetConnMaxIdleTime(0) + conn, err := db.Conn(ctx) + if err != nil { + return nil, errors.Join(err, db.Close()) + } + return &Store{path: path, db: db, conn: conn}, nil +} + +// dsn returns the URI that opens the database at path, an absolute path. +// The path is escaped, so a directory whose name holds a space, "#", "?" or +// "%" opens the file it names. +func dsn(path string) string { + p := filepath.ToSlash(path) + if !strings.HasPrefix(p, "/") { + // A Windows path, "C:/...", becomes "/C:/...", as file URIs write it. + p = "/" + p + } + return (&url.URL{Scheme: "file", Path: p}).String() +} + +// connector opens the driver's connections and runs the pragmas on each, +// in order, before anything else reads the database. The connection it +// returns is the driver's own, with all its optional interfaces. +type connector struct { + driver.Connector +} + +// Connect implements driver.Connector. +func (c connector) Connect(ctx context.Context) (driver.Conn, error) { + conn, err := c.Connector.Connect(ctx) + if err != nil { + return nil, err + } + execer, ok := conn.(driver.ExecerContext) + if !ok { + return nil, errors.Join(errors.New("the SQLite driver's connection cannot run statements"), conn.Close()) + } + for _, p := range pragmas { + if _, err := execer.ExecContext(ctx, "PRAGMA "+p, nil); err != nil { + return nil, errors.Join(fmt.Errorf("PRAGMA %s: %w", p, err), conn.Close()) + } + } + return conn, nil +} + +// prepare checks the opened database, brings its schema up to date and +// writes once. +func (s *Store) prepare(ctx context.Context) error { + // SQLite otherwise finds a damaged page only when a statement reads it, + // which could be mid-run. quick_check reads every page and writes + // nothing. + rows, err := s.conn.QueryContext(ctx, "PRAGMA quick_check") + if err != nil { + return fmt.Errorf("checking the file: %w", err) + } + var problems []string + for rows.Next() { + var line string + if err := rows.Scan(&line); err != nil { + return errors.Join(fmt.Errorf("checking the file: %w", err), rows.Close()) + } + problems = append(problems, line) + } + if err := errors.Join(rows.Err(), rows.Close()); err != nil { + return fmt.Errorf("checking the file: %w", err) + } + if len(problems) != 1 || problems[0] != "ok" { + return fmt.Errorf("the file is damaged: %s", strings.Join(problems, "; ")) + } + + var version int + if err := s.conn.QueryRowContext(ctx, "PRAGMA user_version").Scan(&version); err != nil { + return fmt.Errorf("reading the schema version: %w", err) + } + if version > len(schemaSteps) { + return fmt.Errorf("the file has schema version %d, newer than this binary's %d", version, len(schemaSteps)) + } + for ; version < len(schemaSteps); version++ { + step := func(tx *sql.Tx) error { + if _, err := tx.ExecContext(ctx, schemaSteps[version]); err != nil { + return err + } + return setVersion(ctx, tx, version+1) + } + if err := s.update(ctx, true, step); err != nil { + return fmt.Errorf("updating the schema to version %d: %w", version+1, err) + } + } + // A store that cannot be written then fails at start rather than at + // the first job, and the write leaves the file locked to this + // connection until it closes. + if err := s.update(ctx, false, func(tx *sql.Tx) error { return setVersion(ctx, tx, version) }); err != nil { + return fmt.Errorf("writing to the file: %w", err) + } + return nil +} + +// setVersion sets the database's user_version, which a PRAGMA cannot take +// as a parameter. +func setVersion(ctx context.Context, tx *sql.Tx, version int) error { + _, err := tx.ExecContext(ctx, "PRAGMA user_version = "+strconv.Itoa(version)) + return err +} + +// Close checkpoints the log into the database and releases the file and +// its lock. Calls after the first do nothing. +func (s *Store) Close() error { + s.mu.Lock() + defer s.mu.Unlock() + if s.closed { + return nil + } + s.closed = true + if err := errors.Join(s.conn.Close(), s.db.Close()); err != nil { + return fmt.Errorf("closing the job store %s: %w", s.path, err) + } + return nil +} + +// update runs fn in a transaction and commits it. With sync, it commits at +// synchronous FULL, so the commit is on disk when update returns, and then +// returns to NORMAL; the log is appended in order, so that sync makes every +// earlier commit durable too. The caller holds s.mu, or owns s alone. +func (s *Store) update(ctx context.Context, sync bool, fn func(*sql.Tx) error) (err error) { + if sync { + if _, err := s.conn.ExecContext(ctx, "PRAGMA synchronous = FULL"); err != nil { + return err + } + defer func() { + // Restored even when the commit failed, so the connection is + // never left syncing every commit. + if _, resetErr := s.conn.ExecContext(context.WithoutCancel(ctx), "PRAGMA synchronous = NORMAL"); resetErr != nil { + err = errors.Join(err, fmt.Errorf("returning to synchronous NORMAL: %w", resetErr)) + } + }() + } + tx, err := s.conn.BeginTx(ctx, nil) + if err != nil { + return err + } + if err := fn(tx); err != nil { + return errors.Join(err, tx.Rollback()) + } + return tx.Commit() +} diff --git a/internal/pkg/jobstore/open_test.go b/internal/pkg/jobstore/open_test.go new file mode 100644 index 0000000..56ca3b0 --- /dev/null +++ b/internal/pkg/jobstore/open_test.go @@ -0,0 +1,254 @@ +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) + } +}