| 1 | package mapa |
| 2 | |
| 3 | import ( |
| 4 | "context" |
| 5 | "errors" |
| 6 | "time" |
| 7 | |
| 8 | "gorm.io/gorm" |
| 9 | ) |
| 10 | |
| 11 | // A run's life (Notion import spec §8.3). One run at a time; every write |
| 12 | // it makes checks its lease; Stop rotates the lease before it cancels, |
| 13 | // so a goroutine that ignores its context still changes nothing. |
| 14 | |
| 15 | // Run states. |
| 16 | const ( |
| 17 | runSurveying = "surveying" |
| 18 | runWriting = "writing" |
| 19 | runDone = "done" |
| 20 | runInterrupted = "interrupted" |
| 21 | runStopped = "stopped" |
| 22 | runFailed = "failed" |
| 23 | ) |
| 24 | |
| 25 | // Run error codes Mapa sets itself; Notion's are the module's codes. |
| 26 | const ( |
| 27 | runDisconnected = "disconnected" |
| 28 | runFinished = "finished" |
| 29 | runForgotten = "forgotten" |
| 30 | runInternal = "internal" |
| 31 | ) |
| 32 | |
| 33 | // Liveness (spec §8.3): a run may be reclaimed by Resume when its |
| 34 | // heartbeat is older than staleHeartbeat or its progress older than |
| 35 | // staleProgress. Variables so a test can age a run. |
| 36 | var ( |
| 37 | heartbeatEvery = 20 * time.Second |
| 38 | staleHeartbeat = 2 * time.Minute |
| 39 | staleProgress = 10 * time.Minute |
| 40 | ) |
| 41 | |
| 42 | // ErrNoRun is a Resume or Stop with nothing to act on. |
| 43 | var ErrNoRun = errors.New("There's no import run to do that to.") |
| 44 | |
| 45 | // latestRun is the newest run, if any. |
| 46 | func latestRun(database *gorm.DB) (NotionRun, bool, error) { |
| 47 | var run NotionRun |
| 48 | err := database.Order("id DESC").First(&run).Error |
| 49 | if errors.Is(err, gorm.ErrRecordNotFound) { |
| 50 | return run, false, nil |
| 51 | } |
| 52 | return run, err == nil, err |
| 53 | } |
| 54 | |
| 55 | // reclaimable is an active run whose goroutine is gone or wedged. |
| 56 | func reclaimable(run NotionRun, now time.Time) bool { |
| 57 | return now.Sub(run.HeartbeatAt) > staleHeartbeat || |
| 58 | now.Sub(run.ProgressAt) > staleProgress |
| 59 | } |
| 60 | |
| 61 | // resumable is a run Resume may continue. |
| 62 | func resumable(run NotionRun, now time.Time) bool { |
| 63 | switch run.State { |
| 64 | case runInterrupted, runStopped: |
| 65 | return true |
| 66 | case runSurveying, runWriting: |
| 67 | return reclaimable(run, now) |
| 68 | } |
| 69 | return false |
| 70 | } |
| 71 | |
| 72 | // StartRun begins a new run as who, after done or failed or with none |
| 73 | // before. A failed run's staged trees are cleared now (spec §8.3). |
| 74 | func (store *Store) StartRun(ctx context.Context, who string, |
| 75 | over bool) (runLease, error) { |
| 76 | verb := VerbStarted |
| 77 | if over { |
| 78 | verb = VerbStartedOver |
| 79 | } |
| 80 | var lease runLease |
| 81 | err := store.write(ctx, func(tx *Tx) error { |
| 82 | actor, err := tx.member(who) |
| 83 | if err != nil { |
| 84 | return err |
| 85 | } |
| 86 | if err := tx.startable(over); err != nil { |
| 87 | return err |
| 88 | } |
| 89 | if err := tx.endResumable(VerbStartedOver); err != nil { |
| 90 | return err |
| 91 | } |
| 92 | lease, err = tx.newRun(actor) |
| 93 | if err != nil { |
| 94 | return err |
| 95 | } |
| 96 | return tx.log(actor, ObjectImport, lease.run, verb, 0) |
| 97 | }) |
| 98 | return lease, err |
| 99 | } |
| 100 | |
| 101 | // startable allows Start after done or failed, or with no run before, |
| 102 | // and Start over only where Resume would be offered. A live run refuses |
| 103 | // both: Stop it first. |
| 104 | func (tx *Tx) startable(over bool) error { |
| 105 | if _, found, err := connection(tx.db); err != nil || !found { |
| 106 | return errors.Join(ErrNotConnected, err) |
| 107 | } |
| 108 | run, found, err := latestRun(tx.db) |
| 109 | switch { |
| 110 | case err != nil: |
| 111 | return err |
| 112 | case !found && over: |
| 113 | return ErrNoRun |
| 114 | case !found: |
| 115 | return nil |
| 116 | case live(run, tx.at): |
| 117 | return ErrRunActive |
| 118 | case resumable(run, tx.at) != over && over: |
| 119 | return ErrNoRun |
| 120 | case resumable(run, tx.at) != over: |
| 121 | return ErrRunActive |
| 122 | } |
| 123 | // A wedged run being started over is stopped first, so its |
| 124 | // goroutine, if any, writes nothing more. |
| 125 | return tx.db.Model(&NotionRun{}).Where("state IN ?", []string{ |
| 126 | runSurveying, runWriting}).Updates(map[string]any{ |
| 127 | "state": runStopped, "lease": 0}).Error |
| 128 | } |
| 129 | |
| 130 | // live is a run surveying or writing whose goroutine is alive. |
| 131 | func live(run NotionRun, now time.Time) bool { |
| 132 | return (run.State == runSurveying || run.State == runWriting) && |
| 133 | !reclaimable(run, now) |
| 134 | } |
| 135 | |
| 136 | func (tx *Tx) newRun(actor int64) (runLease, error) { |
| 137 | lease, err := randomPositive() |
| 138 | if err != nil { |
| 139 | return runLease{}, err |
| 140 | } |
| 141 | run := NotionRun{Actor: actor, State: runSurveying, Lease: lease, |
| 142 | StartedAt: tx.at, HeartbeatAt: tx.at, ProgressAt: tx.at} |
| 143 | if err := tx.db.Create(&run).Error; err != nil { |
| 144 | return runLease{}, err |
| 145 | } |
| 146 | return runLease{run: run.ID, lease: lease}, nil |
| 147 | } |
| 148 | |
| 149 | // ResumeRun continues the newest run as who, with a new lease: the old |
| 150 | // goroutine, if it is still going, writes nothing more. It answers the |
| 151 | // lease and whether the survey still has pages to read. |
| 152 | func (store *Store) ResumeRun(ctx context.Context, who string) (runLease, |
| 153 | error) { |
| 154 | var lease runLease |
| 155 | err := store.write(ctx, func(tx *Tx) error { |
| 156 | actor, err := tx.member(who) |
| 157 | if err != nil { |
| 158 | return err |
| 159 | } |
| 160 | run, found, err := latestRun(tx.db) |
| 161 | if err != nil || !found || !resumable(run, tx.at) { |
| 162 | return errors.Join(ErrNoRun, err) |
| 163 | } |
| 164 | if lease, err = tx.rotate(run, actor, resumeState(run)); err != nil { |
| 165 | return err |
| 166 | } |
| 167 | return tx.log(actor, ObjectImport, run.ID, VerbResumed, 0) |
| 168 | }) |
| 169 | return lease, err |
| 170 | } |
| 171 | |
| 172 | // resumeState is where a resumed run picks up: a survey that finished |
| 173 | // set the total, so the run writes; otherwise it surveys. |
| 174 | func resumeState(run NotionRun) string { |
| 175 | if run.Total > 0 || run.State == runWriting { |
| 176 | return runWriting |
| 177 | } |
| 178 | return runSurveying |
| 179 | } |
| 180 | |
| 181 | // rotate gives a run a new lease and state, as actor, with fresh clocks. |
| 182 | func (tx *Tx) rotate(run NotionRun, actor int64, state string) (runLease, |
| 183 | error) { |
| 184 | lease, err := randomPositive() |
| 185 | if err != nil { |
| 186 | return runLease{}, err |
| 187 | } |
| 188 | err = tx.db.Model(&run).Updates(map[string]any{"state": state, |
| 189 | "lease": lease, "actor": actor, "heartbeat_at": tx.at, |
| 190 | "progress_at": tx.at, "error_code": ""}).Error |
| 191 | return runLease{run: run.ID, lease: lease}, err |
| 192 | } |
| 193 | |
| 194 | // StopRun ends the active run at once: one write sets it stopped and |
| 195 | // rotates its lease, so its goroutine's next write of any kind fails, |
| 196 | // whether or not it heeds its context (spec §8.3). |
| 197 | func (store *Store) StopRun(ctx context.Context, who string) (int64, |
| 198 | error) { |
| 199 | var stopped int64 |
| 200 | err := store.write(ctx, func(tx *Tx) error { |
| 201 | actor, err := tx.member(who) |
| 202 | if err != nil { |
| 203 | return err |
| 204 | } |
| 205 | run, found, err := activeRun(tx.db) |
| 206 | if err != nil || !found { |
| 207 | return errors.Join(ErrNoRun, err) |
| 208 | } |
| 209 | if _, err := tx.rotate(run, run.Actor, runStopped); err != nil { |
| 210 | return err |
| 211 | } |
| 212 | stopped = run.ID |
| 213 | return tx.log(actor, ObjectImport, run.ID, VerbStopped, 0) |
| 214 | }) |
| 215 | return stopped, err |
| 216 | } |
| 217 | |
| 218 | // InterruptRuns is boot's: no run can be live when the process starts, |
| 219 | // so one left surveying or writing is interrupted, and offers Resume |
| 220 | // (spec §8.3). Bookkeeping: it changes no page. |
| 221 | func (store *Store) InterruptRuns(ctx context.Context) error { |
| 222 | return store.bookkeep(ctx, runLease{}, func(database *gorm.DB) error { |
| 223 | return database.Model(&NotionRun{}).Where("state IN ?", |
| 224 | []string{runSurveying, runWriting}).Updates(map[string]any{ |
| 225 | "state": runInterrupted, "lease": 0}).Error |
| 226 | }) |
| 227 | } |
| 228 | |
| 229 | // runUpdate is one lease-checked write to the run's own row. |
| 230 | func (store *Store) runUpdate(ctx context.Context, lease runLease, |
| 231 | values map[string]any) error { |
| 232 | return store.bookkeep(ctx, lease, func(database *gorm.DB) error { |
| 233 | return database.Model(&NotionRun{}).Where("id = ?", lease.run). |
| 234 | Updates(values).Error |
| 235 | }) |
| 236 | } |
| 237 | |
| 238 | // endRun sets a run's final state, if it still holds its lease. |
| 239 | func (store *Store) endRun(ctx context.Context, lease runLease, state, |
| 240 | code string) error { |
| 241 | now := store.now().UTC() |
| 242 | return store.runUpdate(ctx, lease, map[string]any{"state": state, |
| 243 | "error_code": code, "finished_at": &now}) |
| 244 | } |
| 245 | |