// 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() }