oficina / mapa Public

Clone
git clone https://amadan.net/oficina/mapa

Plain git — no account needed to clone.

Download

Download this file

1package mapa
2
3import (
4 "context"
5 "errors"
6 "time"
7
8 "gorm.io/gorm"
9
10 "amadan.net/oficina/mapa/internal/mapa/markup"
11 "amadan.net/oficina/mapa/internal/mapa/notionmd"
12)
13
14// Write (Notion import spec §8.1): titles across the whole set, then
15// each page in survey order rendered from its staged tree, its images
16// prepared, and committed through ImportCreate or ImportUpdate; then the
17// fix-up pass; then, only when the run is done, the staged trees go.
18
19func (job *importJob) write(ctx context.Context) error {
20 set, err := job.loadSet(ctx)
21 if err != nil {
22 return err
23 }
24 if err := job.plan(ctx, set); err != nil {
25 return err
26 }
27 for _, entry := range set.pages {
28 if entry.row.State != mapStaged {
29 continue // written before a Resume
30 }
31 if err := job.writePage(ctx, set, entry); err != nil {
32 return err
33 }
34 }
35 if err := job.fixup(ctx, set); err != nil {
36 return err
37 }
38 if err := crashPoint("write:fixed"); err != nil {
39 return err
40 }
41 if err := job.autoPin(ctx, set); err != nil {
42 return err
43 }
44 if err := crashPoint("write:pinned"); err != nil {
45 return err
46 }
47 return job.done(ctx)
48}
49
50// writePage renders, prepares images, commits, and records the outcome.
51func (job *importJob) writePage(ctx context.Context, set *importSet,
52 entry *importEntry) error {
53 if state := job.early(ctx, entry); state != "" {
54 // Its images were not looked at: no counts from an earlier run
55 // in this run's report (round 3, L3).
56 entry.place.Images = nil
57 // Deleted or edited in Mapa: nothing is written, so nothing is
58 // downloaded for it (Fable L15).
59 return job.outcome(ctx, entry, state, "", storedImages(entry))
60 }
61 images, err := job.prepare(ctx, entry)
62 if err != nil {
63 return err
64 }
65 result, err := job.render(ctx, set, entry, images)
66 if ctx.Err() != nil {
67 return ctx.Err() // stopped: not the page's failure
68 }
69 if err != nil {
70 return job.outcome(ctx, entry, mapFailed, "render_failed", images)
71 }
72 entry.result, entry.images = result, images
73 entry.place.Images = &images.counts
74 if err := crashPoint("write:rendered"); err != nil {
75 return err
76 }
77 state, code, err := job.commit(ctx, set, entry, result.Body)
78 if err != nil {
79 return err
80 }
81 if err := crashPoint("write:committed"); err != nil {
82 return err
83 }
84 if state == mapUnchanged {
85 if err := job.recordImages(ctx, entry, images); err != nil {
86 return err
87 }
88 }
89 return job.outcome(ctx, entry, state, code, images)
90}
91
92// prepare fetches what a page's write needs: its blocks' images, then
93// its look (columns and icons spec §6.1), whose images go where the
94// blocks' do: discarded with them, and their places kept with them.
95func (job *importJob) prepare(ctx context.Context,
96 entry *importEntry) (*pageImages, error) {
97 images, err := job.prepareImages(ctx, entry)
98 if err != nil {
99 return nil, err
100 }
101 if entry.look, err = job.prepareLook(ctx, entry,
102 &images.counts); err != nil {
103 return nil, err
104 }
105 images.added = append(images.added, entry.look.added...)
106 images.placed = append(images.placed, entry.look.placed...)
107 return images, nil
108}
109
110// render renders a page within its budget.
111func (job *importJob) render(ctx context.Context, set *importSet,
112 entry *importEntry, images *pageImages) (notionmd.Result, error) {
113 renderCtx, cancel := context.WithTimeout(ctx,
114 renderBudgetFor(entry.staged))
115 defer cancel()
116 options := job.options(set, entry, images)
117 options.Context = renderCtx
118 return notionmd.Render(entry.staged, options)
119}
120
121// renderBudget is how long one page may take to render. A page that
122// takes longer fails alone, render_failed; it never wedges the run
123// (Fable M2). A variable so a test can shorten it.
124var renderBudget = 30 * time.Second
125
126// renderBudgetFor is one page's budget: renderBudget, except where a
127// test gives one page a budget it cannot meet.
128var renderBudgetFor = func(notionmd.Page) time.Duration {
129 return renderBudget
130}
131
132// options are the mapper's options for a page: its parent's title for
133// the In: line, and the date line for a date-titled page (§9.3, §9.4).
134func (job *importJob) options(set *importSet, entry *importEntry,
135 images notionmd.Images) notionmd.Options {
136 options := notionmd.Options{Resolve: set, Images: images,
137 Zone: job.zone, Parent: set.parentTitle(entry)}
138 if raw := fitTitle(plainRuns(entry.staged.Title)); markup.IsDate(
139 Fold(raw)) {
140 options.Date = Fold(raw)
141 }
142 return options
143}
144
145// early is what a mapped page's state already decides, before it is
146// rendered or any image fetched: deleted in Mapa, or kept (§13.2).
147func (job *importJob) early(ctx context.Context, entry *importEntry) string {
148 switch {
149 case !entry.place.mapped(entry.row):
150 return ""
151 case !entry.live:
152 return mapGone
153 case !untouched(entry):
154 entry.place.Kept = job.keptReason(ctx, entry.place.PageID)
155 return mapKept
156 }
157 return ""
158}
159
160// commit decides and writes one page (spec §13.2's table).
161func (job *importJob) commit(ctx context.Context, set *importSet,
162 entry *importEntry, body string) (string, string, error) {
163 if !entry.place.mapped(entry.row) {
164 return job.create(ctx, set, entry, body)
165 }
166 if entry.current.Title == entry.title &&
167 entry.current.Body == cleanBody(body) &&
168 sameLook(entry.current, entry.lookRecord()) {
169 return mapUnchanged, "", nil
170 }
171 return job.update(ctx, set, entry, body)
172}
173
174// update writes an untouched page, taking the next title when a member
175// took the new one mid-run, as create does (Fable L7).
176func (job *importJob) update(ctx context.Context, set *importSet,
177 entry *importEntry, body string) (string, string, error) {
178 for attempt := 1; ; attempt++ {
179 state, code, err := job.updateOnce(ctx, entry, body)
180 if code != "title_taken" || attempt > 8 {
181 return state, code, err
182 }
183 title := fitTitle(plainRuns(entry.staged.Title))
184 plan := &planner{tx: job.store.database.WithContext(ctx),
185 store: job.store, planned: map[string]bool{}}
186 if entry.title, err = plan.next(entry, set, title,
187 attempt); err != nil {
188 return mapFailed, "write_failed", nil
189 }
190 }
191}
192
193func (job *importJob) updateOnce(ctx context.Context, entry *importEntry,
194 body string) (string, string, error) {
195 page, err := job.store.ImportUpdate(ctx, job.writeOf(entry, body))
196 switch {
197 case errors.Is(err, ErrImportKept):
198 // Moved since the run decided: deleted, or edited, in Mapa.
199 if page, found, _ := job.store.anyPage(ctx,
200 entry.place.PageID); !found || page.Gone {
201 // Not live from here on: a later page links it as text,
202 // not as a title that is now free (Fable round 2, Low 4).
203 entry.live = false
204 return mapGone, "", nil
205 }
206 entry.place.Kept = job.keptReason(ctx, entry.place.PageID)
207 return mapKept, "", nil
208 case errors.Is(err, ErrUnlogged):
209 return mapUnchanged, "", nil
210 case errors.Is(err, errLeaseLost), errors.Is(err, errCrashed):
211 return "", "", err
212 case errors.Is(err, ErrTitleTaken):
213 return mapFailed, "title_taken", nil
214 case err != nil:
215 return mapFailed, "write_failed", nil
216 }
217 entry.wrote(page, body)
218 return mapUpdated, "", nil
219}
220
221// wrote is what the run knows of a page it has just written, for the
222// fix-up pass.
223func (entry *importEntry) wrote(page Page, body string) {
224 entry.place.PageID, entry.place.Revision = page.ID, page.Revision
225 entry.live, entry.revision = true, page.Revision
226 look := entry.lookRecord()
227 entry.current = Record{Title: entry.title, Body: cleanBody(body),
228 Icon: look.Icon, Banner: look.Banner}
229}
230
231// lookRecord is the look the run writes for a page: the one it
232// prepared, else the page's own (columns and icons spec §6.4).
233func (entry *importEntry) lookRecord() Record {
234 if entry.look == nil {
235 return Record{Icon: entry.current.Icon, Banner: entry.current.Banner}
236 }
237 return Record{Icon: entry.look.icon, Banner: entry.look.banner}
238}
239
240// create writes a new page, taking the next title when a member took
241// the planned one mid-run (spec §13.6).
242func (job *importJob) create(ctx context.Context, set *importSet,
243 entry *importEntry, body string) (string, string, error) {
244 plan := &planner{tx: job.store.database.WithContext(ctx),
245 store: job.store, planned: map[string]bool{}}
246 for attempt := 1; attempt <= 8; attempt++ {
247 page, err := job.store.ImportCreate(ctx, job.writeOf(entry, body))
248 switch {
249 case err == nil:
250 entry.wrote(page, body)
251 return mapCreated, "", nil
252 case errors.Is(err, errLeaseLost), errors.Is(err, errCrashed):
253 return "", "", err
254 case !errors.Is(err, ErrTitleTaken):
255 return mapFailed, "write_failed", nil
256 }
257 title := fitTitle(plainRuns(entry.staged.Title))
258 if entry.title, err = plan.next(entry, set, title,
259 attempt); err != nil {
260 return mapFailed, "write_failed", nil
261 }
262 }
263 return mapFailed, "title_taken", nil
264}
265
266// writeOf is the store's argument for entry.
267func (job *importJob) writeOf(entry *importEntry, body string) importWrite {
268 place := entry.place
269 place.Title = plainRuns(entry.staged.Title)
270 place.Fitted = entry.title != place.Title
271 // Once renamed in this run, renamed: the fix-up's second write over
272 // the same title must not clear it (Fable round 2, Low 6).
273 place.Renamed = place.Renamed ||
274 (entry.live && entry.current.Title != entry.title)
275 entry.place.Renamed = place.Renamed
276 result := entry.result
277 result.Body = ""
278 place.Render = &result
279 var placed []placedImage
280 if entry.images != nil {
281 place.ImageLines, placed = entry.images.lines, entry.images.placed
282 }
283 look := entry.lookRecord()
284 return importWrite{lease: job.lease, who: job.who, row: entry.row,
285 place: place, title: entry.title, body: body,
286 icon: look.Icon, banner: look.Banner,
287 origin: Origin{Source: "notion", Created: entry.staged.Created,
288 Edited: entry.staged.Edited},
289 pageID: place.PageID, expect: place.Revision, images: placed}
290}
291
292// keptReason reads the page's last event: a teammate's "Update links"
293// is visible as its own reason (spec §8.5).
294func (job *importJob) keptReason(ctx context.Context, pageID int64) string {
295 var verbs []string
296 job.store.database.WithContext(ctx).Model(&Event{}).
297 Where("object_kind = ? AND object_id = ?", ObjectPage, pageID).
298 Order("id DESC").Limit(1).Pluck("verb", &verbs)
299 if len(verbs) == 1 && verbs[0] == VerbRelinked {
300 return "links"
301 }
302 return "edited"
303}
304
305// outcome records what Write did with a page that it did not write, and
306// counts every page. A kept or failed page's pending images go at once.
307func (job *importJob) outcome(ctx context.Context, entry *importEntry,
308 state, code string, images *pageImages) error {
309 entry.row.State = state
310 // A page not written holds its new images nowhere: they go now, not
311 // in seven days (spec §12; Fable round 2, Low 5: deleted too).
312 if state == mapKept || state == mapFailed || state == mapGone {
313 if err := job.images.Discard(ctx, job.who,
314 images.added); err != nil {
315 return err
316 }
317 }
318 return job.store.bookkeep(ctx, job.lease, func(db *gorm.DB) error {
319 if err := job.recordOutcome(db, entry, state, code); err != nil {
320 return err
321 }
322 counts := map[string]any{"written": gorm.Expr("written + 1"),
323 "progress_at": job.store.now().UTC()}
324 if counter := counterOf(state); counter != "" {
325 counts[counter] = gorm.Expr(counter + " + 1")
326 }
327 return db.Model(&NotionRun{}).Where("id = ?", job.lease.run).
328 Updates(counts).Error
329 })
330}
331
332// recordOutcome writes the row for a page the store did not write.
333func (job *importJob) recordOutcome(db *gorm.DB, entry *importEntry,
334 state, code string) error {
335 if state == mapCreated || state == mapUpdated {
336 return nil // the page's own transaction wrote the row
337 }
338 place := entry.place
339 if state != mapFailed && entry.result.Body != "" {
340 place.Title = plainRuns(entry.staged.Title)
341 result := entry.result
342 result.Body = ""
343 place.Render = &result
344 }
345 sealed, err := job.store.sealCoordinate(place)
346 if err != nil {
347 return err
348 }
349 entry.row.ErrorCode, entry.row.SealedCoordinate = code, sealed
350 return db.Model(&entry.row).Select("State", "ErrorCode",
351 "SealedCoordinate").Updates(&entry.row).Error
352}
353
354// counterOf is the run counter a state adds to.
355func counterOf(state string) string {
356 switch state {
357 case mapCreated, mapUpdated, mapUnchanged, mapKept:
358 return state
359 case mapFailed:
360 return "failed"
361 }
362 return "" // deleted in Mapa: the report counts it from the map
363}
364
365// noChange is a bookkeeping write that only checks the lease.
366func noChange(*gorm.DB) error { return nil }
367