1package store
2
3import (
4 "context"
5 "encoding/json"
6 "errors"
7 "fmt"
8 "io"
9 "log/slog"
10 "runtime"
11 "slices"
12 "sort"
13 "time"
14
15 "github.com/mjl-/bstore"
16
17 "github.com/mjl-/mox/message"
18 "github.com/mjl-/mox/mlog"
19 "github.com/mjl-/mox/moxio"
20)
21
22// Assign a new/incoming message to a thread. Message does not yet have an ID. If
23// this isn't a response, ThreadID should remain 0 (unless this is a message with
24// existing message-id) and the caller must set ThreadID to ID.
25// If the account is still busy upgrading messages with threadids in the background, parents
26// may have a threadid 0. That results in this message getting threadid 0, which
27// will handled by the background upgrade process assigning a threadid when it gets
28// to this message.
29func assignThread(log mlog.Log, tx *bstore.Tx, m *Message, part *message.Part) error {
30 if m.MessageID != "" {
31 // Match against existing different message with same Message-ID.
32 q := bstore.QueryTx[Message](tx)
33 q.FilterNonzero(Message{MessageID: m.MessageID})
34 q.FilterEqual("Expunged", false)
35 q.FilterNotEqual("ID", m.ID)
36 q.FilterNotEqual("ThreadID", int64(0))
37 q.SortAsc("ID")
38 q.Limit(1)
39 em, err := q.Get()
40 if err != nil && err != bstore.ErrAbsent {
41 return fmt.Errorf("looking up existing message with message-id: %v", err)
42 } else if err == nil {
43 assignParent(m, em, true)
44 return nil
45 }
46 }
47
48 h, err := part.Header()
49 if err != nil {
50 log.Errorx("assigning threads: parsing references/in-reply-to headers, not matching by message-id", err, slog.Int64("msgid", m.ID))
51 }
52 messageIDs, err := message.ReferencedIDs(h.Values("References"), h.Values("In-Reply-To"))
53 if err != nil {
54 log.Errorx("assigning threads: parsing references/in-reply-to headers, not matching by message-id", err, slog.Int64("msgid", m.ID))
55 }
56 for i := len(messageIDs) - 1; i >= 0; i-- {
57 messageID := messageIDs[i]
58 if messageID == m.MessageID {
59 continue
60 }
61 tm, _, err := lookupThreadMessage(tx, m.ID, messageID, m.SubjectBase, m.DSN)
62 if err != nil {
63 return fmt.Errorf("looking up thread message for new message: %v", err)
64 } else if tm != nil {
65 assignParent(m, *tm, true)
66 return nil
67 }
68 m.ThreadMissingLink = true
69 }
70 if len(messageIDs) > 0 {
71 return nil
72 }
73
74 var isResp bool
75 if part != nil && part.Envelope != nil {
76 m.SubjectBase, isResp = message.ThreadSubject(part.Envelope.Subject, false)
77 }
78 if !isResp || m.SubjectBase == "" {
79 return nil
80 }
81 m.ThreadMissingLink = true
82 tm, err := lookupThreadMessageSubject(tx, *m, m.SubjectBase)
83 if err != nil {
84 return fmt.Errorf("looking up thread message by subject: %v", err)
85 } else if tm != nil {
86 assignParent(m, *tm, true)
87 }
88 return nil
89}
90
91// assignParent assigns threading fields to m that make it a child of parent message pm.
92// updateSeen indicates if m.Seen should be cleared if pm is thread-muted.
93func assignParent(m *Message, pm Message, updateSeen bool) {
94 if pm.ThreadID == 0 {
95 panic(fmt.Sprintf("assigning message id %d/d%q to parent message id %d/%q which has threadid 0", m.ID, m.MessageID, pm.ID, pm.MessageID))
96 }
97 if m.ID == pm.ID {
98 panic(fmt.Sprintf("trying to make message id %d/%q its own parent", m.ID, m.MessageID))
99 }
100 m.ThreadID = pm.ThreadID
101 // Make sure we don't add cycles.
102 if !slices.Contains(pm.ThreadParentIDs, m.ID) {
103 m.ThreadParentIDs = append([]int64{pm.ID}, pm.ThreadParentIDs...)
104 } else if pm.ID != m.ID {
105 m.ThreadParentIDs = []int64{pm.ID}
106 } else {
107 m.ThreadParentIDs = nil
108 }
109 if m.MessageID != "" && m.MessageID == pm.MessageID {
110 m.ThreadMissingLink = true
111 }
112 m.ThreadMuted = pm.ThreadMuted
113 m.ThreadCollapsed = pm.ThreadCollapsed
114 if updateSeen && m.ThreadMuted {
115 m.Seen = true
116 }
117}
118
119// ResetThreading resets the MessageID and SubjectBase fields for all messages in
120// the account. If clearIDs is true, all Thread* fields are also cleared. Changes
121// are made in transactions of batchSize changes. The total number of updated
122// messages is returned.
123//
124// ModSeq is not changed. Calles should bump the uid validity of the mailboxes
125// to propagate the changes to IMAP clients.
126func (a *Account) ResetThreading(ctx context.Context, log mlog.Log, batchSize int, clearIDs bool) (int, error) {
127 // todo: should this send Change events for ThreadMuted and ThreadCollapsed? worth it?
128
129 var lastID int64
130 total := 0
131 for {
132 n := 0
133
134 prepareMessages := func(in, out chan moxio.Work[Message, Message]) {
135 for {
136 w, ok := <-in
137 if !ok {
138 return
139 }
140
141 m := w.In
142
143 // We have the Message-ID and Subject headers in ParsedBuf. We use a partial part
144 // struct so we don't generate so much garbage for the garbage collector to sift
145 // through.
146 var part struct {
147 Envelope *message.Envelope
148 }
149 if err := json.Unmarshal(m.ParsedBuf, &part); err != nil {
150 log.Errorx("unmarshal json parsedbuf for setting message-id, skipping", err, slog.Int64("msgid", m.ID))
151 } else {
152 m.MessageID = ""
153 if part.Envelope != nil && part.Envelope.MessageID != "" {
154 s, _, err := message.MessageIDCanonical(part.Envelope.MessageID)
155 if err != nil {
156 log.Debugx("parsing message-id, skipping", err, slog.Int64("msgid", m.ID), slog.String("messageid", part.Envelope.MessageID))
157 }
158 m.MessageID = s
159 }
160 if part.Envelope != nil {
161 m.SubjectBase, _ = message.ThreadSubject(part.Envelope.Subject, false)
162 }
163 }
164 w.Out = m
165
166 out <- w
167 }
168 }
169
170 err := a.DB.Write(ctx, func(tx *bstore.Tx) error {
171 processMessage := func(in, m Message) error {
172 if clearIDs {
173 m.ThreadID = 0
174 m.ThreadParentIDs = nil
175 m.ThreadMissingLink = false
176 }
177 return tx.Update(&m)
178 }
179
180 // JSON parsing is relatively heavy, we benefit from multiple goroutines.
181 procs := runtime.GOMAXPROCS(0)
182 wq := moxio.NewWorkQueue[Message, Message](procs, 2*procs, prepareMessages, processMessage)
183
184 q := bstore.QueryTx[Message](tx)
185 q.FilterEqual("Expunged", false)
186 q.FilterGreater("ID", lastID)
187 q.SortAsc("ID")
188 err := q.ForEach(func(m Message) error {
189 // We process in batches so we don't block other operations for a long time.
190 if n >= batchSize {
191 return bstore.StopForEach
192 }
193 // Update starting point for next batch.
194 lastID = m.ID
195
196 n++
197 return wq.Add(m)
198 })
199 if err == nil {
200 err = wq.Finish()
201 }
202 wq.Stop()
203 return err
204 })
205 if err != nil {
206 return total, fmt.Errorf("upgrading account to threads storage, step 1/2: %w", err)
207 }
208 total += n
209 if n == 0 {
210 break
211 }
212 }
213 return total, nil
214}
215
216// AssignThreads assigns thread-related fields to messages with ID >=
217// startMessageID. Changes are committed each batchSize changes if txOpt is nil
218// (i.e. during automatic account upgrade, we don't want to block database access
219// for a long time). If txOpt is not nil, all changes are made in that
220// transaction.
221//
222// When resetting thread assignments, the caller must first clear the existing
223// thread fields.
224//
225// Messages are processed in order of ID, so when added to the account, not
226// necessarily by received/date. Most threaded messages can immediately be matched
227// to their parent message. If not, we keep track of the missing message-id and
228// resolve as soon as we encounter it. At the end, we resolve all remaining
229// messages, they start with a cycle.
230//
231// Does not set Seen flag for muted threads.
232//
233// Progress is written to progressWriter, every 100k messages.
234func (a *Account) AssignThreads(ctx context.Context, log mlog.Log, txOpt *bstore.Tx, startMessageID int64, batchSize int, progressWriter io.Writer) error {
235 // We use a more basic version of the thread-matching algorithm describe in:
236 // ../rfc/5256:443
237 // The algorithm assumes you'll select messages, then group into threads. We normally do
238 // thread-calculation when messages are delivered. Here, we assign threads as soon
239 // as we can, but will queue messages that reference known ancestors and resolve as
240 // soon as we process them. We can handle large number of messages, but not very
241 // quickly because we make lots of database queries.
242
243 type childMsg struct {
244 ID int64 // This message will be fetched and updated with the threading fields once the parent is resolved.
245 MessageID string // Of child message. Once child is resolved, its own children can be resolved too.
246 ThreadMissingLink bool
247 }
248 // Messages that have a References/In-Reply-To that we want to set as parent, but
249 // where the parent doesn't have a ThreadID yet are added to pending. The key is
250 // the normalized MessageID of the parent, and the value is a list of messages that
251 // can get resolved once the parent gets its ThreadID. The kids will get the same
252 // ThreadIDs, and they themselves may be parents to kids, and so on.
253 // For duplicate messages (messages with identical Message-ID), the second
254 // Message-ID to be added to pending is added under its own message-id, so it gets
255 // its original as parent.
256 pending := map[string][]childMsg{}
257
258 // Current tx. If not equal to txOpt, we clean it up before we leave.
259 var tx *bstore.Tx
260 defer func() {
261 if tx != nil && tx != txOpt {
262 err := tx.Rollback()
263 log.Check(err, "rolling back transaction")
264 }
265 }()
266
267 // Set thread-related fields for a single message. Caller must save the message,
268 // only if not an error and not added to the pending list.
269 assign := func(m *Message, references, inReplyTo []string, subject string) (pend bool, rerr error) {
270 if m.MessageID != "" {
271 // Attempt to match against existing different message with same Message-ID that
272 // already has a threadid.
273 // If there are multiple messages for a message-id a future call to assign may use
274 // its threadid, or it may end up in pending and we resolve it when we need to.
275 q := bstore.QueryTx[Message](tx)
276 q.FilterNonzero(Message{MessageID: m.MessageID})
277 q.FilterEqual("Expunged", false)
278 q.FilterLess("ID", m.ID)
279 q.SortAsc("ID")
280 q.Limit(1)
281 em, err := q.Get()
282 if err != nil && err != bstore.ErrAbsent {
283 return false, fmt.Errorf("looking up existing message with message-id: %v", err)
284 } else if err == nil {
285 if em.ThreadID == 0 {
286 pending[em.MessageID] = append(pending[em.MessageID], childMsg{m.ID, m.MessageID, true})
287 return true, nil
288 } else {
289 assignParent(m, em, false)
290 return false, nil
291 }
292 }
293 }
294
295 refids, err := message.ReferencedIDs(references, inReplyTo)
296 if err != nil {
297 log.Errorx("assigning threads: parsing references/in-reply-to headers, not matching by message-id", err, slog.Int64("msgid", m.ID))
298 }
299
300 for i := len(refids) - 1; i >= 0; i-- {
301 messageID := refids[i]
302 if messageID == m.MessageID {
303 continue
304 }
305 tm, exists, err := lookupThreadMessage(tx, m.ID, messageID, m.SubjectBase, m.DSN)
306 if err != nil {
307 return false, fmt.Errorf("lookup up thread by message-id %s for message id %d: %w", messageID, m.ID, err)
308 } else if tm != nil {
309 assignParent(m, *tm, false)
310 return false, nil
311 } else if exists {
312 pending[messageID] = append(pending[messageID], childMsg{m.ID, m.MessageID, i < len(refids)-1})
313 return true, nil
314 }
315 }
316
317 var subjectBase string
318 var isResp bool
319 if subject != "" {
320 subjectBase, isResp = message.ThreadSubject(subject, false)
321 }
322 if len(refids) > 0 || !isResp || subjectBase == "" {
323 m.ThreadID = m.ID
324 m.ThreadMissingLink = len(refids) > 0
325 return false, nil
326 }
327
328 // No references to use. If this is a reply/forward (based on subject), we'll match
329 // against base subject, at most 4 weeks back so we don't match against ancient
330 // messages and 1 day ahead so we can match against delayed deliveries.
331 tm, err := lookupThreadMessageSubject(tx, *m, subjectBase)
332 if err != nil {
333 return false, fmt.Errorf("looking up recent messages by base subject %q: %w", subjectBase, err)
334 } else if tm != nil {
335 m.ThreadID = tm.ThreadID
336 m.ThreadParentIDs = []int64{tm.ThreadID} // Always under root message with subject-match.
337 m.ThreadMissingLink = true
338 m.ThreadMuted = tm.ThreadMuted
339 m.ThreadCollapsed = tm.ThreadCollapsed
340 } else {
341 m.ThreadID = m.ID
342 }
343 return false, nil
344 }
345
346 npendingResolved := 0
347
348 // Resolve pending messages that wait on m.MessageID to be resolved, recursively.
349 var resolvePending func(tm Message, cyclic bool) error
350 resolvePending = func(tm Message, cyclic bool) error {
351 if tm.MessageID == "" {
352 return nil
353 }
354 l := pending[tm.MessageID]
355 delete(pending, tm.MessageID)
356 for _, mi := range l {
357 m := Message{ID: mi.ID}
358 if err := tx.Get(&m); err != nil {
359 return fmt.Errorf("get message %d for resolving pending thread for message-id %s, %d: %w", mi.ID, tm.MessageID, tm.ID, err)
360 }
361 if m.ThreadID != 0 {
362 // ThreadID already set because this is a cyclic message. If we would assign a
363 // parent again, we would create a cycle.
364 if m.MessageID != tm.MessageID && !cyclic {
365 panic(fmt.Sprintf("threadid already set (%d) while handling non-cyclic message id %d/%q and with different message-id %q as parent message id %d", m.ThreadID, m.ID, m.MessageID, tm.MessageID, tm.ID))
366 }
367 continue
368 }
369 assignParent(&m, tm, false)
370 m.ThreadMissingLink = mi.ThreadMissingLink
371 if err := tx.Update(&m); err != nil {
372 return fmt.Errorf("update message %d for resolving pending thread for message-id %s, %d: %w", mi.ID, tm.MessageID, tm.ID, err)
373 }
374 if err := resolvePending(m, cyclic); err != nil {
375 return err
376 }
377 npendingResolved++
378 }
379 return nil
380 }
381
382 // Output of the worker goroutines.
383 type threadPrep struct {
384 references []string
385 inReplyTo []string
386 subject string
387 }
388
389 // Single allocation.
390 threadingFields := [][]byte{
391 []byte("references"),
392 []byte("in-reply-to"),
393 []byte("subject"),
394 }
395
396 // Worker goroutine function. We start with a reasonably large buffer for reading
397 // the header into. And we have scratch space to copy the needed headers into. That
398 // means we normally won't allocate any more buffers.
399 prepareMessages := func(in, out chan moxio.Work[Message, threadPrep]) {
400 headerbuf := make([]byte, 8*1024)
401 scratch := make([]byte, 4*1024)
402 for {
403 w, ok := <-in
404 if !ok {
405 return
406 }
407
408 m := w.In
409 var partialPart struct {
410 HeaderOffset int64
411 BodyOffset int64
412 }
413 if err := json.Unmarshal(m.ParsedBuf, &partialPart); err != nil {
414 w.Err = fmt.Errorf("unmarshal part: %v", err)
415 } else {
416 size := partialPart.BodyOffset - partialPart.HeaderOffset
417 if int(size) > len(headerbuf) {
418 headerbuf = make([]byte, size)
419 }
420 if size > 0 {
421 buf := headerbuf[:int(size)]
422 err := func() error {
423 mr := a.MessageReader(m)
424 defer mr.Close()
425
426 // ReadAt returns whole buffer or error. Single read should be fast.
427 n, err := mr.ReadAt(buf, partialPart.HeaderOffset)
428 if err != nil || n != len(buf) {
429 return fmt.Errorf("read header: %v", err)
430 }
431 return nil
432 }()
433 if err != nil {
434 w.Err = err
435 } else if h, err := message.ParseHeaderFields(buf, scratch, threadingFields); err != nil {
436 w.Err = err
437 } else {
438 w.Out.references = h["References"]
439 w.Out.inReplyTo = h["In-Reply-To"]
440 l := h["Subject"]
441 if len(l) > 0 {
442 w.Out.subject = l[0]
443 }
444 }
445 }
446 }
447
448 out <- w
449 }
450 }
451
452 // Assign threads to messages, possibly in batches.
453 nassigned := 0
454 for {
455 n := 0
456 tx = txOpt
457 if tx == nil {
458 var err error
459 tx, err = a.DB.Begin(ctx, true)
460 if err != nil {
461 return fmt.Errorf("begin transaction: %w", err)
462 }
463 }
464
465 processMessage := func(m Message, prep threadPrep) error {
466 pend, err := assign(&m, prep.references, prep.inReplyTo, prep.subject)
467 if err != nil {
468 return fmt.Errorf("for msgid %d: %w", m.ID, err)
469 } else if pend {
470 return nil
471 }
472 if m.ThreadID == 0 {
473 panic(fmt.Sprintf("no threadid after assign of message id %d/%q", m.ID, m.MessageID))
474 }
475 // Fields have been set, store in database and resolve messages waiting for this MessageID.
476 if slices.Contains(m.ThreadParentIDs, m.ID) {
477 panic(fmt.Sprintf("message id %d/%q contains itself in parent ids %v", m.ID, m.MessageID, m.ThreadParentIDs))
478 }
479 if err := tx.Update(&m); err != nil {
480 return err
481 }
482 if err := resolvePending(m, false); err != nil {
483 return fmt.Errorf("resolving pending message-id: %v", err)
484 }
485 return nil
486 }
487
488 // Use multiple worker goroutines to parse headers from on-disk messages.
489 procs := runtime.GOMAXPROCS(0)
490 wq := moxio.NewWorkQueue[Message, threadPrep](2*procs, 4*procs, prepareMessages, processMessage)
491
492 // We assign threads in order by ID, so messages delivered in between our
493 // transaction will get assigned threads too: they'll have the highest id's.
494 q := bstore.QueryTx[Message](tx)
495 q.FilterGreaterEqual("ID", startMessageID)
496 q.FilterEqual("Expunged", false)
497 q.SortAsc("ID")
498 err := q.ForEach(func(m Message) error {
499 // Batch number of changes, so we give other users of account a change to run.
500 if txOpt == nil && n >= batchSize {
501 return bstore.StopForEach
502 }
503 // Starting point for next batch.
504 startMessageID = m.ID + 1
505 // Don't process again. Can happen when earlier upgrade was aborted.
506 if m.ThreadID != 0 {
507 return nil
508 }
509
510 n++
511 return wq.Add(m)
512 })
513 if err == nil {
514 err = wq.Finish()
515 }
516 wq.Stop()
517
518 if err == nil && txOpt == nil {
519 err = tx.Commit()
520 tx = nil
521 }
522 if err != nil {
523 return fmt.Errorf("assigning threads: %w", err)
524 }
525 if n == 0 {
526 break
527 }
528 nassigned += n
529 if nassigned%100000 == 0 {
530 log.Debug("assigning threads, progress", slog.Int("count", nassigned), slog.Int("unresolved", len(pending)))
531 if _, err := fmt.Fprintf(progressWriter, "assigning threads, progress: %d messages\n", nassigned); err != nil {
532 return fmt.Errorf("writing progress: %v", err)
533 }
534 }
535 }
536 if _, err := fmt.Fprintf(progressWriter, "assigning threads, done: %d messages\n", nassigned); err != nil {
537 return fmt.Errorf("writing progress: %v", err)
538 }
539
540 log.Debug("assigning threads, mostly done, finishing with resolving of cyclic messages", slog.Int("count", nassigned), slog.Int("unresolved", len(pending)))
541
542 if _, err := fmt.Fprintf(progressWriter, "assigning threads, resolving %d cyclic pending message-ids\n", len(pending)); err != nil {
543 return fmt.Errorf("writing progress: %v", err)
544 }
545
546 // Remaining messages in pending have cycles and possibly tails. The cycle is at
547 // the head of the thread. Once we resolve that, the rest of the thread can be
548 // resolved too. Ignoring self-references (duplicate messages), there can only be
549 // one cycle, and it is at the head. So we look for cycles, ignoring
550 // self-references, and resolve a message as soon as we see the cycle.
551
552 parent := map[string]string{} // Child Message-ID pointing to the parent Message-ID, excluding self-references.
553 pendlist := []string{}
554 for pmsgid, l := range pending {
555 pendlist = append(pendlist, pmsgid)
556 for _, k := range l {
557 if k.MessageID == pmsgid {
558 // No self-references for duplicate messages.
559 continue
560 }
561 if _, ok := parent[k.MessageID]; !ok {
562 parent[k.MessageID] = pmsgid
563 }
564 // else, this message should be resolved by following pending.
565 }
566 }
567 sort.Strings(pendlist)
568
569 tx = txOpt
570 if tx == nil {
571 var err error
572 tx, err = a.DB.Begin(ctx, true)
573 if err != nil {
574 return fmt.Errorf("begin transaction: %w", err)
575 }
576 }
577
578 // We walk through all messages of pendlist, but some will already have been
579 // resolved by the time we get to them.
580 done := map[string]bool{}
581 for _, msgid := range pendlist {
582 if done[msgid] {
583 continue
584 }
585
586 // We walk up to parent, until we see a message-id we've already seen, a cycle.
587 seen := map[string]bool{}
588 for {
589 pmsgid, ok := parent[msgid]
590 if !ok {
591 panic(fmt.Sprintf("missing parent message-id %q, not a cycle?", msgid))
592 }
593 if !seen[pmsgid] {
594 seen[pmsgid] = true
595 msgid = pmsgid
596 continue
597 }
598
599 // Cycle detected. Make this message-id the thread root.
600 q := bstore.QueryTx[Message](tx)
601 q.FilterNonzero(Message{MessageID: msgid})
602 q.FilterEqual("ThreadID", int64(0))
603 q.FilterEqual("Expunged", false)
604 q.SortAsc("ID")
605 l, err := q.List()
606 if err == nil && len(l) == 0 {
607 err = errors.New("no messages")
608 }
609 if err != nil {
610 return fmt.Errorf("list message by message-id for cyclic thread root: %v", err)
611 }
612 for i, m := range l {
613 m.ThreadID = l[0].ID
614 m.ThreadMissingLink = true
615 if i == 0 {
616 m.ThreadParentIDs = nil
617 l[0] = m // For resolvePending below.
618 } else {
619 assignParent(&m, l[0], false)
620 }
621 if slices.Contains(m.ThreadParentIDs, m.ID) {
622 panic(fmt.Sprintf("message id %d/%q contains itself in parents %v", m.ID, m.MessageID, m.ThreadParentIDs))
623 }
624 if err := tx.Update(&m); err != nil {
625 return fmt.Errorf("assigning threadid to cyclic thread root: %v", err)
626 }
627 }
628
629 // Mark all children as done so we don't process these messages again.
630 walk := map[string]struct{}{msgid: {}}
631 for len(walk) > 0 {
632 for msgid := range walk {
633 delete(walk, msgid)
634 if done[msgid] {
635 continue
636 }
637 done[msgid] = true
638 for _, mi := range pending[msgid] {
639 if !done[mi.MessageID] {
640 walk[mi.MessageID] = struct{}{}
641 }
642 }
643 }
644 }
645
646 // Resolve all messages in this thread.
647 if err := resolvePending(l[0], true); err != nil {
648 return fmt.Errorf("resolving cyclic children of cyclic thread root: %v", err)
649 }
650
651 break
652 }
653 }
654
655 // Check that there are no more messages without threadid.
656 q := bstore.QueryTx[Message](tx)
657 q.FilterEqual("ThreadID", int64(0))
658 q.FilterEqual("Expunged", false)
659 l, err := q.List()
660 if err == nil && len(l) > 0 {
661 err = errors.New("found messages without threadid")
662 }
663 if err != nil {
664 return fmt.Errorf("listing messages without threadid: %v", err)
665 }
666
667 if txOpt == nil {
668 err := tx.Commit()
669 tx = nil
670 if err != nil {
671 return fmt.Errorf("commit resolving cyclic thread roots: %v", err)
672 }
673 }
674 return nil
675}
676
677// lookupThreadMessage tries to find the parent message with messageID, that must
678// have a matching subjectBase (unless it is a DSN).
679//
680// If the message isn't present (with a valid thread id), a nil message and nil
681// error is returned. The bool return value indicates if a message with the
682// message-id exists at all.
683func lookupThreadMessage(tx *bstore.Tx, mID int64, messageID, subjectBase string, isDSN bool) (*Message, bool, error) {
684 q := bstore.QueryTx[Message](tx)
685 q.FilterNonzero(Message{MessageID: messageID})
686 if !isDSN {
687 q.FilterEqual("SubjectBase", subjectBase)
688 }
689 q.FilterEqual("Expunged", false)
690 q.FilterNotEqual("ID", mID)
691 q.SortAsc("ID")
692 l, err := q.List()
693 if err != nil {
694 return nil, false, fmt.Errorf("message-id %s: %w", messageID, err)
695 }
696 exists := len(l) > 0
697 for _, tm := range l {
698 if tm.ThreadID != 0 {
699 return &tm, true, nil
700 }
701 }
702 return nil, exists, nil
703}
704
705// lookupThreadMessageSubject looks up a parent/ancestor message for the message
706// thread based on a matching subject. The message must have been delivered to the same mailbox originally.
707//
708// If no message (with a threadid) is found a nil message and nil error is returned.
709func lookupThreadMessageSubject(tx *bstore.Tx, m Message, subjectBase string) (*Message, error) {
710 q := bstore.QueryTx[Message](tx)
711 q.FilterGreater("Received", m.Received.Add(-4*7*24*time.Hour))
712 q.FilterLess("Received", m.Received.Add(1*24*time.Hour))
713 q.FilterNonzero(Message{SubjectBase: subjectBase, MailboxOrigID: m.MailboxOrigID})
714 q.FilterEqual("Expunged", false)
715 q.FilterNotEqual("ID", m.ID)
716 q.FilterNotEqual("ThreadID", int64(0))
717 q.SortDesc("Received")
718 q.Limit(1)
719 tm, err := q.Get()
720 if err == bstore.ErrAbsent {
721 return nil, nil
722 } else if err != nil {
723 return nil, err
724 }
725 return &tm, nil
726}
727
728func upgradeThreads(ctx context.Context, log mlog.Log, acc *Account, up *Upgrade) error {
729 log = log.With(slog.String("account", acc.Name))
730
731 if up.Threads == 0 {
732 // Step 1 in the threads upgrade is storing the canonicalized Message-ID for each
733 // message and the base subject for thread matching. This allows efficient thread
734 // lookup in the second step.
735
736 log.Info("upgrading account for threading, step 1/2: updating all messages with message-id and base subject")
737 t0 := time.Now()
738
739 const batchSize = 10000
740 total, err := acc.ResetThreading(ctx, log, batchSize, true)
741 if err != nil {
742 return fmt.Errorf("resetting message threading fields: %v", err)
743 }
744
745 up.Threads = 1
746 if err := acc.DB.Update(ctx, up); err != nil {
747 up.Threads = 0
748 return fmt.Errorf("saving upgrade process while upgrading account to threads storage, step 1/2: %w", err)
749 }
750 log.Info("upgrading account for threading, step 1/2: completed", slog.Duration("duration", time.Since(t0)), slog.Int("messages", total))
751 }
752
753 if up.Threads == 1 {
754 // Step 2 of the upgrade is going through all messages and assigning threadid's.
755 // Lookup of messageid and base subject is now fast through indexed database
756 // access.
757
758 log.Info("upgrading account for threading, step 2/2: matching messages to threads")
759 t0 := time.Now()
760
761 const batchSize = 10000
762 if err := acc.AssignThreads(ctx, log, nil, 1, batchSize, io.Discard); err != nil {
763 return fmt.Errorf("upgrading to threads storage, step 2/2: %w", err)
764 }
765 up.Threads = 2
766 if err := acc.DB.Update(ctx, up); err != nil {
767 up.Threads = 1
768 return fmt.Errorf("saving upgrade process for thread storage, step 2/2: %w", err)
769 }
770 log.Info("upgrading account for threading, step 2/2: completed", slog.Duration("duration", time.Since(t0)))
771 }
772
773 // Note: Not bumping uidvalidity or setting modseq. Clients haven't been able to
774 // use threadid's before, so there is nothing to be out of date.
775
776 return nil
777}
778