| 1 | package historycatalog |
| 2 | |
| 3 | import ( |
| 4 | "context" |
| 5 | "database/sql" |
| 6 | "strings" |
| 7 | "time" |
| 8 | |
| 9 | "reasonix/internal/projectiondb" |
| 10 | ) |
| 11 | |
| 12 | // Rebuild replaces only the disposable FTS projection after indexing every |
| 13 | // supplied authoritative root into a validated sibling database. |
| 14 | func Rebuild(ctx context.Context, opts Options, roots []Root) (Status, error) { |
| 15 | opts = rebuildOptions(opts) |
| 16 | if opts.InMemory || strings.TrimSpace(opts.Path) == "" { |
| 17 | catalog, err := Open(ctx, opts) |
| 18 | if err != nil { |
| 19 | return Status{}, err |
| 20 | } |
| 21 | for _, root := range roots { |
| 22 | if err := catalog.ReconcileRoot(ctx, root); err != nil { |
| 23 | closeRebuildCatalog(catalog) |
| 24 | return catalog.Status(), err |
| 25 | } |
| 26 | } |
| 27 | status := catalog.Status() |
| 28 | closeRebuildCatalog(catalog) |
| 29 | return status, nil |
| 30 | } |
| 31 | err := projectiondb.Rebuild(ctx, projectiondb.OpenOptions{ |
| 32 | Path: opts.Path, MemoryName: "history-search-rebuild", Migrations: migrations(), |
| 33 | SecureDelete: true, AutoVacuum: true, |
| 34 | }, func(ctx context.Context, db *sql.DB) error { |
| 35 | catalog := &Catalog{db: db, opts: opts, status: Status{State: "ready", Mode: projectiondb.ModeDisk, Path: opts.Path}} |
| 36 | for _, root := range roots { |
| 37 | if err := catalog.ReconcileRoot(ctx, root); err != nil { |
| 38 | return err |
| 39 | } |
| 40 | } |
| 41 | return nil |
| 42 | }) |
| 43 | if err != nil { |
| 44 | return Status{}, err |
| 45 | } |
| 46 | published, err := Open(ctx, opts) |
| 47 | if err != nil { |
| 48 | return Status{}, err |
| 49 | } |
| 50 | status := published.Status() |
| 51 | closeRebuildCatalog(published) |
| 52 | return status, nil |
| 53 | } |
| 54 | |
| 55 | func rebuildOptions(opts Options) Options { |
| 56 | if opts.Path == "" { |
| 57 | opts.Path = DefaultPath() |
| 58 | } |
| 59 | if strings.TrimSpace(opts.Path) == "" { |
| 60 | opts.Path, opts.InMemory = "", true |
| 61 | } |
| 62 | if opts.Now == nil { |
| 63 | opts.Now = time.Now |
| 64 | } |
| 65 | if opts.MissingGrace <= 0 { |
| 66 | opts.MissingGrace = defaultMissingGrace |
| 67 | } |
| 68 | opts.OnRevision = nil |
| 69 | return opts |
| 70 | } |
| 71 | |
| 72 | func closeRebuildCatalog(catalog *Catalog) { |
| 73 | closeCtx, cancel := context.WithTimeout(context.Background(), time.Second) |
| 74 | defer cancel() |
| 75 | _ = catalog.Close(closeCtx) |
| 76 | } |
| 77 |