| 1 | package mapa |
| 2 | |
| 3 | import ( |
| 4 | "context" |
| 5 | "time" |
| 6 | |
| 7 | "gorm.io/gorm" |
| 8 | ) |
| 9 | |
| 10 | // sweepIdleToken is retention's part of the Notion import (its spec §6, |
| 11 | // §8.3): a connection with no run for IdleTokenWindow loses its token, |
| 12 | // and the staged trees of a run nobody resumed go with it. An idle |
| 13 | // token is a liability with no use. Exempt from gate 8 by name, as all |
| 14 | // of retention is; it changes no page. The import's page then says the |
| 15 | // connection is gone, and to remove the integration in Notion. |
| 16 | func (store *Store) sweepIdleToken(ctx context.Context, |
| 17 | now time.Time) error { |
| 18 | // One transaction: the token, the runs it ended and their staged |
| 19 | // trees go together or not at all (Fable M5). |
| 20 | return store.database.WithContext(ctx).Transaction( |
| 21 | func(database *gorm.DB) error { |
| 22 | row, found, err := connection(database) |
| 23 | if err != nil || !found || !idle(database, row, now) { |
| 24 | return err |
| 25 | } |
| 26 | if err := database.Delete(&row).Error; err != nil { |
| 27 | return err |
| 28 | } |
| 29 | err = database.Model(&NotionRun{}).Where("state IN ?", |
| 30 | []string{runInterrupted, runStopped}).Updates( |
| 31 | map[string]any{"state": runFailed, |
| 32 | "error_code": "idle"}).Error |
| 33 | if err != nil { |
| 34 | return err |
| 35 | } |
| 36 | return clearStaged(database) |
| 37 | }) |
| 38 | } |
| 39 | |
| 40 | // idle is a connection with no check and no run for IdleTokenWindow. |
| 41 | func idle(database *gorm.DB, row NotionConnection, now time.Time) bool { |
| 42 | last := row.VerifiedAt |
| 43 | if run, found, err := latestRun(database); err == nil && found { |
| 44 | // The run's last sign of life, not its start: a run that went |
| 45 | // on for days was not idle (Fable round 2, Low 6). |
| 46 | for _, at := range []time.Time{run.StartedAt, run.HeartbeatAt, |
| 47 | run.ProgressAt} { |
| 48 | if at.After(last) { |
| 49 | last = at |
| 50 | } |
| 51 | } |
| 52 | if run.FinishedAt != nil && run.FinishedAt.After(last) { |
| 53 | last = *run.FinishedAt |
| 54 | } |
| 55 | } |
| 56 | return now.Sub(last) >= IdleTokenWindow |
| 57 | } |
| 58 | |