| 1 | package docs |
| 2 | |
| 3 | import ( |
| 4 | "context" |
| 5 | "errors" |
| 6 | "strings" |
| 7 | "sync" |
| 8 | "unicode/utf8" |
| 9 | |
| 10 | "github.com/carlosframework/docs/internal/export" |
| 11 | ) |
| 12 | |
| 13 | // The thumbnail on a document's row, and where it comes from. |
| 14 | // |
| 15 | // Spec decision 11 and §6.4 ask the document list for "real rendered |
| 16 | // page-one thumbnails"; §11.4 rules that a raster thumbnail needs a |
| 17 | // pipeline this app does not have. Both are honoured here rather than |
| 18 | // one of them being quietly dropped. The geometry is real — it is the |
| 19 | // PDF exporter's own layout, through export.PageOne, so a row shows |
| 20 | // where the document's first page actually breaks its lines — and no |
| 21 | // raster is involved, because at 26x34 px a US-Letter page is about |
| 22 | // 23 points to the pixel and a glyph is a fraction of one. What is |
| 23 | // drawn is where the text is, at the size the text is. When the layout |
| 24 | // engine and internal/raster land (spec §13), this keeps its shape and |
| 25 | // rasterizes what PageOne already reports. |
| 26 | // |
| 27 | // This replaces the empty box list.html reserved for it. That box was |
| 28 | // deliberately not a fake — "reserved space, not a placeholder image" |
| 29 | // — and the bar that had to be cleared to fill it was showing |
| 30 | // something true about the document, not something plausible. |
| 31 | |
| 32 | // previewBar is one line of the first page, in PAGE POINTS — the same |
| 33 | // coordinate space export.PageOne reports and the same one the SVG's |
| 34 | // viewBox declares, so the browser does the scaling and this code does |
| 35 | // no arithmetic that could disagree with the layout. |
| 36 | // |
| 37 | // Ints, not floats: they are written straight into an SVG attribute by |
| 38 | // html/template, and a float would render in Go's shortest-round-trip |
| 39 | // form (1e+06 for a large one), which is not SVG number syntax. Points |
| 40 | // are fine enough at this scale — one point is a twenty-third of a |
| 41 | // pixel in the rendered box. |
| 42 | type previewBar struct { |
| 43 | X, Y, W, H int |
| 44 | } |
| 45 | |
| 46 | // bars converts a laid-out first page into the rectangles that stand |
| 47 | // in for its lines. |
| 48 | // |
| 49 | // The height of a bar is derived from the type size rather than from |
| 50 | // the line box, so a heading's bar is proportionally taller than a |
| 51 | // body line's, and minBarPt keeps a very small one from collapsing to |
| 52 | // nothing. Both are legibility decisions and the only numbers here not |
| 53 | // reported from the layout. |
| 54 | // |
| 55 | // Be honest about the scale they operate at. 34px for 792pt makes a |
| 56 | // body line box 0.72px and its bar about 0.39px; a heading's is about |
| 57 | // 0.54px. No renderer resolves that difference as "heavier" in any |
| 58 | // literal sense — what actually reaches the eye is a band of sub-pixel |
| 59 | // coverage, and headings read as slightly darker rows within it. It |
| 60 | // works, checked in a browser at 1x and 2x against the seeded |
| 61 | // documents, but the mechanism is antialiasing rather than a drawn |
| 62 | // weight, and a future change here should be judged in a browser |
| 63 | // rather than by the arithmetic. |
| 64 | func bars(lines []export.LineBox) []previewBar { |
| 65 | const ( |
| 66 | barOfSize = 0.66 // of the type size, roughly its cap height |
| 67 | minBarPt = 9.0 |
| 68 | ) |
| 69 | if len(lines) == 0 { |
| 70 | return nil |
| 71 | } |
| 72 | out := make([]previewBar, 0, len(lines)) |
| 73 | for _, l := range lines { |
| 74 | h := l.Size * barOfSize |
| 75 | if h < minBarPt { |
| 76 | h = minBarPt |
| 77 | } |
| 78 | // Centred in its own line box, which is where the text it |
| 79 | // stands for sits. |
| 80 | y := l.Top + (l.Height-h)/2 |
| 81 | out = append(out, previewBar{ |
| 82 | X: int(l.Left + 0.5), |
| 83 | Y: int(y + 0.5), |
| 84 | W: int(l.Width + 0.5), |
| 85 | H: int(h + 0.5), |
| 86 | }) |
| 87 | } |
| 88 | return out |
| 89 | } |
| 90 | |
| 91 | // previews is the document list's thumbnail cache, and the cache of |
| 92 | // each row's opening words. |
| 93 | // |
| 94 | // IN MEMORY, AND NOT IN THE DATABASE — the one decision in this file |
| 95 | // worth arguing with, so here is the argument. A previewBar carries no |
| 96 | // characters: it is four numbers, and the document's words never leave |
| 97 | // export.PageOne (see LineBox's own note). An excerpt is the |
| 98 | // document's own words, so writing it to SQLite WOULD put text at |
| 99 | // rest, outside the seal; it is the running instance holding what it |
| 100 | // already holds whenever it replays a document, and nothing more. |
| 101 | // |
| 102 | // The bars are not written down either, for a reason that outlives |
| 103 | // that. Spec |
| 104 | // §2 seals content at rest and §2's boundary test greps raw SQLite |
| 105 | // bytes for a fixture's known plaintext. A preview column would be a |
| 106 | // second thing to remember to seal when sealing lands, and that grep |
| 107 | // could never catch a lapse, because a shape contains none of the |
| 108 | // fixture's words: the check that guards the seal rule would pass |
| 109 | // while the obligation went unmet. Keeping the cache in memory creates |
| 110 | // no obligation to forget. §2.1's leak list already blesses the |
| 111 | // running instance holding exactly this — item 1 names thumbnails as |
| 112 | // what the trade buys. |
| 113 | // |
| 114 | // Freshness is by construction rather than by invalidation. The key is |
| 115 | // the document's updated_at in Unix nanoseconds, so an edit makes the |
| 116 | // stored entry unreachable without any writer having to remember to |
| 117 | // evict it — and a write path added later cannot forget a call it does |
| 118 | // not have to make. What it does rely on is that every content write |
| 119 | // bumps updated_at; Store.ApplyUpdate's own comment now records that |
| 120 | // as an invariant rather than leaving it as a habit. |
| 121 | // |
| 122 | // Two traps, both live: |
| 123 | // |
| 124 | // - Compare UnixNano, never time.Time with ==. A time read back |
| 125 | // through the sqlite driver and one made with time.Now().UTC() are |
| 126 | // never == even at the same instant, and a cache keyed on that |
| 127 | // comparison silently never hits. |
| 128 | // - Take the timestamp from the row the list query returned, never |
| 129 | // from a *Document that has been through ApplyUpdate: that method |
| 130 | // bumps the column, not the struct it was handed. |
| 131 | type previews struct { |
| 132 | mu sync.Mutex |
| 133 | // by is keyed on Document.ID, and is bounded — see maxPreviews for |
| 134 | // how it is trimmed and why a wipe was the wrong answer. |
| 135 | by map[int64]previewEntry |
| 136 | } |
| 137 | |
| 138 | type previewEntry struct { |
| 139 | updatedAtNanos int64 |
| 140 | // bars is nil for a document with nothing on its first page, and |
| 141 | // for one whose structure would not read at this version. Both are |
| 142 | // settled answers meaning "draw nothing", and both are cached: an |
| 143 | // empty document must not be replayed on every list render, and a |
| 144 | // document whose log will not replay would otherwise be retried on |
| 145 | // every page view for as long as it stays broken, turning one bad |
| 146 | // row into a permanent error-log fountain. |
| 147 | // |
| 148 | // There is no separate "failed" flag. There was one, written and |
| 149 | // never read — get answered from bars being nil either way — so it |
| 150 | // recorded a distinction nothing acted on. |
| 151 | bars []previewBar |
| 152 | // excerpt is the document's opening words (see excerpt), "" when it |
| 153 | // has none. Cached and settled with the bars, from the same parse. |
| 154 | excerpt string |
| 155 | } |
| 156 | |
| 157 | // maxPreviews bounds the map. |
| 158 | // |
| 159 | // Eviction is one arbitrary entry per insert, not a wipe. A wipe was |
| 160 | // wrong in a way worth recording, because it only misbehaves at scale: |
| 161 | // combined with thumbnailBudget, an instance whose listed documents |
| 162 | // exceed this bound would drop everything, warm at most a budget's |
| 163 | // worth on the next render, overflow, and drop it again — so every row |
| 164 | // past the fortieth would draw the empty box on every render, for |
| 165 | // ever. Evicting one keeps the map full of *something* and lets a |
| 166 | // large list warm over successive renders. |
| 167 | // |
| 168 | // Arbitrary rather than least-recently-used on purpose: Go's map |
| 169 | // iteration gives a usable arbitrary key for free, and at this size |
| 170 | // the difference between evicting the coldest entry and evicting a |
| 171 | // random one is not worth the bookkeeping an LRU needs. |
| 172 | const maxPreviews = 512 |
| 173 | |
| 174 | func newPreviews() *previews { return &previews{by: map[int64]previewEntry{}} } |
| 175 | |
| 176 | // get returns the cached entry for doc at its current updated_at, and |
| 177 | // whether there was a usable one. |
| 178 | func (p *previews) get(id int64, updatedAtNanos int64) (previewEntry, bool) { |
| 179 | p.mu.Lock() |
| 180 | defer p.mu.Unlock() |
| 181 | e, ok := p.by[id] |
| 182 | if !ok || e.updatedAtNanos != updatedAtNanos { |
| 183 | return previewEntry{}, false |
| 184 | } |
| 185 | return e, true |
| 186 | } |
| 187 | |
| 188 | func (p *previews) put(id int64, updatedAtNanos int64, e previewEntry) { |
| 189 | p.mu.Lock() |
| 190 | defer p.mu.Unlock() |
| 191 | if _, replacing := p.by[id]; !replacing { |
| 192 | for len(p.by) >= maxPreviews { |
| 193 | for k := range p.by { |
| 194 | delete(p.by, k) |
| 195 | break |
| 196 | } |
| 197 | } |
| 198 | } |
| 199 | e.updatedAtNanos = updatedAtNanos |
| 200 | p.by[id] = e |
| 201 | } |
| 202 | |
| 203 | // thumbnail lays out one document's first page and caches the result. |
| 204 | // The caller has already missed the cache; thumbnailer is what checks |
| 205 | // it, so this does not look again. |
| 206 | // |
| 207 | // It never returns an error. A document whose structure will not read |
| 208 | // gets no thumbnail and the row renders the empty box, because the |
| 209 | // list is the one page that must work and a single unreplayable |
| 210 | // document turning it into a 500 would be a worse bug than the one it |
| 211 | // is reporting. |
| 212 | // |
| 213 | // WHICH failures are remembered is the subtle part. A document whose |
| 214 | // log is corrupt is remembered, so it is not retried on every page |
| 215 | // view for as long as it stays broken. A request that was CANCELLED is |
| 216 | // not: Store.JSON runs on the request's own context, so a viewer who |
| 217 | // closes the tab during a cold render — up to a budget's worth of |
| 218 | // replays — would otherwise stamp "no thumbnail" onto every document |
| 219 | // still being laid out, and each would keep it until its next edit. A |
| 220 | // timeout and a busy database are the same shape. Those say nothing |
| 221 | // about the document, so they are logged at a lower level and left |
| 222 | // uncached, and the next render simply tries again. |
| 223 | func (h *handlers) thumbnail(ctx context.Context, doc *Document) previewEntry { |
| 224 | nanos := doc.UpdatedAt.UnixNano() |
| 225 | |
| 226 | // remember records a settled "draw nothing" for this version. A |
| 227 | // context that is already done means the answer is about the |
| 228 | // request, not the document, so nothing is written down. |
| 229 | remember := func(what string, err error) previewEntry { |
| 230 | if ctx.Err() != nil || errors.Is(err, context.Canceled) || errors.Is(err, context.DeadlineExceeded) { |
| 231 | h.logger.Debug("docs: list thumbnail abandoned with the request", "doc_id", doc.ID, "stage", what, "err", err) |
| 232 | return previewEntry{} |
| 233 | } |
| 234 | h.logger.Error("docs: "+what+" for a list thumbnail", "doc_id", doc.ID, "err", err) |
| 235 | h.previews.put(doc.ID, nanos, previewEntry{}) |
| 236 | return previewEntry{} |
| 237 | } |
| 238 | |
| 239 | structure, err := h.store.JSON(ctx, doc) |
| 240 | if err != nil { |
| 241 | return remember("read structure", err) |
| 242 | } |
| 243 | // Deliberately no title. export.PageOne lays out whatever Title |
| 244 | // the Document carries, because the PDF exporter puts one at the |
| 245 | // top of its first page — a file that does not say which document |
| 246 | // it is, is worse than one that repeats a heading. A thumbnail is |
| 247 | // not a file: it is a picture of the paper, and views/show.html |
| 248 | // keeps the title off the paper entirely (it lives in the shell |
| 249 | // bar, chrome around the document rather than on it). Laying it in |
| 250 | // here would draw a heading the reader has never seen on the page, |
| 251 | // directly beside the very title it duplicates — and would give |
| 252 | // every empty document a one-bar preview of content it does not |
| 253 | // have. |
| 254 | parsed, err := export.Parse("", structure) |
| 255 | if err != nil { |
| 256 | return remember("parse structure", err) |
| 257 | } |
| 258 | |
| 259 | e := previewEntry{bars: bars(export.PageOne(parsed)), excerpt: excerpt(parsed.Root)} |
| 260 | h.previews.put(doc.ID, nanos, e) |
| 261 | return e |
| 262 | } |
| 263 | |
| 264 | // excerptRunes is about two lines of a list row, enough that the one |
| 265 | // line the row shows is always full; the stylesheet does the cutting. |
| 266 | const excerptRunes = 240 |
| 267 | |
| 268 | // excerpt is a document's opening words, for the line under its title |
| 269 | // in the list: the text of its blocks in order, headings skipped (a |
| 270 | // heading is usually the title again, or a section name that says less |
| 271 | // than the paragraph under it), joined with spaces and cut at a word |
| 272 | // near excerptRunes. "" when the document has no body text. |
| 273 | func excerpt(root export.Node) string { |
| 274 | var b strings.Builder |
| 275 | var walk func(n export.Node) bool |
| 276 | walk = func(n export.Node) bool { |
| 277 | if n.Type == "heading" { |
| 278 | return true |
| 279 | } |
| 280 | if n.IsText() { |
| 281 | b.WriteString(n.Text) |
| 282 | return utf8.RuneCountInString(b.String()) < excerptRunes |
| 283 | } |
| 284 | for _, c := range n.Content { |
| 285 | if !walk(c) { |
| 286 | return false |
| 287 | } |
| 288 | } |
| 289 | if n.Type != "doc" && b.Len() > 0 && !strings.HasSuffix(b.String(), " ") { |
| 290 | b.WriteByte(' ') |
| 291 | } |
| 292 | return true |
| 293 | } |
| 294 | walk(root) |
| 295 | text := strings.Join(strings.Fields(b.String()), " ") |
| 296 | if utf8.RuneCountInString(text) <= excerptRunes { |
| 297 | return text |
| 298 | } |
| 299 | cut := []rune(text)[:excerptRunes] |
| 300 | if i := strings.LastIndexByte(string(cut), ' '); i > excerptRunes/2 { |
| 301 | return string(cut)[:i] + "…" |
| 302 | } |
| 303 | return string(cut) + "…" |
| 304 | } |
| 305 | |
| 306 | // thumbnailBudget is how many documents one list render will lay out |
| 307 | // on a cold cache before it stops and leaves the rest to fill in on |
| 308 | // later renders. |
| 309 | // |
| 310 | // The list is the app's landing page and it has no pagination, so |
| 311 | // without a bound the first render after a restart costs one page of |
| 312 | // layout per document a person owns, serially, before a byte of HTML |
| 313 | // is written. With one, a cold cache costs a bounded amount and warms |
| 314 | // over the next few renders; a warm cache never reaches the bound at |
| 315 | // all, because a hit does not spend from it. |
| 316 | // |
| 317 | // Measured rather than guessed, on the seeded sample documents |
| 318 | // (2026-09-02, this machine): a miss is about 1.9ms — replay through |
| 319 | // the snapshot and its tail, then one page of layout — and a hit is |
| 320 | // far under that. 36 documents rendered cold in 68ms and warm in |
| 321 | // 3.4ms. So this bound puts a cold landing page at roughly 75ms of |
| 322 | // layout, which is a page load rather than a stall, and it is only |
| 323 | // ever paid after a restart. Re-measure before raising it; the number |
| 324 | // that matters is the miss, and it grows with a document's update log |
| 325 | // between snapshots. |
| 326 | const thumbnailBudget = 40 |
| 327 | |
| 328 | // thumbnailer returns the function the row builders call for each |
| 329 | // document, holding one render's budget between them. |
| 330 | // |
| 331 | // A cache hit costs nothing and spends nothing, which is what keeps a |
| 332 | // warm list from ever reaching the bound: the budget exists for the |
| 333 | // cold case, and the cold case is the only one that is slow. |
| 334 | func (h *handlers) thumbnailer(ctx context.Context) func(*Document) thumbView { |
| 335 | budget := thumbnailBudget |
| 336 | return func(d *Document) thumbView { |
| 337 | if e, ok := h.previews.get(d.ID, d.UpdatedAt.UnixNano()); ok { |
| 338 | return newThumbView(e) |
| 339 | } |
| 340 | if budget <= 0 { |
| 341 | return newThumbView(previewEntry{}) |
| 342 | } |
| 343 | budget-- |
| 344 | return newThumbView(h.thumbnail(ctx, d)) |
| 345 | } |
| 346 | } |
| 347 | |
| 348 | // thumbView is what list.html's "thumb" template is handed: the bars, |
| 349 | // and the viewBox they are drawn in. |
| 350 | // |
| 351 | // The viewBox travels with them rather than being written into the |
| 352 | // template as a literal, so it is derived from the exporter's own page |
| 353 | // constants — the SVG is the page at its own scale, and [docs-thumb]'s |
| 354 | // 26x34 box does the whole reduction. A literal in the markup would be |
| 355 | // a fourth place US-Letter is written down and the first one nothing |
| 356 | // holds to the other three. |
| 357 | type thumbView struct { |
| 358 | Bars []previewBar |
| 359 | W, H int |
| 360 | // Excerpt is the document's opening words, the line under a list |
| 361 | // row's title. It travels with the bars because it comes from the |
| 362 | // same parse and lives in the same cache entry. |
| 363 | Excerpt string |
| 364 | } |
| 365 | |
| 366 | func newThumbView(e previewEntry) thumbView { |
| 367 | return thumbView{Bars: e.bars, W: int(export.PageWidthPt), H: int(export.PageHeightPt), Excerpt: e.excerpt} |
| 368 | } |
| 369 | |