返回 DeepSeek-Reasonix
projectiondb.go
根目录 / internal / projectiondb / projectiondb.go
1 // Package projectiondb owns the lifecycle of disposable SQLite projections.
2 // Business data must remain authoritative outside the database: callers are
3 // expected to be able to discard and rebuild every database opened here.
4 package projectiondb
5
6 import (
7 "context"
8 "database/sql"
9 "errors"
10 "fmt"
11 "net/url"
12 "os"
13 "path/filepath"
14 "runtime"
15 "strings"
16 "sync/atomic"
17 "time"
18
19 filelock "reasonix/internal/identitylock"
20 "reasonix/internal/sqliteuri"
21
22 moderncsqlite "modernc.org/sqlite"
23 sqlite3 "modernc.org/sqlite/lib"
24 )
25
26 type Mode string
27
28 var memoryDatabaseSequence atomic.Uint64
29
30 const (
31 ModeDisk Mode = "disk"
32 ModeMemory Mode = "memory"
33 )
34
35 type State string
36
37 const (
38 StateReady State = "ready"
39 StateDegraded State = "degraded"
40 )
41
42 type Status struct {
43 State State `json:"state"`
44 Mode Mode `json:"mode"`
45 Path string `json:"path,omitempty"`
46 Revision uint64 `json:"revision"`
47 Indexed int64 `json:"indexed"`
48 Total int64 `json:"total"`
49 Pending int64 `json:"pending"`
50 Failed int64 `json:"failed"`
51 LastError string `json:"lastError,omitempty"`
52 QuarantinedPath string `json:"quarantinedPath,omitempty"`
53 }
54
55 type Migration struct {
56 Version int
57 Apply func(context.Context, *sql.Tx) error
58 }
59
60 type OpenOptions struct {
61 Path string
62 MemoryName string
63 Migrations []Migration
64 InMemory bool
65 // RequireDisk disables the process-local memory fallback. Rebuild uses this
66 // so a failed temporary open reports the real disk error instead of
67 // "could not use disk storage" after silently opening :memory:.
68 RequireDisk bool
69 MaxOpenConns int
70 Now func() time.Time
71 SecureDelete bool
72 AutoVacuum bool
73 // RetainBackup keeps the previous database at its generated .replaced-
74 // timestamp path so disposable projections can offer a rollback point.
75 RetainBackup bool
76 // QuickCheck uses SQLite's quick_check for a disposable projection.
77 // Authoritative stores keep the full integrity_check default.
78 QuickCheck bool
79 // ReuseIntegrityCheck permits cached audits of unchanged disposable files.
80 // File identity, size, mtime, SQLite header and empty WAL are required.
81 // Default stays full validation; authoritative stores must not opt in.
82 ReuseIntegrityCheck bool
83 // ResumeKey opts Rebuild into a single persistent staging database. The
84 // callback atomically commits data and position. Cancellation retains staging;
85 // a changed key starts fresh. Progress is disposable, never business authority.
86 ResumeKey string
87 }
88
89 // WALSizeLimit is the size a disk projection's WAL is truncated back to after
90 // a checkpoint.
91 const WALSizeLimit = 4 << 20
92
93 // CheckpointBeforeClose folds the WAL into the database and truncates it. It is
94 // best-effort: another process's reader leaves the WAL for its next checkpoint.
95 func CheckpointBeforeClose(ctx context.Context, db *sql.DB) {
96 if db != nil {
97 _, _ = db.ExecContext(ctx, `PRAGMA wal_checkpoint(TRUNCATE)`)
98 }
99 }
100
101 type Handle struct {
102 DB *sql.DB
103 Status Status
104 }
105
106 type FutureSchemaError struct {
107 Found int
108 Supported int
109 }
110
111 func (e *FutureSchemaError) Error() string {
112 return fmt.Sprintf("projection schema %d is newer than supported %d", e.Found, e.Supported)
113 }
114
115 func Open(ctx context.Context, opts OpenOptions) (*Handle, error) {
116 return openProjection(ctx, opts, true)
117 }
118
119 // OpenAdvisory opens disposable metadata before a full integrity audit. The
120 // owner must call CheckIntegrity in its maintenance lifecycle and invalidate
121 // all readers on corruption. This must never certify content or execution.
122 func OpenAdvisory(ctx context.Context, opts OpenOptions) (*Handle, error) {
123 return openProjection(ctx, opts, false)
124 }
125
126 func openProjection(ctx context.Context, opts OpenOptions, checkIntegrity bool) (*Handle, error) {
127 if opts.Now == nil {
128 opts.Now = time.Now
129 }
130 if opts.MemoryName == "" {
131 opts.MemoryName = "projection"
132 }
133 // Blank paths must never become relative "v1.sqlite" files under cwd.
134 if strings.TrimSpace(opts.Path) == "" {
135 opts.Path = ""
136 opts.InMemory = true
137 }
138 mode := ModeDisk
139 status := Status{State: StateReady, Mode: mode, Path: opts.Path}
140 useMemory := opts.InMemory || PathLooksRemote(opts.Path)
141 if !useMemory {
142 if err := os.MkdirAll(filepath.Dir(opts.Path), 0o700); err != nil {
143 if opts.RequireDisk {
144 return nil, fmt.Errorf("create projection directory: %w", err)
145 }
146 useMemory = true
147 status.LastError = err.Error()
148 } else {
149 _ = os.Chmod(filepath.Dir(opts.Path), 0o700)
150 if filesystemRemote(filepath.Dir(opts.Path)) {
151 if opts.RequireDisk {
152 return nil, errors.New("projection cache is on a remote filesystem")
153 }
154 useMemory = true
155 status.LastError = "projection cache is on a remote filesystem; using memory"
156 }
157 }
158 }
159 if useMemory {
160 if opts.RequireDisk {
161 return nil, errors.New("projection requires disk storage")
162 }
163 mode = ModeMemory
164 }
165
166 db, err := open(ctx, opts, mode, checkIntegrity)
167 if err != nil && mode == ModeDisk {
168 var future *FutureSchemaError
169 switch {
170 case errors.As(err, &future):
171 // A newer process wrote this projection. Keep the file intact and
172 // serve an empty memory projection so startup never quarantines a
173 // healthy future schema.
174 if opts.RequireDisk {
175 return nil, err
176 }
177 status.State = StateDegraded
178 status.LastError = err.Error()
179 mode = ModeMemory
180 db, err = open(ctx, opts, mode, checkIntegrity)
181 case isCorruptionError(err):
182 // Only integrity-level failures may rename the on-disk projection.
183 status.QuarantinedPath = Quarantine(opts.Path, opts.Now())
184 db, err = open(ctx, opts, mode, checkIntegrity)
185 if err != nil {
186 if opts.RequireDisk {
187 return nil, err
188 }
189 status.State = StateDegraded
190 status.LastError = err.Error()
191 mode = ModeMemory
192 db, err = open(ctx, opts, mode, checkIntegrity)
193 }
194 default:
195 // Busy, permission, IO, or transient open errors must never rename
196 // a healthy database. Fall back to memory for this process only.
197 if opts.RequireDisk {
198 return nil, err
199 }
200 status.State = StateDegraded
201 status.LastError = err.Error()
202 mode = ModeMemory
203 db, err = open(ctx, opts, mode, checkIntegrity)
204 }
205 }
206 if err != nil {
207 return nil, err
208 }
209 status.Mode = mode
210 if mode == ModeMemory {
211 status.Path = ""
212 }
213 return &Handle{DB: db, Status: status}, nil
214 }
215
216 func open(ctx context.Context, opts OpenOptions, mode Mode, checkIntegrity bool) (*sql.DB, error) {
217 var dsn string
218 if mode == ModeMemory {
219 // time.Now has coarse resolution on some platforms, notably Windows.
220 // A process-local sequence prevents concurrently opened projections with
221 // the same logical name from sharing one SQLite memory database by accident.
222 dsn = fmt.Sprintf("file:reasonix-%s-%d-%d?mode=memory&cache=shared", url.PathEscape(opts.MemoryName),
223 opts.Now().UnixNano(), memoryDatabaseSequence.Add(1))
224 } else {
225 var err error
226 // journal_size_limit is per connection, so it rides the DSN to reach
227 // every pooled one; without it a checkpointed WAL keeps its peak size.
228 dsn, err = sqliteuri.Disk(opts.Path, url.Values{
229 "_pragma": {"busy_timeout(150)", "foreign_keys(1)", fmt.Sprintf("journal_size_limit(%d)", WALSizeLimit)},
230 })
231 if err != nil {
232 return nil, err
233 }
234 }
235 var auditFile integrityCertificate
236 var auditKnown bool
237 if opts.ReuseIntegrityCheck && mode == ModeDisk {
238 auditFile, auditKnown = integrityFileState(opts.Path)
239 }
240 db, err := sql.Open("sqlite", dsn)
241 if err != nil {
242 return nil, err
243 }
244 maxOpen := opts.MaxOpenConns
245 if maxOpen <= 0 {
246 maxOpen = 4
247 }
248 // Shared-cache memory databases cannot safely pool concurrent writers.
249 // Disk catalogs retain their requested pool and WAL read concurrency.
250 if mode == ModeMemory {
251 maxOpen = 1
252 }
253 db.SetMaxOpenConns(maxOpen)
254 db.SetMaxIdleConns(min(maxOpen, 2))
255 fail := func(err error) (*sql.DB, error) {
256 _ = db.Close()
257 return nil, err
258 }
259 if err := db.PingContext(ctx); err != nil {
260 return fail(err)
261 }
262 if mode == ModeDisk {
263 if _, err := db.ExecContext(ctx, `PRAGMA journal_mode=WAL`); err != nil {
264 return fail(err)
265 }
266 }
267 for _, pragma := range []string{`PRAGMA synchronous=NORMAL`, `PRAGMA foreign_keys=ON`, `PRAGMA busy_timeout=150`} {
268 if _, err := db.ExecContext(ctx, pragma); err != nil {
269 return fail(err)
270 }
271 }
272 if opts.SecureDelete {
273 // Best-effort: some builds/filesystems reject the pragma without making
274 // the projection unusable.
275 _, _ = db.ExecContext(ctx, `PRAGMA secure_delete=ON`)
276 }
277 if opts.AutoVacuum {
278 // auto_vacuum can only be changed on an empty database; ignore failures
279 // on already-initialized files so open does not degrade to memory.
280 _, _ = db.ExecContext(ctx, `PRAGMA auto_vacuum=INCREMENTAL`)
281 }
282 if checkIntegrity {
283 validate := func() error { return checkDatabaseIntegrity(ctx, db, opts.QuickCheck) }
284 var err error
285 if opts.ReuseIntegrityCheck && mode == ModeDisk {
286 err = reusableIntegrityChecks.checkOpened(opts.Path, opts.QuickCheck, auditFile, auditKnown, validate)
287 } else {
288 err = validate()
289 }
290 if err != nil {
291 return fail(err)
292 }
293 }
294 if err := ApplyMigrations(ctx, db, opts.Migrations, opts.Now); err != nil {
295 return fail(err)
296 }
297 if mode == ModeDisk {
298 _ = os.Chmod(opts.Path, 0o600)
299 _ = os.Chmod(opts.Path+"-wal", 0o600)
300 _ = os.Chmod(opts.Path+"-shm", 0o600)
301 }
302 return db, nil
303 }
304
305 func ApplyMigrations(ctx context.Context, db *sql.DB, migrations []Migration, now func() time.Time) error {
306 if now == nil {
307 now = time.Now
308 }
309 if _, err := db.ExecContext(ctx, `CREATE TABLE IF NOT EXISTS schema_migrations (
310 version INTEGER PRIMARY KEY,
311 applied_at INTEGER NOT NULL
312 )`); err != nil {
313 return err
314 }
315 var current int
316 if err := db.QueryRowContext(ctx, `SELECT COALESCE(MAX(version), 0) FROM schema_migrations`).Scan(&current); err != nil {
317 return err
318 }
319 supported := 0
320 for _, migration := range migrations {
321 if migration.Version > supported {
322 supported = migration.Version
323 }
324 }
325 if current > supported {
326 return &FutureSchemaError{Found: current, Supported: supported}
327 }
328 for _, migration := range migrations {
329 if migration.Version <= current {
330 continue
331 }
332 if migration.Version != current+1 || migration.Apply == nil {
333 return fmt.Errorf("projection migration gap after version %d", current)
334 }
335 tx, err := db.BeginTx(ctx, nil)
336 if err != nil {
337 return err
338 }
339 if err := migration.Apply(ctx, tx); err != nil {
340 _ = tx.Rollback()
341 return fmt.Errorf("apply projection migration %d: %w", migration.Version, err)
342 }
343 if _, err := tx.ExecContext(ctx, `INSERT INTO schema_migrations(version, applied_at) VALUES(?, ?)`, migration.Version, now().UnixMilli()); err != nil {
344 _ = tx.Rollback()
345 return err
346 }
347 if err := tx.Commit(); err != nil {
348 return err
349 }
350 current = migration.Version
351 }
352 return nil
353 }
354
355 type Inspection struct {
356 Exists bool `json:"exists"`
357 Path string `json:"path"`
358 Schema int `json:"schema"`
359 Integrity string `json:"integrity,omitempty"`
360 Size int64 `json:"size"`
361 Error string `json:"error,omitempty"`
362 }
363
364 // Inspect is deliberately read-only: it never creates, migrates, repairs, or
365 // quarantines a database.
366 func Inspect(ctx context.Context, path string) Inspection {
367 out := Inspection{Path: path}
368 info, err := os.Stat(path)
369 if errors.Is(err, os.ErrNotExist) {
370 return out
371 }
372 if err != nil {
373 out.Error = err.Error()
374 return out
375 }
376 out.Exists = true
377 out.Size = info.Size()
378 // A live projection may hold its schema and latest commits only in WAL.
379 // immutable=1 would ignore that WAL and report a healthy database as broken.
380 dsn, err := sqliteuri.Disk(path, url.Values{
381 "_pragma": {"busy_timeout(150)", "foreign_keys(1)"},
382 "mode": {"ro"},
383 })
384 if err != nil {
385 out.Error = err.Error()
386 return out
387 }
388 db, err := sql.Open("sqlite", dsn)
389 if err != nil {
390 out.Error = err.Error()
391 return out
392 }
393 defer db.Close()
394 if err := db.QueryRowContext(ctx, `PRAGMA integrity_check`).Scan(&out.Integrity); err != nil {
395 out.Error = err.Error()
396 return out
397 }
398 if err := db.QueryRowContext(ctx, `SELECT COALESCE(MAX(version),0) FROM schema_migrations`).Scan(&out.Schema); err != nil {
399 out.Error = err.Error()
400 }
401 return out
402 }
403
404 func Quarantine(path string, now time.Time) string {
405 if strings.TrimSpace(path) == "" {
406 return ""
407 }
408 quarantined := fmt.Sprintf("%s.corrupt-%d", path, now.UnixMilli())
409 if err := os.Rename(path, quarantined); err != nil {
410 return ""
411 }
412 for _, suffix := range []string{"-wal", "-shm"} {
413 _ = os.Rename(path+suffix, quarantined+suffix)
414 }
415 return quarantined
416 }
417
418 // isCorruptionError reports whether err proves the on-disk projection is unsafe
419 // to keep open. Temporary busy/permission/IO failures must return false so a
420 // multi-process client never renames a healthy database out from under peers.
421 func isCorruptionError(err error) bool {
422 if err == nil {
423 return false
424 }
425 var future *FutureSchemaError
426 if errors.As(err, &future) {
427 return false
428 }
429 var se *moderncsqlite.Error
430 if errors.As(err, &se) {
431 switch se.Code() & 0xff {
432 case sqlite3.SQLITE_CORRUPT, sqlite3.SQLITE_NOTADB:
433 return true
434 default:
435 return false
436 }
437 }
438 msg := strings.ToLower(err.Error())
439 return strings.Contains(msg, "integrity check") ||
440 strings.Contains(msg, "malformed") ||
441 strings.Contains(msg, "file is not a database") ||
442 strings.Contains(msg, "not a database")
443 }
444
445 func PathLooksRemote(path string) bool {
446 clean := filepath.Clean(path)
447 if runtime.GOOS == "windows" && strings.HasPrefix(clean, `\\`) {
448 return true
449 }
450 slash := filepath.ToSlash(clean)
451 return strings.HasPrefix(slash, "/net/") || strings.HasPrefix(slash, "/nfs/") || strings.HasPrefix(slash, "/afs/")
452 }
453
454 // Rebuild constructs and validates a replacement beside the live database,
455 // then swaps it into place. The old projection remains untouched if building,
456 // validation, or the platform rename fails (notably an open database on
457 // Windows). Rebuild never touches authoritative business files.
458 func Rebuild(ctx context.Context, opts OpenOptions, populate func(context.Context, *sql.DB) error) error {
459 if strings.TrimSpace(opts.Path) == "" || opts.InMemory {
460 return errors.New("projection rebuild requires a disk path")
461 }
462 if err := os.MkdirAll(filepath.Dir(opts.Path), 0o700); err != nil {
463 return fmt.Errorf("create projection rebuild directory: %w", err)
464 }
465 release, err := filelock.Acquire(ctx, opts.Path+".rebuild.lock")
466 if err != nil {
467 return fmt.Errorf("lock projection rebuild: %w", err)
468 }
469 defer release()
470 if opts.Now == nil {
471 opts.Now = time.Now
472 }
473 temporary := fmt.Sprintf("%s.rebuild-%d", opts.Path, opts.Now().UnixNano())
474 if opts.ResumeKey != "" {
475 temporary = opts.Path + ".rebuild-pending"
476 }
477 replacement := opts
478 replacement.Path = temporary
479 replacement.InMemory = false
480 replacement.RequireDisk = true
481 handle, err := Open(ctx, replacement)
482 if err != nil {
483 return fmt.Errorf("open projection replacement: %w", err)
484 }
485 cleanupTemporary := func() {
486 _ = os.Remove(temporary)
487 _ = os.Remove(temporary + "-wal")
488 _ = os.Remove(temporary + "-shm")
489 }
490 if handle.Status.Mode != ModeDisk {
491 _ = handle.DB.Close()
492 cleanupTemporary()
493 detail := strings.TrimSpace(handle.Status.LastError)
494 if detail == "" {
495 detail = "unknown open fallback"
496 }
497 return fmt.Errorf("projection replacement could not use disk storage: %s", detail)
498 }
499 if opts.ResumeKey != "" {
500 handle, err = resumeRebuildReplacement(ctx, handle, replacement, cleanupTemporary)
501 if err != nil {
502 return err
503 }
504 }
505 if err := populateRebuildReplacement(ctx, opts, handle, populate, cleanupTemporary); err != nil {
506 return err
507 }
508
509 backup := fmt.Sprintf("%s.replaced-%d", opts.Path, opts.Now().UnixNano())
510 hadOld := false
511 if _, err := os.Stat(opts.Path); err == nil {
512 if err := os.Rename(opts.Path, backup); err != nil {
513 cleanupTemporary()
514 return fmt.Errorf("projection database is busy: %w", err)
515 }
516 hadOld = true
517 for _, suffix := range []string{"-wal", "-shm"} {
518 if err := os.Rename(opts.Path+suffix, backup+suffix); err != nil && !errors.Is(err, os.ErrNotExist) {
519 _ = os.Rename(backup, opts.Path)
520 for _, restored := range []string{"-wal", "-shm"} {
521 _ = os.Rename(backup+restored, opts.Path+restored)
522 }
523 cleanupTemporary()
524 return fmt.Errorf("projection database is busy: %w", err)
525 }
526 }
527 } else if !errors.Is(err, os.ErrNotExist) {
528 cleanupTemporary()
529 return err
530 }
531 if err := os.Rename(temporary, opts.Path); err != nil {
532 if hadOld {
533 _ = os.Rename(backup, opts.Path)
534 for _, suffix := range []string{"-wal", "-shm"} {
535 _ = os.Rename(backup+suffix, opts.Path+suffix)
536 }
537 }
538 cleanupTemporary()
539 return fmt.Errorf("install projection replacement: %w", err)
540 }
541 _ = os.Chmod(opts.Path, 0o600)
542 if hadOld && !opts.RetainBackup {
543 _ = os.Remove(backup)
544 _ = os.Remove(backup + "-wal")
545 _ = os.Remove(backup + "-shm")
546 }
547 cleanupTemporary()
548 return nil
549 }
550
550 lines GO