| 1 | package memoria |
| 2 | |
| 3 | import ( |
| 4 | "context" |
| 5 | "errors" |
| 6 | "fmt" |
| 7 | "strings" |
| 8 | "time" |
| 9 | |
| 10 | "gorm.io/gorm" |
| 11 | |
| 12 | "amadan.net/oficina/memoria/internal/memoria/chunk" |
| 13 | "amadan.net/oficina/memoria/internal/memoria/seal" |
| 14 | ) |
| 15 | |
| 16 | // Run states. |
| 17 | const ( |
| 18 | RunEnumerating = "enumerating" |
| 19 | RunFetching = "fetching" |
| 20 | RunDone = "done" |
| 21 | RunFailed = "failed" |
| 22 | RunInterrupted = "interrupted" |
| 23 | ) |
| 24 | |
| 25 | // Ledger row states. |
| 26 | const ( |
| 27 | PagePending = "pending" |
| 28 | PageFetched = "fetched" |
| 29 | PageEmpty = "empty" |
| 30 | PageFailed = "failed" |
| 31 | ) |
| 32 | |
| 33 | // heartbeatStale is how long a run may go without a heartbeat before a |
| 34 | // LIVE process may reclaim it. A run killed by the platform sleeping is |
| 35 | // reclaimed at boot instead and does not wait for this. |
| 36 | const heartbeatStale = 10 * time.Minute |
| 37 | |
| 38 | // ErrSyncInFlight is returned when a run is already active. |
| 39 | var ErrSyncInFlight = errors.New("a sync is already running") |
| 40 | |
| 41 | // ErrNoConnector is returned when nothing is configured. |
| 42 | var ErrNoConnector = errors.New("no connector is configured") |
| 43 | |
| 44 | // SaveConnector stores or replaces a connector's credential. |
| 45 | // |
| 46 | // Rotation is replacing the row. There is no key history: a replaced |
| 47 | // token has no remaining use, and keeping one would be a credential |
| 48 | // retained for no reason. |
| 49 | func (s *Store) SaveConnector(ctx context.Context, kind, token, workspace string) error { |
| 50 | sealed, err := s.sealer.Seal(seal.PurposeCredential, []byte(token)) |
| 51 | if err != nil { |
| 52 | return err |
| 53 | } |
| 54 | print, err := s.sealer.Fingerprint(seal.PurposeCredential, []byte("workspace\x00"+workspace)) |
| 55 | if err != nil { |
| 56 | return err |
| 57 | } |
| 58 | now := time.Now().UTC() |
| 59 | return s.db.G.WithContext(ctx).Transaction(func(tx *gorm.DB) error { |
| 60 | return s.guard(ctx, ownerWrite, func() error { return saveConnectorTx(tx, kind, sealed, print, now) }) |
| 61 | }) |
| 62 | } |
| 63 | |
| 64 | func saveConnectorTx(tx *gorm.DB, kind string, sealed []byte, print string, now time.Time) error { |
| 65 | var existing Connector |
| 66 | res := tx.Where("kind = ?", kind).First(&existing) |
| 67 | if res.Error == nil { |
| 68 | // An explicit allowlist, never a bound request body. |
| 69 | return tx.Model(&Connector{}).Where("id = ?", existing.ID).Updates(map[string]any{ |
| 70 | "sealed_token": sealed, |
| 71 | "workspace_print": print, |
| 72 | "last_verified": now, |
| 73 | }).Error |
| 74 | } |
| 75 | return tx.Create(&Connector{ |
| 76 | Kind: kind, SealedToken: sealed, WorkspacePrint: print, LastVerified: &now, |
| 77 | }).Error |
| 78 | } |
| 79 | |
| 80 | // Connector returns a configured connector, without its token. |
| 81 | func (s *Store) Connector(ctx context.Context, kind string) (*Connector, error) { |
| 82 | var c Connector |
| 83 | if err := s.db.G.WithContext(ctx).Where("kind = ?", kind).First(&c).Error; err != nil { |
| 84 | if errors.Is(err, gorm.ErrRecordNotFound) { |
| 85 | return nil, ErrNoConnector |
| 86 | } |
| 87 | return nil, err |
| 88 | } |
| 89 | return &c, nil |
| 90 | } |
| 91 | |
| 92 | // ConnectorToken opens a connector's credential. The only place the |
| 93 | // plaintext token exists outside the notion client. |
| 94 | func (s *Store) ConnectorToken(ctx context.Context, kind string) (string, error) { |
| 95 | c, err := s.Connector(ctx, kind) |
| 96 | if err != nil { |
| 97 | return "", err |
| 98 | } |
| 99 | tok, err := s.sealer.Open(seal.PurposeCredential, c.SealedToken) |
| 100 | if err != nil { |
| 101 | return "", err |
| 102 | } |
| 103 | return string(tok), nil |
| 104 | } |
| 105 | |
| 106 | // DeleteConnector removes the credential and the ledger. |
| 107 | // |
| 108 | // It deletes NO DOCUMENTS. What memoria imported, memoria keeps — the |
| 109 | // content was published into memoria and memoria owns it, so removing it |
| 110 | // is a separate act performed in memoria. The confirmation copy says so |
| 111 | // in those words rather than leaving it to be discovered. |
| 112 | func (s *Store) DeleteConnector(ctx context.Context, kind string) error { |
| 113 | return s.db.G.WithContext(ctx).Transaction(func(tx *gorm.DB) error { |
| 114 | return s.guard(ctx, ownerWrite, func() error { return deleteConnectorTx(tx, kind) }) |
| 115 | }) |
| 116 | } |
| 117 | |
| 118 | func deleteConnectorTx(tx *gorm.DB, kind string) error { |
| 119 | var c Connector |
| 120 | if err := tx.Where("kind = ?", kind).First(&c).Error; err != nil { |
| 121 | if errors.Is(err, gorm.ErrRecordNotFound) { |
| 122 | return nil |
| 123 | } |
| 124 | return err |
| 125 | } |
| 126 | if err := tx.Where("connector_id = ?", c.ID).Delete(&SourcePage{}).Error; err != nil { |
| 127 | return err |
| 128 | } |
| 129 | if err := tx.Where("connector_id = ?", c.ID).Delete(&SyncRun{}).Error; err != nil { |
| 130 | return err |
| 131 | } |
| 132 | return tx.Where("id = ?", c.ID).Delete(&Connector{}).Error |
| 133 | } |
| 134 | |
| 135 | // StartRun opens a run, or refuses because one is already active. |
| 136 | // |
| 137 | // Single-flight is a conditional insert rather than a mutex, so it |
| 138 | // survives a restart — but "survives a restart" was the bug in an earlier |
| 139 | // design, not the feature. The run is a goroutine; when the platform |
| 140 | // sleeps the process it dies without writing anything, leaving the row |
| 141 | // "fetching" and every later sync refused as already-running, forever, on |
| 142 | // the NORMAL path. ReclaimRuns fixes that at boot; the heartbeat below |
| 143 | // covers a run wedged inside a live process. |
| 144 | func (s *Store) StartRun(ctx context.Context, connectorID int64) (*SyncRun, error) { |
| 145 | var run SyncRun |
| 146 | err := s.db.G.WithContext(ctx).Transaction(func(tx *gorm.DB) error { |
| 147 | return s.guard(ctx, ownerWrite, func() error { return startRunTx(tx, connectorID, &run) }) |
| 148 | }) |
| 149 | if err != nil { |
| 150 | return nil, err |
| 151 | } |
| 152 | return &run, nil |
| 153 | } |
| 154 | |
| 155 | func startRunTx(tx *gorm.DB, connectorID int64, run *SyncRun) error { |
| 156 | var active []SyncRun |
| 157 | if err := tx.Where("connector_id = ? AND state IN ?", connectorID, |
| 158 | []string{RunEnumerating, RunFetching}).Find(&active).Error; err != nil { |
| 159 | return err |
| 160 | } |
| 161 | for _, a := range active { |
| 162 | if a.Heartbeat != nil && time.Since(*a.Heartbeat) > heartbeatStale { |
| 163 | if err := tx.Model(&SyncRun{}).Where("id = ?", a.ID).Updates(map[string]any{ |
| 164 | "state": RunInterrupted, |
| 165 | "error_code": "interrupted", |
| 166 | }).Error; err != nil { |
| 167 | return err |
| 168 | } |
| 169 | continue |
| 170 | } |
| 171 | return ErrSyncInFlight |
| 172 | } |
| 173 | now := time.Now().UTC() |
| 174 | *run = SyncRun{ |
| 175 | ConnectorID: connectorID, State: RunEnumerating, |
| 176 | Total: -1, StartedAt: now, Heartbeat: &now, |
| 177 | } |
| 178 | return tx.Create(run).Error |
| 179 | } |
| 180 | |
| 181 | // ReclaimRuns marks every run that was in flight as interrupted. |
| 182 | // |
| 183 | // Called at boot, and sound by construction rather than by timeout: a |
| 184 | // process that has just started cannot be running a sync, so anything |
| 185 | // still marked in flight was killed by the platform. |
| 186 | func (s *Store) ReclaimRuns(ctx context.Context) (int, error) { |
| 187 | res := s.db.G.WithContext(ctx).Model(&SyncRun{}). |
| 188 | Where("state IN ?", []string{RunEnumerating, RunFetching}). |
| 189 | Updates(map[string]any{"state": RunInterrupted, "error_code": "interrupted"}) |
| 190 | return int(res.RowsAffected), res.Error |
| 191 | } |
| 192 | |
| 193 | // LatestRun returns the most recent run for a connector. |
| 194 | func (s *Store) LatestRun(ctx context.Context, connectorID int64) (*SyncRun, error) { |
| 195 | var run SyncRun |
| 196 | err := s.db.G.WithContext(ctx).Where("connector_id = ?", connectorID). |
| 197 | Order("id desc").First(&run).Error |
| 198 | if errors.Is(err, gorm.ErrRecordNotFound) { |
| 199 | return nil, nil |
| 200 | } |
| 201 | if err != nil { |
| 202 | return nil, err |
| 203 | } |
| 204 | return &run, nil |
| 205 | } |
| 206 | |
| 207 | // UpdateRun applies an allowlisted patch to a run. |
| 208 | func (s *Store) UpdateRun(ctx context.Context, runID int64, fields map[string]any) error { |
| 209 | allowed := map[string]bool{ |
| 210 | "state": true, "roots": true, "total": true, "fetched": true, |
| 211 | "skipped": true, "empty": true, "failed_pages": true, |
| 212 | "unread_blocks": true, "error_code": true, "heartbeat": true, |
| 213 | "finished_at": true, |
| 214 | } |
| 215 | patch := make(map[string]any, len(fields)) |
| 216 | for k, v := range fields { |
| 217 | if !allowed[k] { |
| 218 | return fmt.Errorf("update run: field %q is not allowlisted", k) |
| 219 | } |
| 220 | patch[k] = v |
| 221 | } |
| 222 | if len(patch) == 0 { |
| 223 | return nil |
| 224 | } |
| 225 | return s.db.G.WithContext(ctx).Model(&SyncRun{}).Where("id = ?", runID).Updates(patch).Error |
| 226 | } |
| 227 | |
| 228 | // Beat records that a run is still alive. |
| 229 | func (s *Store) Beat(ctx context.Context, runID int64) error { |
| 230 | now := time.Now().UTC() |
| 231 | return s.UpdateRun(ctx, runID, map[string]any{"heartbeat": now}) |
| 232 | } |
| 233 | |
| 234 | // LedgerEntry is one page as the sync loop needs it: the coordinate |
| 235 | // opened, and enough state to decide whether it needs work. |
| 236 | type LedgerEntry struct { |
| 237 | ID int64 |
| 238 | PageID string |
| 239 | Path []string |
| 240 | Title string |
| 241 | SeenEdited string |
| 242 | IngestedEdited string |
| 243 | PathPrint string |
| 244 | State string |
| 245 | DocumentID int64 |
| 246 | } |
| 247 | |
| 248 | // SeeSourcePage records a page the enumeration reached. |
| 249 | // |
| 250 | // Upserts on (connector, page print) and writes what enumeration knows: |
| 251 | // the coordinate, the ancestry, the edit time it SAW. It never touches |
| 252 | // IngestedEdited — that column belongs to the fetch phase, and collapsing |
| 253 | // the two into one makes the comparison compare a value against itself |
| 254 | // and skip every edit. |
| 255 | func (s *Store) SeeSourcePage(ctx context.Context, connectorID int64, pageID, title string, path []string, edited string) error { |
| 256 | print, err := s.sealer.Fingerprint(seal.PurposeCoordinate, []byte("page\x00"+pageID)) |
| 257 | if err != nil { |
| 258 | return err |
| 259 | } |
| 260 | sealedID, err := s.sealer.Seal(seal.PurposeCoordinate, []byte(pageID)) |
| 261 | if err != nil { |
| 262 | return err |
| 263 | } |
| 264 | pathStr := chunk.Chunk{Path: path}.PathString() |
| 265 | // Through the shared helper, never inline. Two places computing this |
| 266 | // fingerprint differently would make every comparison false and |
| 267 | // re-ingest the whole workspace on every sync — or make it always |
| 268 | // true and never re-ingest anything. Both fail quietly. |
| 269 | pathPrint, err := s.pathPrint(path, title) |
| 270 | if err != nil { |
| 271 | return err |
| 272 | } |
| 273 | var sealedPath []byte |
| 274 | if pathStr != "" { |
| 275 | if sealedPath, err = s.sealer.Seal(seal.PurposePath, []byte(pathStr)); err != nil { |
| 276 | return err |
| 277 | } |
| 278 | } |
| 279 | now := time.Now().UTC() |
| 280 | |
| 281 | return s.db.G.WithContext(ctx).Transaction(func(tx *gorm.DB) error { |
| 282 | var row SourcePage |
| 283 | res := tx.Where("connector_id = ? AND page_print = ?", connectorID, print).First(&row) |
| 284 | if res.Error == nil { |
| 285 | return tx.Model(&SourcePage{}).Where("id = ?", row.ID).Updates(map[string]any{ |
| 286 | "sealed_page_id": sealedID, |
| 287 | "sealed_path": sealedPath, |
| 288 | "path_print": pathPrint, |
| 289 | "seen_edited": edited, |
| 290 | "last_seen": now, |
| 291 | }).Error |
| 292 | } |
| 293 | return tx.Create(&SourcePage{ |
| 294 | ConnectorID: connectorID, PagePrint: print, SealedPageID: sealedID, |
| 295 | SealedPath: sealedPath, PathPrint: pathPrint, SeenEdited: edited, |
| 296 | State: PagePending, LastSeen: now, |
| 297 | }).Error |
| 298 | }) |
| 299 | } |
| 300 | |
| 301 | // PagesNeedingWork returns the ledger rows the fetch phase must visit. |
| 302 | // |
| 303 | // Three conditions, and the second is the one an earlier design missed |
| 304 | // entirely: an ANCESTOR rename does not change a descendant's own edit |
| 305 | // time, so without comparing the path print a moved or re-parented page |
| 306 | // keeps stale ancestry forever and nothing upstream ever signals it. |
| 307 | func (s *Store) PagesNeedingWork(ctx context.Context, connectorID int64) ([]LedgerEntry, error) { |
| 308 | var rows []SourcePage |
| 309 | if err := s.db.G.WithContext(ctx). |
| 310 | Where("connector_id = ?", connectorID). |
| 311 | Order("id").Find(&rows).Error; err != nil { |
| 312 | return nil, err |
| 313 | } |
| 314 | out := make([]LedgerEntry, 0, len(rows)) |
| 315 | for _, r := range rows { |
| 316 | if r.State == PageFetched && r.SeenEdited == r.IngestedEdited && r.PathPrint == r.ingestedPathPrint() { |
| 317 | continue |
| 318 | } |
| 319 | id, err := s.sealer.Open(seal.PurposeCoordinate, r.SealedPageID) |
| 320 | if err != nil { |
| 321 | return nil, fmt.Errorf("open coordinate %d: %w", r.ID, err) |
| 322 | } |
| 323 | var path []string |
| 324 | if len(r.SealedPath) > 0 { |
| 325 | p, err := s.sealer.Open(seal.PurposePath, r.SealedPath) |
| 326 | if err != nil { |
| 327 | return nil, fmt.Errorf("open path %d: %w", r.ID, err) |
| 328 | } |
| 329 | if s := string(p); s != "" { |
| 330 | path = strings.Split(s, " › ") |
| 331 | } |
| 332 | } |
| 333 | out = append(out, LedgerEntry{ |
| 334 | ID: r.ID, PageID: string(id), Path: path, |
| 335 | SeenEdited: r.SeenEdited, IngestedEdited: r.IngestedEdited, |
| 336 | PathPrint: r.PathPrint, State: r.State, DocumentID: r.DocumentID, |
| 337 | }) |
| 338 | } |
| 339 | return out, nil |
| 340 | } |
| 341 | |
| 342 | // ingestedPathPrint is the path print as of the last successful ingest. |
| 343 | func (r SourcePage) ingestedPathPrint() string { return r.IngestedPath } |
| 344 | |
| 345 | // MarkPage records the outcome of fetching one page. |
| 346 | func (s *Store) MarkPage(ctx context.Context, id int64, state, errorCode string, documentID int64, edited, pathPrint string) error { |
| 347 | return s.db.G.WithContext(ctx).Model(&SourcePage{}).Where("id = ?", id).Updates(map[string]any{ |
| 348 | "state": state, |
| 349 | "error_code": errorCode, |
| 350 | "document_id": documentID, |
| 351 | "ingested_edited": edited, |
| 352 | "ingested_path": pathPrint, |
| 353 | }).Error |
| 354 | } |
| 355 | |
| 356 | // CountPages returns how many ledger rows a connector holds, and how many |
| 357 | // are in each terminal state. |
| 358 | func (s *Store) CountPages(ctx context.Context, connectorID int64) (total, fetched int, err error) { |
| 359 | var t, f int64 |
| 360 | q := s.db.G.WithContext(ctx).Model(&SourcePage{}).Where("connector_id = ?", connectorID) |
| 361 | if err := q.Count(&t).Error; err != nil { |
| 362 | return 0, 0, err |
| 363 | } |
| 364 | // "Imported" means memoria HOLDS a document for this row, which is |
| 365 | // what document_id records — not what state the last fetch ended in. |
| 366 | // |
| 367 | // Counting states instead made a page that imported fine and then |
| 368 | // 404'd on a later run drop out of the total, though the document was |
| 369 | // still there and still searchable. memoria does not delete on |
| 370 | // absence; the count must not imply that it did. |
| 371 | if err := s.db.G.WithContext(ctx).Model(&SourcePage{}). |
| 372 | Where("connector_id = ? AND document_id > 0", connectorID).Count(&f).Error; err != nil { |
| 373 | return 0, 0, err |
| 374 | } |
| 375 | return int(t), int(f), nil |
| 376 | } |
| 377 | |