| 1 | package mapa |
| 2 | |
| 3 | import ( |
| 4 | "context" |
| 5 | "errors" |
| 6 | "log/slog" |
| 7 | "sync" |
| 8 | "time" |
| 9 | |
| 10 | "gorm.io/gorm" |
| 11 | |
| 12 | "amadan.net/oficina/mapa/internal/mapa/notionmd" |
| 13 | "amadan.net/oficina/notion.git/notion" |
| 14 | ) |
| 15 | |
| 16 | // A run is a goroutine the starting request spawns (Notion import spec |
| 17 | // §8.1). It is not a background worker: it runs until it finishes, is |
| 18 | // stopped, or the platform sleeps the process, which boot then reports |
| 19 | // as interrupted. |
| 20 | |
| 21 | // importJob is one run's goroutine and what it needs. |
| 22 | type importJob struct { |
| 23 | store *Store |
| 24 | logger *slog.Logger |
| 25 | zone *time.Location |
| 26 | lease runLease |
| 27 | // who is the person who pressed Start or Resume: every write is |
| 28 | // theirs (P7). |
| 29 | who string |
| 30 | client *notion.Client |
| 31 | files *notion.Files |
| 32 | images ImageStore |
| 33 | imagesStopped string |
| 34 | } |
| 35 | |
| 36 | // imports is the app's running jobs, so Stop can cancel one. |
| 37 | type imports struct { |
| 38 | mutex sync.Mutex |
| 39 | cancels map[int64]context.CancelFunc |
| 40 | // wait lets a test wait for a job to end. |
| 41 | wait sync.WaitGroup |
| 42 | } |
| 43 | |
| 44 | // launch builds the run's client and starts its goroutine. |
| 45 | func (app *app) launch(lease runLease, who string) error { |
| 46 | token, err := app.store.token(context.Background()) |
| 47 | if err != nil { |
| 48 | return err |
| 49 | } |
| 50 | client, err := app.notion.Client(token) |
| 51 | if err != nil { |
| 52 | return err |
| 53 | } |
| 54 | job := &importJob{store: app.store, logger: app.logger, |
| 55 | zone: app.config.TimeZone, lease: lease, who: who, client: client, |
| 56 | files: app.notion.Files(), images: app.images} |
| 57 | ctx, cancel := context.WithCancel(context.Background()) |
| 58 | app.running.mutex.Lock() |
| 59 | if app.running.cancels == nil { |
| 60 | app.running.cancels = map[int64]context.CancelFunc{} |
| 61 | } |
| 62 | if previous := app.running.cancels[lease.run]; previous != nil { |
| 63 | previous() |
| 64 | } |
| 65 | app.running.cancels[lease.run] = cancel |
| 66 | app.running.mutex.Unlock() |
| 67 | app.running.wait.Add(1) |
| 68 | go func() { |
| 69 | defer app.running.wait.Done() |
| 70 | defer cancel() |
| 71 | job.run(ctx) |
| 72 | }() |
| 73 | return nil |
| 74 | } |
| 75 | |
| 76 | // begin launches a run just started or resumed. If the launch fails |
| 77 | // (the token cannot be opened, the client cannot be built), the run is |
| 78 | // ended failed at once, so it never sits "Reading Notion" for the two |
| 79 | // minutes until it could be reclaimed (Fable L8). |
| 80 | func (app *app) begin(lease runLease, who string) error { |
| 81 | err := app.launch(lease, who) |
| 82 | if err != nil { |
| 83 | _ = app.store.endRun(context.Background(), lease, runFailed, |
| 84 | runInternal) |
| 85 | } |
| 86 | return err |
| 87 | } |
| 88 | |
| 89 | // cancel stops a run's goroutine waiting, after Stop rotated its lease. |
| 90 | func (app *app) cancel(run int64) { |
| 91 | app.running.mutex.Lock() |
| 92 | defer app.running.mutex.Unlock() |
| 93 | if cancel := app.running.cancels[run]; cancel != nil { |
| 94 | cancel() |
| 95 | } |
| 96 | } |
| 97 | |
| 98 | // run is the goroutine. Its panics are its own: a crash ends the run |
| 99 | // failed with internal, never a run that looks alive (spec §8.3). |
| 100 | func (job *importJob) run(ctx context.Context) { |
| 101 | defer func() { |
| 102 | if recovered := recover(); recovered != nil { |
| 103 | job.logger.Error("notion import panicked", "run", job.lease.run) |
| 104 | _ = job.store.endRun(context.Background(), job.lease, runFailed, |
| 105 | runInternal) |
| 106 | } |
| 107 | }() |
| 108 | ctx, stop := context.WithCancel(ctx) |
| 109 | defer stop() |
| 110 | go job.heartbeat(ctx, stop) |
| 111 | err := job.phases(ctx) |
| 112 | switch { |
| 113 | case err == nil, errors.Is(err, errLeaseLost), ctx.Err() != nil, |
| 114 | errors.Is(err, errCrashed): |
| 115 | return |
| 116 | } |
| 117 | code := string(notion.CodeOf(err)) |
| 118 | var coded *notion.Error |
| 119 | if !errors.As(err, &coded) { |
| 120 | code = runInternal |
| 121 | job.logger.Error("notion import failed", "run", job.lease.run, |
| 122 | "err", err) |
| 123 | } |
| 124 | _ = job.store.endRun(context.Background(), job.lease, runFailed, code) |
| 125 | } |
| 126 | |
| 127 | func (job *importJob) phases(ctx context.Context) error { |
| 128 | var run NotionRun |
| 129 | err := job.store.database.WithContext(ctx). |
| 130 | Where("id = ?", job.lease.run).First(&run).Error |
| 131 | if err != nil { |
| 132 | return err |
| 133 | } |
| 134 | if run.State == runSurveying { |
| 135 | if err := job.survey(ctx); err != nil { |
| 136 | return err |
| 137 | } |
| 138 | } |
| 139 | return job.write(ctx) |
| 140 | } |
| 141 | |
| 142 | // heartbeat proves the goroutine is alive every heartbeatEvery. When the |
| 143 | // lease has moved it stops the run's context: Stop or a reclaim took |
| 144 | // the run. |
| 145 | func (job *importJob) heartbeat(ctx context.Context, stop func()) { |
| 146 | ticker := time.NewTicker(heartbeatEvery) |
| 147 | defer ticker.Stop() |
| 148 | for { |
| 149 | select { |
| 150 | case <-ctx.Done(): |
| 151 | return |
| 152 | case <-ticker.C: |
| 153 | err := job.store.runUpdate(ctx, job.lease, map[string]any{ |
| 154 | "heartbeat_at": job.store.now().UTC()}) |
| 155 | if errors.Is(err, errLeaseLost) { |
| 156 | stop() |
| 157 | return |
| 158 | } |
| 159 | } |
| 160 | } |
| 161 | } |
| 162 | |
| 163 | // fixup re-renders, from the staged trees, every page written in this |
| 164 | // run that links to another, and commits it again where its body |
| 165 | // changed and it is still untouched (spec §13.6). Every such page, not |
| 166 | // only those linking to a page whose plan moved within this run: after |
| 167 | // a Resume the plan is made afresh, and a title a member took before it |
| 168 | // would be missed (Fable L6). |
| 169 | func (job *importJob) fixup(ctx context.Context, set *importSet) error { |
| 170 | for _, entry := range set.pages { |
| 171 | if len(entry.result.Targets) == 0 && entry.place.Render != nil { |
| 172 | entry.result.Targets = entry.place.Render.Targets |
| 173 | } |
| 174 | written := entry.row.State == mapCreated || |
| 175 | entry.row.State == mapUpdated |
| 176 | if !written || len(entry.result.Targets) == 0 { |
| 177 | continue |
| 178 | } |
| 179 | if err := job.fixOne(ctx, set, entry); err != nil { |
| 180 | return err |
| 181 | } |
| 182 | } |
| 183 | return nil |
| 184 | } |
| 185 | |
| 186 | func (job *importJob) fixOne(ctx context.Context, set *importSet, |
| 187 | entry *importEntry) error { |
| 188 | images := entry.images |
| 189 | if images == nil { |
| 190 | images = storedImages(entry) |
| 191 | } |
| 192 | options := job.options(set, entry, images) |
| 193 | options.Context = ctx |
| 194 | result, err := notionmd.Render(entry.staged, options) |
| 195 | if err != nil || cleanBody(result.Body) == entry.current.Body { |
| 196 | return nil |
| 197 | } |
| 198 | entry.result, entry.images = result, images |
| 199 | write := job.writeOf(entry, result.Body) |
| 200 | write.state = entry.row.State |
| 201 | page, err := job.store.ImportUpdate(ctx, write) |
| 202 | if errors.Is(err, errLeaseLost) || errors.Is(err, errCrashed) { |
| 203 | return err |
| 204 | } |
| 205 | if err == nil { |
| 206 | entry.wrote(page, result.Body) |
| 207 | } |
| 208 | return nil |
| 209 | } |
| 210 | |
| 211 | // done ends a finished run: its staged trees are cleared in one |
| 212 | // bookkeeping write with the run's state (spec §8.1). |
| 213 | func (job *importJob) done(ctx context.Context) error { |
| 214 | now := job.store.now().UTC() |
| 215 | return job.store.bookkeep(ctx, job.lease, func(db *gorm.DB) error { |
| 216 | err := db.Model(&NotionPage{}).Where("surveyed_run = ? AND "+ |
| 217 | "sealed_staged IS NOT NULL", job.lease.run). |
| 218 | Update("sealed_staged", nil).Error |
| 219 | if err != nil { |
| 220 | return err |
| 221 | } |
| 222 | return db.Model(&NotionRun{}).Where("id = ?", job.lease.run). |
| 223 | Updates(map[string]any{"state": runDone, "finished_at": &now, |
| 224 | "error_code": ""}).Error |
| 225 | }) |
| 226 | } |
| 227 | |
| 228 | // importCrash, when a test sets it, is asked at each named point |
| 229 | // between two statements of the run and of ImportCreate and |
| 230 | // ImportUpdate; an error there is the process dying at that point |
| 231 | // (gate I17). Nil in production. |
| 232 | var importCrash func(point string) error |
| 233 | |
| 234 | // errCrashed is what a test's crash returns: the run stops as a dead |
| 235 | // process would, writing nothing more. |
| 236 | var errCrashed = errors.New("mapa: crashed here (a test)") |
| 237 | |
| 238 | func crashPoint(point string) error { |
| 239 | if importCrash == nil { |
| 240 | return nil |
| 241 | } |
| 242 | return importCrash(point) |
| 243 | } |
| 244 | |
| 245 | // WaitImports waits for every running import to end. Tests only. |
| 246 | func (built Built) WaitImports() { built.app.running.wait.Wait() } |
| 247 | |