--- a/pkg/connector/config.go +++ b/pkg/connector/config.go @@ -41,6 +41,7 @@ type ThreadBackfillConfig struct { BatchCount int `yaml:"batch_count"` BatchDelay time.Duration `yaml:"batch_delay"` + DaysLimit int `yaml:"days_limit"` } type umConfig Config @@ -80,6 +81,7 @@ helper.Copy(up.Bool, "log_redacted_bloks_payloads") helper.Copy(up.Int, "thread_backfill", "batch_count") helper.Copy(up.Str|up.Int, "thread_backfill", "batch_delay") + helper.Copy(up.Int, "thread_backfill", "days_limit") } func (m *MetaConnector) GetConfig() (string, any, up.Upgrader) { --- a/pkg/connector/events.go +++ b/pkg/connector/events.go @@ -559,6 +559,8 @@ UncertainReceiver bool filled bool + + xessengerNewMessageMs int64 } var ( @@ -581,7 +583,9 @@ } func (r *FBChatResync) ShouldCreatePortal() bool { - if r.Raw != nil && r.Raw.FolderName == folderSpam { + if r.xessengerTooOld() { + return false + } else if r.Raw != nil && r.Raw.FolderName == folderSpam { return false } else if r.Update != nil && r.Update.FolderName == folderSpam { return false --- a/pkg/connector/example-config.yaml +++ b/pkg/connector/example-config.yaml @@ -43,3 +43,7 @@ batch_count: -1 # Delay between fetching each batch of threads (to avoid rate limiting) batch_delay: 2s + # Don't create portals for threads whose last activity is older than this many days, and stop + # fetching batches once the threads reach that far back. They get a portal when a new message arrives. + # 0 to disable. + days_limit: 0 --- a/pkg/connector/handlemeta.go +++ b/pkg/connector/handlemeta.go @@ -363,6 +363,7 @@ collectPortalEvents(params, maps.Values(upsert), m.handleUpsertMessages, &innerQueue) collectPortalEvents(params, tbl.LSUpdateExistingMessageRange, m.handleUpdateExistingMessageRange, &innerQueue) + xessengerNoteNewMessages(params, insert) for _, resync := range threadResyncs { innerQueue = append(innerQueue, resync) } --- a/pkg/connector/threadbackfill.go +++ b/pkg/connector/threadbackfill.go @@ -36,6 +36,10 @@ for { if ctx.Err() != nil { return ctx.Err() + } else if m.xessengerThreadsReachedDaysLimit() { + log.Info().Int("batches_processed", batchCount).Msg("Thread backfill complete - reached days_limit") + m.markBackfillComplete(ctx, m.LoginMeta) + return nil } // Fetch next batch of threads, TODO: other SyncGroups? --- /dev/null +++ b/pkg/connector/xessenger_thread_scope.go @@ -0,0 +1,43 @@ +package connector + +import ( + "time" + + "go.mau.fi/mautrix-meta/pkg/messagix/table" +) + +// Xessenger: thread_backfill.days_limit. A thread row makes no room for a thread whose last activity +// is older, and the thread backfill stops once the inbox it has loaded reaches that far back. Such a +// thread gets its room when a new message arrives: from the thread-exists check that comes with the +// message, or from its thread row, which then counts the message as activity. Rooms that exist are +// untouched. Zero keeps upstream's behaviour. + +// xessengerTooOld is consulted only for a thread without a room. A thread row without an activity +// time is let through, as upstream does. +func (r *FBChatResync) xessengerTooOld() bool { + if r.m == nil || r.m.Main == nil { + return false + } + activity := max(r.getLastActivityTimestampMs(), r.xessengerNewMessageMs) + return xessengerOlderThan(activity, r.m.Main.Config.ThreadBackfill.DaysLimit, time.Now()) +} + +// xessengerNoteNewMessages gives each thread row the time of a live message that came in the same +// batch: the row is what makes the room the message goes into, and it may still carry the activity +// time from before the message. +func xessengerNoteNewMessages(p threadMaps, messages []*table.WrappedMessage) { + for _, msg := range messages { + if resync, ok := p.syncs[p.MapWhatsAppThreadKey(msg.GetThreadKey())]; ok && msg.TimestampMs > resync.xessengerNewMessageMs { + resync.xessengerNewMessageMs = msg.TimestampMs + } + } +} + +func (m *MetaClient) xessengerThreadsReachedDaysLimit() bool { + keyStore := m.Client.GetSyncGroupKeyStore(1) + return keyStore != nil && xessengerOlderThan(keyStore.MinLastActivityTimestampMs, m.Main.Config.ThreadBackfill.DaysLimit, time.Now()) +} + +func xessengerOlderThan(activityMs int64, days int, now time.Time) bool { + return days > 0 && activityMs > 0 && time.UnixMilli(activityMs).Before(now.AddDate(0, 0, -days)) +} --- /dev/null +++ b/pkg/connector/xessenger_thread_scope_test.go @@ -0,0 +1,83 @@ +package connector + +import ( + "os" + "path/filepath" + "testing" + "time" + + up "go.mau.fi/util/configupgrade" + "gopkg.in/yaml.v3" + + "go.mau.fi/mautrix-meta/pkg/messagix/table" +) + +func TestXessengerThreadRowsMakeRoomsOnlyForRecentThreads(t *testing.T) { + now := time.Now() + client := &MetaClient{Main: &MetaConnector{Config: Config{ThreadBackfill: ThreadBackfillConfig{DaysLimit: 90}}}} + ms := func(t time.Time) int64 { return t.UnixMilli() } + inbox := func(activity int64) *table.LSDeleteThenInsertThread { + return &table.LSDeleteThenInsertThread{ThreadKey: 7, FolderName: folderInbox, LastActivityTimestampMs: activity} + } + for _, c := range []struct { + name string + resync *FBChatResync + create bool + }{ + {"inbox thread active yesterday", &FBChatResync{Raw: inbox(ms(now.AddDate(0, 0, -1))), m: client}, true}, + {"inbox thread quiet since 2018", &FBChatResync{Raw: inbox(ms(time.Date(2018, 5, 1, 0, 0, 0, 0, time.UTC))), m: client}, false}, + {"updated thread quiet for 91 days", &FBChatResync{Update: &table.LSUpdateOrInsertThread{FolderName: folderInbox, LastActivityTimestampMs: ms(now.AddDate(0, 0, -91))}, m: client}, false}, + {"thread row without an activity time", &FBChatResync{Raw: inbox(0), m: client}, true}, + {"recent spam stays out as upstream", &FBChatResync{Raw: &table.LSDeleteThenInsertThread{FolderName: folderSpam, LastActivityTimestampMs: ms(now)}, m: client}, false}, + {"no limit", &FBChatResync{Raw: inbox(ms(now.AddDate(-8, 0, 0))), m: &MetaClient{Main: &MetaConnector{}}}, true}, + } { + if got := c.resync.ShouldCreatePortal(); got != c.create { + t.Errorf("%s: create room %v, want %v", c.name, got, c.create) + } + } + + // A new message in a quiet thread makes its room even when the thread row beside it still has the + // old activity time; a message for another thread doesn't. + quiet := &FBChatResync{Raw: inbox(ms(now.AddDate(-2, 0, 0))), m: client} + other := &FBChatResync{Raw: &table.LSDeleteThenInsertThread{ThreadKey: 8, FolderName: folderInbox, LastActivityTimestampMs: ms(now.AddDate(-2, 0, 0))}, m: client} + params := threadMaps{syncs: map[int64]*FBChatResync{7: quiet, 8: other}} + xessengerNoteNewMessages(params, []*table.WrappedMessage{ + {LSInsertMessage: &table.LSInsertMessage{ThreadKey: 7, TimestampMs: ms(now)}}, + {LSInsertMessage: &table.LSInsertMessage{ThreadKey: 9, TimestampMs: ms(now)}}, + }) + if !quiet.ShouldCreatePortal() || other.ShouldCreatePortal() { + t.Fatal("a new message decided the wrong thread's room") + } + + at := time.Date(2026, 11, 13, 0, 0, 0, 0, time.UTC) + if xessengerOlderThan(ms(at.AddDate(0, 0, -90)), 90, at) || !xessengerOlderThan(ms(at.AddDate(0, 0, -90))-1, 90, at) { + t.Fatal("older means more than 90 days before now") + } + // The thread backfill reads the loaded inbox's position; without a connection there is none. + if client.xessengerThreadsReachedDaysLimit() { + t.Fatal("no position stopped the thread backfill") + } +} + +func TestXessengerConfigKeepsThreadBackfillDaysLimit(t *testing.T) { + example, _, upgrader := (&MetaConnector{}).GetConfig() + path := filepath.Join(t.TempDir(), "config.yaml") + if err := os.WriteFile(path, []byte("thread_backfill:\n batch_count: 10\n days_limit: 90\n"), 0o600); err != nil { + t.Fatal(err) + } + // The bridge upgrades its config on every start, dropping any key the example config lacks. + upgraded, _, err := up.Do(path, false, up.MergeUpgraders(example, upgrader)) + if err != nil { + t.Fatal(err) + } + var config, defaults Config + if err = yaml.Unmarshal(upgraded, &config); err != nil { + t.Fatal(err) + } + if config.ThreadBackfill.BatchCount != 10 || config.ThreadBackfill.DaysLimit != 90 { + t.Fatalf("thread_backfill after the config upgrade: %+v", config.ThreadBackfill) + } + if err = yaml.Unmarshal([]byte(example), &defaults); err != nil || defaults.ThreadBackfill.DaysLimit != 0 { + t.Fatalf("example days_limit = %d (%v), want 0 for upstream's behaviour", defaults.ThreadBackfill.DaysLimit, err) + } +}