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 "database/sql"
6 "errors"
7 "fmt"
8 "strings"
9 "sync"
10 "sync/atomic"
11 "time"
12
13 "amadan.net/oficina/mapa/internal/mapa/markup"
14)
15
16// Index is the in-memory, decrypted view of every live page: links,
17// pending links, backlinks, unlinked mentions and search (§3.2, decision
18// 14). None of it is written to the durable file; it is rebuilt from
19// sealed rows on wake.
20//
21// **The event log is its change feed**, as in Fichas: every write lands
22// an event in the same transaction, so the highest event id answers "has
23// anything changed", and the events past it say which pages. No write
24// path tells the index anything.
25//
26// **Partitioned by scope** (§6.2): team pages in one partition, each
27// person's private pages in their own. Every read takes the team
28// partition and the viewer's own, and nothing else, so what Ana's
29// private notes hold cannot change what Bo is shown (gate 1).
30type Index struct {
31 store *Store
32
33 mutex sync.RWMutex
34 loaded bool
35 seen int64
36 // catchUps counts catch-ups, all of them in writers' requests.
37 // Tests read it to hold that a reader never does one.
38 catchUps atomic.Int64
39 pages map[int64]*entry
40 // titles maps a folded title or alias to its live team page.
41 titles map[string]int64
42 // team and private are the partitions: page ids, and private ones
43 // by owner.
44 team map[int64]bool
45 private map[int64]map[int64]bool
46 // linkers maps a folded link text to the pages that type it.
47 linkers map[string]*linkers
48 // days maps an owner and a date to their daily note.
49 days map[int64]map[string]int64
50 // teamTerms and ownTerms are the search postings (postings.go),
51 // partitioned exactly as team and private are.
52 teamTerms *partition
53 ownTerms map[int64]*partition
54 // titleRows is every team title and alias, sorted, for prefix
55 // search; rebuilt after a change, never at query time.
56 titleRows []titleRow
57 titlesDirty bool
58 pending pendingSet
59 // within maps a folded link text to the team pages whose "In:" line
60 // names it (inside.go, columns and icons spec §5.1).
61 within map[string]map[int64]bool
62}
63
64// entry is one live page, opened and parsed.
65type entry struct {
66 id, nonce, owner int64
67 revision int64
68 kind, rung string
69 created, updated time.Time
70 record Record
71 aliases []AliasView
72 blocks []markup.Block
73 links []markup.Link
74 // in is the folded target of the page's "In:" line, or "".
75 in string
76 // unlinked is each block's words outside links and code (§6.4).
77 unlinked [][]word
78 // counts and length are what the page is indexed with for search.
79 counts map[string]uint16
80 length int
81}
82
83// team reports whether every member may open the page.
84func (page *entry) team() bool { return page.rung == RungTeam }
85
86// linkers is the pages that type one link text, partitioned like the
87// index: text as typed, by page.
88type linkers struct {
89 team map[int64]string
90 private map[int64]map[int64]string
91}
92
93// NewIndex returns an empty index; it loads on first use.
94func NewIndex(store *Store) *Index {
95 index := &Index{store: store}
96 index.reset()
97 store.afterWrite(func(ctx context.Context) {
98 if err := index.caughtUp(ctx); err != nil {
99 // The commit stands; the index is behind until the next
100 // write catches it up, or the next wake reloads it.
101 store.logger().Error("catching the index up", "err", err)
102 }
103 })
104 return index
105}
106
107// CatchUps is how many times the index has followed the event log.
108func (index *Index) CatchUps() int64 { return index.catchUps.Load() }
109
110func (index *Index) reset() {
111 index.pages = map[int64]*entry{}
112 index.titles = map[string]int64{}
113 index.team = map[int64]bool{}
114 index.private = map[int64]map[int64]bool{}
115 index.linkers = map[string]*linkers{}
116 index.days = map[int64]map[string]int64{}
117 index.teamTerms = newPartition()
118 index.ownTerms = map[int64]*partition{}
119 index.titleRows, index.titlesDirty = nil, true
120 index.pending = pendingSet{dirty: true}
121 index.within = map[string]map[int64]bool{}
122}
123
124// Sync readies the index for a read. A reader never catches the index
125// up: the writer whose commit changed it already has (review M3), so a
126// reader takes only the read lock and never parses someone else's
127// write. The first read after a wake loads everything.
128func (index *Index) Sync(ctx context.Context) error {
129 index.mutex.RLock()
130 loaded := index.loaded
131 index.mutex.RUnlock()
132 if loaded {
133 return nil
134 }
135 index.mutex.Lock()
136 defer index.mutex.Unlock()
137 if index.loaded {
138 return nil
139 }
140 latest, err := index.head(ctx)
141 if err != nil {
142 return err
143 }
144 // latest is read before loading, so a write that commits during the
145 // load is replayed by its writer's catch-up rather than missed.
146 if err := index.loadAll(ctx); err != nil {
147 return err
148 }
149 index.seen, index.loaded = latest, true
150 index.settle()
151 return nil
152}
153
154// head is the event log's newest id.
155func (index *Index) head(ctx context.Context) (int64, error) {
156 var latest int64
157 err := index.store.database.WithContext(ctx).Model(&Event{}).
158 Select("COALESCE(MAX(id), 0)").Scan(&latest).Error
159 if err != nil {
160 return 0, fmt.Errorf("mapa: reading the event log head: %w", err)
161 }
162 return latest, nil
163}
164
165// caughtUp follows the event log. Store.write calls it in the writer's
166// own request, after the transaction, so the work of a write is paid by
167// the person who made it; Watch calls it off-request, for writes another
168// process made. It asks the log's head without a lock and takes the
169// write lock only when the index is behind, so readers wait on real
170// work only. Before the first read there is nothing loaded to keep
171// current, and the load will include it.
172func (index *Index) caughtUp(ctx context.Context) error {
173 latest, err := index.head(ctx)
174 if err != nil {
175 return err
176 }
177 index.mutex.RLock()
178 behind := index.loaded && latest > index.seen
179 index.mutex.RUnlock()
180 if !behind {
181 return nil
182 }
183 index.mutex.Lock()
184 defer index.mutex.Unlock()
185 if latest <= index.seen {
186 return nil // another catch-up got here first
187 }
188 index.catchUps.Add(1)
189 if err := index.follow(ctx, latest); err != nil {
190 return err
191 }
192 index.settle()
193 return nil
194}
195
196// watchEvery is how often Watch looks at the event log's head.
197const watchEvery = time.Second
198
199// Watch catches the index up, off-request, with writes this process did
200// not make: during a zero-downtime swap two processes serve one file
201// for a while, and each must see the other's writes (review M3). It
202// only reads the log; it commits nothing, so it is not one of the
203// timers doctrine §13 rules out. It stops when ctx ends or the database
204// closes.
205func (index *Index) Watch(ctx context.Context, every time.Duration) {
206 ticker := time.NewTicker(every)
207 defer ticker.Stop()
208 for {
209 select {
210 case <-ctx.Done():
211 return
212 case <-ticker.C:
213 }
214 err := index.caughtUp(ctx)
215 if errors.Is(err, sql.ErrConnDone) || closedDatabase(err) {
216 return
217 }
218 if err != nil {
219 index.store.logger().Warn("watching the event log", "err", err)
220 }
221 }
222}
223
224// closedDatabase is the error a query on a closed handle gives.
225func closedDatabase(err error) bool {
226 return err != nil && strings.Contains(err.Error(), "database is closed")
227}
228
229// settle rebuilds what queries read sorted: the dictionaries and the
230// title rows. The caller holds the write lock.
231func (index *Index) settle() {
232 index.teamTerms.settle()
233 for _, part := range index.ownTerms {
234 part.settle()
235 }
236 if index.titlesDirty {
237 index.rebuildTitles()
238 }
239 if index.pending.dirty {
240 index.rebuildPending()
241 }
242}
243
244// follow replays the events past seen, reloading each page they name.
245func (index *Index) follow(ctx context.Context, latest int64) error {
246 var touched []int64
247 err := index.store.database.WithContext(ctx).Model(&Event{}).
248 Where("id > ? AND id <= ? AND object_kind = ?", index.seen, latest,
249 ObjectPage).Distinct().Pluck("object_id", &touched).Error
250 if err != nil {
251 return fmt.Errorf("mapa: reading new events: %w", err)
252 }
253 for _, pageID := range touched {
254 if err := index.reload(ctx, pageID); err != nil {
255 return err
256 }
257 }
258 index.seen = latest
259 return nil
260}
261
262// loadAll rebuilds every derivation from the sealed rows.
263func (index *Index) loadAll(ctx context.Context) error {
264 index.reset()
265 var pages []Page
266 err := index.store.database.WithContext(ctx).Where("gone = ?", false).
267 Find(&pages).Error
268 if err != nil {
269 return fmt.Errorf("mapa: loading pages: %w", err)
270 }
271 aliases, err := index.store.allAliases(ctx)
272 if err != nil {
273 return err
274 }
275 for _, page := range pages {
276 opened, err := index.open(page, aliases[page.ID])
277 if err != nil {
278 return err
279 }
280 index.add(opened)
281 }
282 return nil
283}
284
285// reload re-reads one page: it may have changed, or be gone.
286func (index *Index) reload(ctx context.Context, pageID int64) error {
287 index.remove(pageID)
288 database := index.store.database.WithContext(ctx)
289 var page Page
290 result := database.Where("id = ? AND gone = ?", pageID, false).
291 Limit(1).Find(&page)
292 if result.Error != nil || result.RowsAffected == 0 {
293 return result.Error
294 }
295 aliases, err := index.store.aliases(database, pageID)
296 if err != nil {
297 return err
298 }
299 opened, err := index.open(page, aliases)
300 if err != nil {
301 return err
302 }
303 index.add(opened)
304 return nil
305}
306
307func (index *Index) open(page Page, aliases []AliasView) (*entry, error) {
308 record, err := index.store.OpenPage(page)
309 if err != nil {
310 return nil, err
311 }
312 blocks := markup.Parse(record.Body)
313 opened := &entry{id: page.ID, nonce: page.Nonce, owner: page.OwnerID,
314 revision: page.Revision, kind: page.Kind, rung: page.Rung,
315 created: page.CreatedAt, updated: page.UpdatedAt, record: record,
316 aliases: aliases, blocks: blocks, links: markup.LinksIn(blocks),
317 in: inTarget(page.Kind, page.Rung, blocks)}
318 opened.counts, opened.length = termCounts(searchText(opened))
319 opened.unlinked = make([][]word, len(blocks))
320 for number, block := range blocks {
321 for _, run := range markup.Unlinked(block) {
322 // A boundary between runs is never inside a match.
323 opened.unlinked[number] = append(opened.unlinked[number],
324 append(wordsOf(run), word{fold: "\x00"})...)
325 }
326 }
327 return opened, nil
328}
329