oficina / memoria Public

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

Plain git — no account needed to clone.

Download

Download this file

1package memoria
2
3import (
4 "context"
5 "errors"
6 "log/slog"
7 "sync"
8 "time"
9
10 "gorm.io/gorm"
11
12 "amadan.net/oficina/memoria/internal/memoria/chunk"
13 "amadan.net/oficina/memoria/internal/memoria/notion"
14 "amadan.net/oficina/memoria/internal/memoria/seal"
15)
16
17// SourceClient is what a sync needs from a source. An interface so the
18// loop can be driven against a fake without the app package importing an
19// HTTP client — which the network gate forbids it anyway.
20type SourceClient interface {
21 // Roots returns the true roots and, separately, the orphans —
22 // results whose parent search did not return. See notion.Roots.
23 Roots(ctx context.Context) (roots, orphans []notion.Ref, err error)
24 Fetch(ctx context.Context, ref notion.Ref) (*notion.Content, error)
25}
26
27// Syncer runs imports.
28type Syncer struct {
29 store *Store
30 logger *slog.Logger
31 // dial builds a client from a token. Swapped in tests.
32 dial func(token string) (SourceClient, error)
33}
34
35// NewSyncer wires a syncer against the real Notion API.
36func NewSyncer(store *Store, logger *slog.Logger) *Syncer {
37 return &Syncer{store: store, logger: logger, dial: func(token string) (SourceClient, error) {
38 return notion.New(token)
39 }}
40}
41
42// Run imports everything reachable from the connector's roots.
43//
44// ONE PASS, not the two phases an earlier design specified. With
45// traversal, enumeration and extraction are the same API call — fetching
46// a page returns its body AND the child pages beneath it — so separating
47// them would double every request against a limit of three per second.
48// The ledger is still written per page, so the ingest work already done
49// survives an interruption; what a resumed run repeats is the traversal,
50// because a page's children cannot be discovered without asking for them
51// and a child's own edits do not change its parent's edit time.
52//
53// Errors divide in two, and the division is load-bearing:
54//
55// - A traversal failure below a page (rate limit exhausted, a broken
56// cursor, an unreadable body) is FATAL. It means the pages beneath
57// that point were never enumerated, and a run that continued would
58// report "done" while missing a whole subtree — an absence produced
59// by a failure, which is the shape this codebase ranks worst.
60// - A single page that has gone (404 between enumeration and fetch) is
61// recorded against that page and the run carries on. One placeholder
62// must not block an import, but it must not vanish either.
63func (s *Syncer) Run(ctx context.Context, connectorID, runID int64) {
64 token, err := s.store.ConnectorToken(ctx, "notion")
65 if err != nil {
66 s.fail(ctx, runID, "unauthorized")
67 return
68 }
69 client, err := s.dial(token)
70 if err != nil {
71 s.fail(ctx, runID, "unauthorized")
72 return
73 }
74 s.RunWith(ctx, client, connectorID, runID)
75}
76
77// runStats is the live count of what a run has done.
78//
79// Guarded, because the heartbeat goroutine reads it while the walk
80// writes it — and it is read for a reason: an earlier version wrote the
81// counters only at the very end, so a thirty-minute import rendered
82// "0 so far" for its whole duration. A count maintained nowhere and
83// displayed as zero is this codebase's second broken rule, on the status
84// page written to honour it.
85type runStats struct {
86 mu sync.Mutex
87 fetched, skipped, empty, failed, unread, seen int
88}
89
90func (r *runStats) add(f func(*runStats)) {
91 r.mu.Lock()
92 defer r.mu.Unlock()
93 f(r)
94}
95
96func (r *runStats) snapshot() map[string]any {
97 r.mu.Lock()
98 defer r.mu.Unlock()
99 return map[string]any{
100 "fetched": r.fetched, "skipped": r.skipped, "empty": r.empty,
101 "failed_pages": r.failed, "unread_blocks": r.unread,
102 }
103}
104
105// beatEvery is how often a run says it is still alive AND publishes its
106// counters. A DURATION, not a page count: pages take wildly different
107// times — one request per nested block, each paced at 350ms, plus an
108// honoured Retry-After — so "every 25 pages" could exceed the staleness
109// window while the run was perfectly healthy. StartRun would then reclaim
110// a LIVE run and start a second goroutine on the same ledger. Found by a
111// code review.
112const beatEvery = 20 * time.Second
113
114// startBeat publishes the heartbeat and the counters until stopped.
115func (s *Syncer) startBeat(ctx context.Context, runID int64, st *runStats) func() {
116 done := make(chan struct{})
117 go func() {
118 t := time.NewTicker(beatEvery)
119 defer t.Stop()
120 for {
121 select {
122 case <-done:
123 return
124 case <-t.C:
125 patch := st.snapshot()
126 patch["heartbeat"] = time.Now().UTC()
127 if err := s.store.UpdateRun(ctx, runID, patch); err != nil {
128 s.logger.Error("sync heartbeat", "run", runID, "err", err)
129 }
130 }
131 }
132 }()
133 return func() { close(done) }
134}
135
136// RunWith is Run against a supplied client.
137func (s *Syncer) RunWith(ctx context.Context, client SourceClient, connectorID, runID int64) {
138 // The run is the team's import, started by an owner and running on
139 // for minutes: its writes are not that owner's, and are not bound to
140 // the lease of the request that started it (team_guard.go).
141 ctx = systemWrite(ctx)
142 roots, orphans, err := client.Roots(ctx)
143 if err != nil {
144 s.fail(ctx, runID, string(notion.CodeOf(err)))
145 return
146 }
147 if err := s.store.UpdateRun(ctx, runID, map[string]any{
148 "roots": len(roots), "state": RunFetching,
149 }); err != nil {
150 s.fail(ctx, runID, "database")
151 return
152 }
153
154 st := &runStats{}
155 stop := s.startBeat(ctx, runID, st)
156 defer stop()
157
158 visited := map[string]bool{}
159
160 // The real tree first, so every page that HAS an ancestor is reached
161 // through it and inherits the right path.
162 if !s.walk(ctx, client, connectorID, runID, roots, visited, st) {
163 return
164 }
165 // Then the orphans — results whose parent search did not return, most
166 // often a page nested inside a toggle, whose parent is a block. They
167 // go last and skip anything already visited, so an orphan can never
168 // claim a page the traversal would have given real ancestry to.
169 if !s.walk(ctx, client, connectorID, runID, orphans, visited, st) {
170 return
171 }
172
173 now := time.Now().UTC()
174 patch := st.snapshot()
175 st.mu.Lock()
176 patch["total"] = st.seen
177 st.mu.Unlock()
178 patch["state"] = RunDone
179 patch["finished_at"] = now
180 patch["heartbeat"] = now
181 if err := s.store.UpdateRun(ctx, runID, patch); err != nil {
182 s.logger.Error("sync finish", "run", runID, "err", err)
183 }
184 // Counts only. No title, no path, no page id — AGENTS.md's rule, and
185 // the reason this line carries nothing that came from the workspace.
186 s.logger.Info("sync finished", "run", runID, "pages", patch["total"],
187 "fetched", patch["fetched"], "skipped", patch["skipped"],
188 "empty", patch["empty"], "failed", patch["failed_pages"],
189 "unread_blocks", patch["unread_blocks"])
190}
191
192// walk breadth-first from seeds. It reports false when the run has
193// failed, having already marked it.
194func (s *Syncer) walk(ctx context.Context, client SourceClient, connectorID, runID int64,
195 seeds []notion.Ref, visited map[string]bool, st *runStats) bool {
196
197 queue := append([]notion.Ref{}, seeds...)
198 for len(queue) > 0 {
199 ref := queue[0]
200 queue = queue[1:]
201 if visited[ref.ID] {
202 continue
203 }
204 visited[ref.ID] = true
205 st.add(func(r *runStats) { r.seen++ })
206
207 // A data source is a CONTAINER, not a document. It gets no ledger
208 // row: one there would sit "pending" forever, be counted in the
209 // total, and be counted as "already up to date" on every later
210 // run — so the page said "1 of 2 imported" permanently.
211 container := ref.Kind == notion.KindDataSource
212 if !container {
213 // Record the coordinate BEFORE fetching, so a page that then
214 // fails to read has somewhere to be named rather than being
215 // absent.
216 if err := s.store.SeeSourcePage(ctx, connectorID, ref.ID, ref.Title, ref.Path, ref.EditedTime); err != nil {
217 s.logger.Error("sync ledger write", "run", runID, "err", err)
218 s.fail(ctx, runID, "database")
219 return false
220 }
221 }
222
223 content, err := client.Fetch(ctx, ref)
224 if err != nil {
225 if gone(err) {
226 st.add(func(r *runStats) { r.failed++ })
227 if !container {
228 s.markGone(ctx, connectorID, ref, string(notion.CodeOf(err)))
229 }
230 continue
231 }
232 // Not survivable: the subtree below here was never seen.
233 s.fail(ctx, runID, string(notion.CodeOf(err)))
234 return false
235 }
236 queue = append(queue, content.Children...)
237 st.add(func(r *runStats) { r.unread += content.UnreadBlocks })
238
239 if container {
240 continue
241 }
242
243 state, docID, err := s.ingest(ctx, connectorID, ref, content)
244 if err != nil {
245 st.add(func(r *runStats) { r.failed++ })
246 s.markGone(ctx, connectorID, ref, "extract_failed")
247 continue
248 }
249 switch state {
250 case PageEmpty:
251 st.add(func(r *runStats) { r.empty++ })
252 case "":
253 st.add(func(r *runStats) { r.skipped++ })
254 continue
255 default:
256 st.add(func(r *runStats) { r.fetched++ })
257 }
258 s.markByPage(ctx, connectorID, ref, state, "", docID, ref.EditedTime)
259 }
260 return true
261}
262
263// ingest stores one page, or reports that it did not need storing.
264//
265// Returns "" when the page was already up to date. A data source is a
266// container rather than a document and is never stored.
267func (s *Syncer) ingest(ctx context.Context, connectorID int64, ref notion.Ref, content *notion.Content) (string, int64, error) {
268 if ref.Kind == notion.KindDataSource {
269 return "", 0, nil
270 }
271 upToDate, err := s.upToDate(ctx, connectorID, ref)
272 if err != nil {
273 return "", 0, err
274 }
275 if upToDate {
276 return "", 0, nil
277 }
278 id, err := s.store.Ingest(ctx, IngestSpec{
279 Source: "notion",
280 Key: ref.ID,
281 Title: ref.Title,
282 Body: content.Markdown,
283 Path: ref.Path,
284 // On, because an empty page is a fact about the source. See
285 // IngestSpec.AllowTitleOnly.
286 AllowTitleOnly: true,
287 })
288 if err != nil {
289 // ErrIndexLag means the row COMMITTED and only the in-memory
290 // index is behind. The document exists, is in the list, and comes
291 // back at the next rebuild, which is every boot. Recording that
292 // as a failure — and wiping the id — would be telling someone a
293 // document is missing when it is right there.
294 if errors.Is(err, ErrIndexLag) {
295 s.logger.Error("index refresh failed after commit", "source", "notion", "err", err)
296 if content.Markdown == "" {
297 return PageEmpty, id, nil
298 }
299 return PageFetched, id, nil
300 }
301 return "", 0, err
302 }
303 if content.Markdown == "" {
304 return PageEmpty, id, nil
305 }
306 return PageFetched, id, nil
307}
308
309// upToDate reports whether the ledger already holds this page at this
310// edit time AND this ancestry.
311//
312// Both, because an ancestor rename moves the ancestry without moving the
313// page's own edit time — so a check on the edit time alone leaves every
314// descendant of a renamed page stale forever, with nothing upstream ever
315// signalling it.
316func (s *Syncer) upToDate(ctx context.Context, connectorID int64, ref notion.Ref) (bool, error) {
317 rows, err := s.store.pageRow(ctx, connectorID, ref.ID)
318 if err != nil || rows == nil {
319 return false, err
320 }
321 if rows.State != PageFetched && rows.State != PageEmpty {
322 return false, nil
323 }
324 if rows.IngestedEdited != ref.EditedTime {
325 return false, nil
326 }
327 want, err := s.store.pathPrint(ref.Path, ref.Title)
328 if err != nil {
329 return false, err
330 }
331 return rows.IngestedPath == want, nil
332}
333
334// markGone records a failure WITHOUT erasing what memoria already holds.
335//
336// An earlier version routed failures through markByPage with a zero
337// document id and an empty edit time, so a page that had imported fine
338// and then 404'd on a later run had its record wiped: "Imported" dropped,
339// and the next run had to fetch and re-ingest a document that was never
340// gone. Found by a code review.
341func (s *Syncer) markGone(ctx context.Context, connectorID int64, ref notion.Ref, code string) {
342 row, err := s.store.pageRow(ctx, connectorID, ref.ID)
343 if err != nil {
344 s.logger.Error("sync read ledger row", "err", err)
345 return
346 }
347 if row == nil {
348 return
349 }
350 // Keep document_id, ingested_edited and ingested_path exactly as they
351 // were; only the state and the code move.
352 if err := s.store.MarkPage(ctx, row.ID, PageFailed, code,
353 row.DocumentID, row.IngestedEdited, row.IngestedPath); err != nil {
354 s.logger.Error("sync mark page", "err", err)
355 }
356}
357
358func (s *Syncer) markByPage(ctx context.Context, connectorID int64, ref notion.Ref, state, code string, docID int64, edited string) {
359 row, err := s.store.pageRow(ctx, connectorID, ref.ID)
360 if err != nil {
361 s.logger.Error("sync read ledger row", "err", err)
362 return
363 }
364 if row == nil {
365 return
366 }
367 print, err := s.store.pathPrint(ref.Path, ref.Title)
368 if err != nil {
369 s.logger.Error("sync path print", "err", err)
370 return
371 }
372 if edited == "" {
373 print = ""
374 }
375 if err := s.store.MarkPage(ctx, row.ID, state, code, docID, edited, print); err != nil {
376 s.logger.Error("sync mark page", "err", err)
377 }
378}
379
380func (s *Syncer) fail(ctx context.Context, runID int64, code string) {
381 now := time.Now().UTC()
382 if err := s.store.UpdateRun(ctx, runID, map[string]any{
383 "state": RunFailed, "error_code": code, "finished_at": now,
384 }); err != nil {
385 s.logger.Error("sync fail", "run", runID, "err", err)
386 }
387 s.logger.Error("sync failed", "run", runID, "code", code)
388}
389
390func asNotionErr(err error, target **notion.Error) bool { return errors.As(err, target) }
391
392// gone reports whether an error is about one page rather than about the
393// traversal. Only a 404 qualifies: everything else means we do not know
394// what lies below, and continuing would report a complete import.
395func gone(err error) bool {
396 var e *notion.Error
397 if !asNotionErr(err, &e) {
398 return false
399 }
400 return e.Status == 404
401}
402
403// pageRow reads one ledger row by coordinate.
404func (s *Store) pageRow(ctx context.Context, connectorID int64, pageID string) (*SourcePage, error) {
405 print, err := s.sealer.Fingerprint(seal.PurposeCoordinate, []byte("page\x00"+pageID))
406 if err != nil {
407 return nil, err
408 }
409 var row SourcePage
410 res := s.db.G.WithContext(ctx).Where("connector_id = ? AND page_print = ?", connectorID, print).First(&row)
411 if res.Error != nil {
412 // NOT-FOUND is not an error; anything else is. This returned
413 // (nil, nil) for both, so a database failure looked exactly like
414 // "memoria has never seen this page" — the caller then skipped
415 // its mark silently and the ledger under-reported with nothing
416 // logged. The plausible-empty-result shape, in a helper.
417 if errors.Is(res.Error, gorm.ErrRecordNotFound) {
418 return nil, nil
419 }
420 return nil, res.Error
421 }
422 return &row, nil
423}
424
425// pathPrint is the keyed fingerprint of an ancestry plus a title, so a
426// move or a rename is detectable without opening the row.
427func (s *Store) pathPrint(path []string, title string) (string, error) {
428 pathStr := chunk.Chunk{Path: path}.PathString()
429 return s.sealer.Fingerprint(seal.PurposePath, []byte("path\x00"+pathStr+"\x00"+title))
430}
431