| 1 | package main |
| 2 | |
| 3 | import ( |
| 4 | "context" |
| 5 | "database/sql" |
| 6 | "encoding/json" |
| 7 | "errors" |
| 8 | "io" |
| 9 | "net/url" |
| 10 | "os" |
| 11 | "path/filepath" |
| 12 | "regexp" |
| 13 | "strconv" |
| 14 | "strings" |
| 15 | "time" |
| 16 | |
| 17 | "amadan.net/oficina/equipo/internal/equipo" |
| 18 | _ "modernc.org/sqlite" |
| 19 | ) |
| 20 | |
| 21 | const dbCheckLimit = 60 * time.Second |
| 22 | const dbCheckMessages = 100 |
| 23 | |
| 24 | type dbCheckIssue struct { |
| 25 | BTree *uint32 `json:"b_tree,omitempty"` |
| 26 | Page *uint32 `json:"page,omitempty"` |
| 27 | } |
| 28 | type dbCheckSummary struct { |
| 29 | Status string `json:"status"` |
| 30 | Message string `json:"message,omitempty"` |
| 31 | QuickCheck string `json:"quick_check"` |
| 32 | IntegrityCheck string `json:"integrity_check"` |
| 33 | ErrorCount int `json:"error_count"` |
| 34 | LimitReached bool `json:"error_limit_reached"` |
| 35 | Issues []dbCheckIssue `json:"issues"` |
| 36 | PageCount *int64 `json:"page_count"` |
| 37 | PageSize *int64 `json:"page_size"` |
| 38 | JournalMode *string `json:"journal_mode"` |
| 39 | WALBytes *int64 `json:"wal_bytes"` |
| 40 | ElapsedMS int64 `json:"elapsed_ms"` |
| 41 | } |
| 42 | |
| 43 | // Only SQLite's structural coordinates can leave this process. In particular, |
| 44 | // never print raw errors, table/index names, CHECK expressions or row contents. |
| 45 | var dbCoordinates = regexp.MustCompile(`(?m)^(?:Tree ([0-9]{1,10}) page ([0-9]{1,10})|Page ([0-9]{1,10}))\b`) |
| 46 | |
| 47 | func (s *dbCheckSummary) finding(raw string) { |
| 48 | s.ErrorCount++ |
| 49 | if len(s.Issues) >= 5 { |
| 50 | return |
| 51 | } |
| 52 | issue := dbCheckIssue{} |
| 53 | if m := dbCoordinates.FindStringSubmatch(raw); m != nil { |
| 54 | number := func(v string) *uint32 { |
| 55 | n, e := strconv.ParseUint(v, 10, 32) |
| 56 | if e != nil { |
| 57 | return nil |
| 58 | } |
| 59 | p := uint32(n) |
| 60 | return &p |
| 61 | } |
| 62 | issue.BTree = number(m[1]) |
| 63 | issue.Page = number(m[2]) |
| 64 | if issue.Page == nil { |
| 65 | issue.Page = number(m[3]) |
| 66 | } |
| 67 | } |
| 68 | s.Issues = append(s.Issues, issue) |
| 69 | } |
| 70 | |
| 71 | func openCheckDB(path string) (*sql.DB, error) { |
| 72 | // Encode as a filename, never interpret environment content as SQLite options. |
| 73 | u := url.URL{Scheme: "file", Path: path, RawQuery: "mode=ro"} |
| 74 | d, err := sql.Open("sqlite", u.String()) |
| 75 | if err != nil { |
| 76 | return nil, err |
| 77 | } |
| 78 | d.SetMaxOpenConns(1) |
| 79 | return d, nil |
| 80 | } |
| 81 | |
| 82 | func runDBCheckCommand(args []string, out io.Writer) (bool, int) { |
| 83 | if len(args) == 0 || args[0] != "check-db" { |
| 84 | return false, 0 |
| 85 | } |
| 86 | if len(args) != 1 { |
| 87 | s := dbCheckSummary{Status: "failed", Message: equipo.CopyDBArguments, ErrorCount: 1, QuickCheck: "not_run", IntegrityCheck: "not_run", Issues: []dbCheckIssue{}} |
| 88 | _ = json.NewEncoder(out).Encode(s) |
| 89 | return true, 1 |
| 90 | } |
| 91 | return true, checkDB(context.Background(), out, os.Getenv("CARLOS_DB")) |
| 92 | } |
| 93 | |
| 94 | // checkDB reads the live file structure without booting the app. Constraint |
| 95 | // violations may not be reported; this checks file structure. SQLite diagnostic |
| 96 | // text is never emitted: only bounded b-tree/page coordinates are retained. |
| 97 | func checkDB(parent context.Context, out io.Writer, path string) int { |
| 98 | return checkDBWithin(parent, out, path, dbCheckLimit) |
| 99 | } |
| 100 | |
| 101 | func checkDBWithin(parent context.Context, out io.Writer, path string, limit time.Duration) (code int) { |
| 102 | started := time.Now() |
| 103 | ctx, cancel := context.WithTimeout(parent, limit) |
| 104 | defer cancel() |
| 105 | s := dbCheckSummary{Status: "failed", QuickCheck: "not_run", IntegrityCheck: "not_run", Issues: []dbCheckIssue{}} |
| 106 | defer func() { |
| 107 | if ctx.Err() != nil { |
| 108 | s.Message = equipo.CopyDBTimeout |
| 109 | if s.ErrorCount == 0 { |
| 110 | s.ErrorCount = 1 |
| 111 | } |
| 112 | } |
| 113 | if s.ErrorCount == 0 { |
| 114 | s.Status = "ok" |
| 115 | } else { |
| 116 | code = 1 |
| 117 | } |
| 118 | s.ElapsedMS = time.Since(started).Milliseconds() |
| 119 | if json.NewEncoder(out).Encode(s) != nil { |
| 120 | code = 1 |
| 121 | } |
| 122 | }() |
| 123 | fail := func(message string) { s.Message = message; s.ErrorCount++ } |
| 124 | if ctx.Err() != nil { |
| 125 | fail(equipo.CopyDBTimeout) |
| 126 | return 1 |
| 127 | } |
| 128 | if path == "" { |
| 129 | fail(equipo.CopyDBPathMissing) |
| 130 | return 1 |
| 131 | } |
| 132 | if !filepath.IsAbs(path) { |
| 133 | fail(equipo.CopyDBPathInvalid) |
| 134 | return 1 |
| 135 | } |
| 136 | info, err := os.Stat(path) |
| 137 | if errors.Is(err, os.ErrNotExist) { |
| 138 | fail(equipo.CopyDBPathMissing) |
| 139 | return 1 |
| 140 | } |
| 141 | if err != nil || !info.Mode().IsRegular() { |
| 142 | fail(equipo.CopyDBPathInvalid) |
| 143 | return 1 |
| 144 | } |
| 145 | d, err := openCheckDB(path) |
| 146 | if err != nil { |
| 147 | fail(equipo.CopyDBOpenFailed) |
| 148 | return 1 |
| 149 | } |
| 150 | defer d.Close() |
| 151 | if err = d.PingContext(ctx); err != nil { |
| 152 | fail(equipo.CopyDBOpenFailed) |
| 153 | return 1 |
| 154 | } |
| 155 | tx, err := d.BeginTx(ctx, &sql.TxOptions{ReadOnly: true}) |
| 156 | if err != nil { |
| 157 | fail(equipo.CopyDBOpenFailed) |
| 158 | return 1 |
| 159 | } |
| 160 | defer tx.Rollback() |
| 161 | // No setters, migrations, application hooks or checkpoint. Both checks and |
| 162 | // metadata share one read snapshot while the serving connection keeps writing. |
| 163 | s.QuickCheck = s.check(ctx, tx, "PRAGMA quick_check(100)") |
| 164 | s.IntegrityCheck = s.check(ctx, tx, "PRAGMA integrity_check(100)") |
| 165 | if s.ErrorCount > 0 { |
| 166 | s.Message = equipo.CopyDBCheckFailed |
| 167 | } |
| 168 | integer := func(query string) *int64 { |
| 169 | var n int64 |
| 170 | if err := tx.QueryRowContext(ctx, query).Scan(&n); err != nil || n < 0 { |
| 171 | fail(equipo.CopyDBMetadataFailed) |
| 172 | return nil |
| 173 | } |
| 174 | return &n |
| 175 | } |
| 176 | s.PageCount = integer("PRAGMA page_count") |
| 177 | s.PageSize = integer("PRAGMA page_size") |
| 178 | var journal string |
| 179 | if err = tx.QueryRowContext(ctx, "PRAGMA journal_mode").Scan(&journal); err != nil { |
| 180 | fail(equipo.CopyDBMetadataFailed) |
| 181 | } else { |
| 182 | switch journal { |
| 183 | case "wal", "delete", "truncate", "persist", "memory", "off": |
| 184 | s.JournalMode = &journal |
| 185 | default: |
| 186 | fail(equipo.CopyDBMetadataFailed) |
| 187 | } |
| 188 | } |
| 189 | // A WAL is optional, and an invisible WAL is unknown, not zero. Resolve a |
| 190 | // symlink only for this observation; SQLite resolves the database itself. |
| 191 | if resolved, e := filepath.EvalSymlinks(path); e == nil { |
| 192 | if wal, e := os.Stat(resolved + "-wal"); e == nil && wal.Mode().IsRegular() { |
| 193 | n := wal.Size() |
| 194 | s.WALBytes = &n |
| 195 | } |
| 196 | } |
| 197 | return 0 |
| 198 | } |
| 199 | |
| 200 | func (s *dbCheckSummary) check(ctx context.Context, tx *sql.Tx, query string) string { |
| 201 | rows, err := tx.QueryContext(ctx, query) |
| 202 | if err != nil { |
| 203 | s.finding("") |
| 204 | return "error" |
| 205 | } |
| 206 | defer rows.Close() |
| 207 | result := "ok" |
| 208 | count := 0 |
| 209 | for rows.Next() { |
| 210 | var raw string |
| 211 | if err = rows.Scan(&raw); err != nil { |
| 212 | s.finding("") |
| 213 | return "error" |
| 214 | } |
| 215 | if strings.TrimSpace(raw) != "ok" { |
| 216 | s.finding(raw) |
| 217 | count++ |
| 218 | result = "findings" |
| 219 | } |
| 220 | if count >= dbCheckMessages { |
| 221 | s.LimitReached = true |
| 222 | break |
| 223 | } |
| 224 | } |
| 225 | if rows.Err() != nil { |
| 226 | s.finding("") |
| 227 | if result == "findings" { |
| 228 | return "findings_and_error" |
| 229 | } |
| 230 | return "error" |
| 231 | } |
| 232 | return result |
| 233 | } |
| 234 | |