File
Blob: config/store.go
| 1 | package config |
| 2 | |
| 3 | import ( |
| 4 | "context" |
| 5 | "database/sql" |
| 6 | "database/sql/driver" |
| 7 | "errors" |
| 8 | "fmt" |
| 9 | "math" |
| 10 | "os" |
| 11 | "path/filepath" |
| 12 | "strings" |
| 13 | |
| 14 | "go.miragespace.co/specter/util" |
| 15 | ) |
| 16 | |
| 17 | // Store owns one complete local replica. SQLite is authoritative; consumers |
| 18 | // retain their own active configurations. |
| 19 | type Store struct { |
| 20 | db *sql.DB |
| 21 | // The commit boundary is replaceable to test ambiguous transaction results. |
| 22 | commit func(*sql.Tx) error |
| 23 | } |
| 24 | |
| 25 | // Open starts an empty replica or recovers an existing one. It never imports |
| 26 | // deployment flags, resets an invalid database, or initializes documents. |
| 27 | func Open(dir string) (*Store, error) { |
| 28 | if strings.TrimSpace(dir) == "" { |
| 29 | return nil, errors.New("configuration directory must not be empty") |
| 30 | } |
| 31 | dir, err := filepath.Abs(dir) |
| 32 | if err != nil { |
| 33 | return nil, err |
| 34 | } |
| 35 | if err := util.MkdirAllDurable(dir, 0700); err != nil { |
| 36 | return nil, fmt.Errorf("open configuration: %w", err) |
| 37 | } |
| 38 | db, err := openDatabase(dir) |
| 39 | if err != nil { |
| 40 | return nil, fmt.Errorf("open configuration: %w", err) |
| 41 | } |
| 42 | s := &Store{db: db, commit: (*sql.Tx).Commit} |
| 43 | if _, err := s.Snapshot(); err != nil { |
| 44 | return nil, errors.Join(err, db.Close()) |
| 45 | } |
| 46 | return s, nil |
| 47 | } |
| 48 | |
| 49 | // Init creates nonempty initial documents only when the store has no documents. |
| 50 | // The check and write share one transaction, including while a server is running. |
| 51 | func Init(dir string, records []Record) (err error) { |
| 52 | if len(records) == 0 { |
| 53 | return errors.New("initial configuration must contain at least one document") |
| 54 | } |
| 55 | if err := checkRecords(records); err != nil { |
| 56 | return err |
| 57 | } |
| 58 | s, err := Open(dir) |
| 59 | if err != nil { |
| 60 | return err |
| 61 | } |
| 62 | defer func() { err = errors.Join(err, s.Close()) }() |
| 63 | err = s.write(func(tx *sql.Tx) (bool, error) { |
| 64 | var exists bool |
| 65 | if err := tx.QueryRow("SELECT EXISTS(SELECT 1 FROM documents)").Scan(&exists); err != nil { |
| 66 | return false, err |
| 67 | } |
| 68 | if exists { |
| 69 | return false, os.ErrExist |
| 70 | } |
| 71 | return writeRecords(tx, records) |
| 72 | }) |
| 73 | return err |
| 74 | } |
| 75 | |
| 76 | // Get returns SQLite's current document, after recovering any uncertain commit. |
| 77 | // Reading does not confirm the durability of a failed save. |
| 78 | func (s *Store) Get(name string) (Record, bool, error) { |
| 79 | conn, err := s.db.Conn(context.Background()) |
| 80 | if err != nil { |
| 81 | return Record{}, false, err |
| 82 | } |
| 83 | defer conn.Close() |
| 84 | record, found, err := readRecord(conn, name) |
| 85 | if err != nil { |
| 86 | return Record{}, false, discard(conn, err) |
| 87 | } |
| 88 | return record, found, nil |
| 89 | } |
| 90 | |
| 91 | // Snapshot returns all documents, including unknown schemas, sorted by name. |
| 92 | func (s *Store) Snapshot() ([]Record, error) { |
| 93 | conn, err := s.db.Conn(context.Background()) |
| 94 | if err != nil { |
| 95 | return nil, err |
| 96 | } |
| 97 | defer conn.Close() |
| 98 | records, err := readRecords(conn) |
| 99 | if err != nil { |
| 100 | return nil, discard(conn, err) |
| 101 | } |
| 102 | return records, nil |
| 103 | } |
| 104 | |
| 105 | // Put replaces a complete document after checking this server's current token. |
| 106 | // Disconnected edits can both succeed and later converge by Version ordering. |
| 107 | func (s *Store) Put(name string, schema uint64, value []byte, expectedToken string) (Record, error) { |
| 108 | var record Record |
| 109 | err := s.write(func(tx *sql.Tx) (bool, error) { |
| 110 | current, found, err := readRecord(tx, name) |
| 111 | if err != nil { |
| 112 | return false, err |
| 113 | } |
| 114 | if current.Token() != expectedToken { |
| 115 | return false, ErrConflict |
| 116 | } |
| 117 | revision := uint64(1) |
| 118 | if found { |
| 119 | if schema < current.Version.Schema { |
| 120 | return false, ErrSchemaRegression |
| 121 | } |
| 122 | if current.Version.Revision == math.MaxUint64 { |
| 123 | return false, errors.New("configuration revision exhausted") |
| 124 | } |
| 125 | revision = current.Version.Revision + 1 |
| 126 | } |
| 127 | record, err = NewRecord(name, schema, revision, value) |
| 128 | if err != nil { |
| 129 | return false, err |
| 130 | } |
| 131 | return writeRecords(tx, []Record{record}) |
| 132 | }) |
| 133 | return record, err |
| 134 | } |
| 135 | |
| 136 | // Merge validates every incoming record and commits all winning versions in one |
| 137 | // transaction. An oversized union is rejected whole, including on retry. |
| 138 | func (s *Store) Merge(records []Record) error { |
| 139 | if err := checkRecords(records); err != nil { |
| 140 | return err |
| 141 | } |
| 142 | return s.write(func(tx *sql.Tx) (bool, error) { |
| 143 | return writeRecords(tx, records) |
| 144 | }) |
| 145 | } |
| 146 | |
| 147 | // Hold the connection through the commit result so an uncertain connection can |
| 148 | // be retired before another operation uses it. Transactions are never replayed. |
| 149 | func (s *Store) write(change func(*sql.Tx) (bool, error)) error { |
| 150 | conn, err := s.db.Conn(context.Background()) |
| 151 | if err != nil { |
| 152 | return err |
| 153 | } |
| 154 | defer conn.Close() |
| 155 | tx, err := conn.BeginTx(context.Background(), nil) |
| 156 | if err != nil { |
| 157 | return discard(conn, err) |
| 158 | } |
| 159 | defer tx.Rollback() |
| 160 | // Reject existing corruption before a winning update could replace it, then |
| 161 | // validate the complete result before making any change durable. |
| 162 | _, err = readRecords(tx) |
| 163 | var changed bool |
| 164 | if err == nil { |
| 165 | changed, err = change(tx) |
| 166 | } |
| 167 | if err == nil && changed { |
| 168 | _, err = readRecords(tx) |
| 169 | } |
| 170 | if err != nil || !changed { |
| 171 | if rollbackErr := tx.Rollback(); rollbackErr != nil { |
| 172 | return discard(conn, errors.Join(err, rollbackErr)) |
| 173 | } |
| 174 | return err |
| 175 | } |
| 176 | if err := s.commit(tx); err != nil { |
| 177 | // Finish the transaction before retiring its leased connection. |
| 178 | _ = tx.Rollback() |
| 179 | return discard(conn, err) |
| 180 | } |
| 181 | return nil |
| 182 | } |
| 183 | |
| 184 | func discard(conn *sql.Conn, cause error) error { |
| 185 | _ = conn.Raw(func(any) error { return driver.ErrBadConn }) |
| 186 | return fmt.Errorf("%w: %w", ErrDurabilityUncertain, cause) |
| 187 | } |
| 188 | |
| 189 | func (s *Store) Close() error { |
| 190 | return s.db.Close() |
| 191 | } |