--- a/pkg/igconnector/chatsync.go +++ b/pkg/igconnector/chatsync.go @@ -47,7 +47,7 @@ if err != nil { zerolog.Ctx(ctx).Err(err).Msg("Failed to save thread mappings") } - events = append(events, ic.wrapChatResync(node.Node.AsIGDirectThread, false)) + events = append(events, ic.xessengerInboxResync(node.Node.AsIGDirectThread)) } if retryCtx.Err() != nil { done() @@ -70,8 +70,8 @@ return } if !ic.LoginMeta.BackfillCompleted && !ic.Main.Bridge.Background { - if !mailbox.ThreadsByFolder.PageInfo.HasNextPage { - zerolog.Ctx(ctx).Info().Msg("Only one page in inbox, marking backfill as completed") + if _, more := ic.xessengerNextPage(mailbox.ThreadsByFolder); !more { + zerolog.Ctx(ctx).Info().Msg("Only one page in inbox or it reached days_limit, marking backfill as completed") ic.LoginMeta.BackfillCompleted = true err := ic.UserLogin.Save(ctx) if err != nil { @@ -113,7 +113,7 @@ if err != nil { return fmt.Errorf("failed to save thread mappings: %w", err) } - res := ic.UserLogin.QueueRemoteEvent(ic.wrapChatResync(thread, false)) + res := ic.UserLogin.QueueRemoteEvent(ic.xessengerInboxResync(thread)) if !res.Success { return res.Error } @@ -130,6 +130,7 @@ } batchCount := 0 + more := true if startCursor == "" { log.Info().Msg("No start cursor, loading from scratch") resp, err := ic.Client.GetMailbox(ctx) @@ -140,10 +141,11 @@ if !processThreads(resp.Mailbox.ThreadsByFolder) { return } + startCursor, more = ic.xessengerNextPage(resp.Mailbox.ThreadsByFolder) } else { batchCount++ } - for batchCount < ic.Main.Config.ThreadBackfill.BatchCount { + for more && batchCount < ic.Main.Config.ThreadBackfill.BatchCount { select { case <-time.After(ic.Main.Config.ThreadBackfill.BatchDelay): case <-ctx.Done(): @@ -158,9 +160,7 @@ return } batchCount++ - if !resp.Mailbox.ThreadsByFolder.PageInfo.HasNextPage { - break - } + startCursor, more = ic.xessengerNextPage(resp.Mailbox.ThreadsByFolder) } log.Info().Int("total_batch_count", batchCount).Msg("Completed chat backfill successfully") ic.LoginMeta.BackfillCompleted = true --- a/pkg/igconnector/config.go +++ b/pkg/igconnector/config.go @@ -56,6 +56,7 @@ type ThreadBackfillConfig struct { BatchCount int `yaml:"batch_count"` BatchDelay time.Duration `yaml:"batch_delay"` + DaysLimit int `yaml:"days_limit"` } func (tbc ThreadBackfillConfig) Enabled() bool { @@ -93,6 +94,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 (ic *IGConnector) GetConfig() (string, any, up.Upgrader) { --- a/pkg/igconnector/example-config.yaml +++ b/pkg/igconnector/example-config.yaml @@ -38,3 +38,7 @@ batch_count: 0 # Delay between fetching each batch of threads (to avoid rate limiting) batch_delay: 2s + # Don't create portals for inbox threads whose last activity is older than this many days, and stop + # fetching batches once the inbox reaches that far back. They get a portal when a new message arrives. + # 0 to disable. + days_limit: 0 --- /dev/null +++ b/pkg/igconnector/xessenger_thread_scope.go @@ -0,0 +1,47 @@ +package igconnector + +import ( + "time" + + "maunium.net/go/mautrix/bridgev2/simplevent" + + "go.mau.fi/mautrix-meta/pkg/instameow/slidetypes" +) + +// Xessenger: thread_backfill.days_limit. An inbox thread whose last activity is older gets no room +// from the inbox sync or the thread backfill, and the backfill stops once a page reaches that far +// back. Such a thread gets its room from its next message, whose event may create one. Rooms that +// exist are resynced as before. Zero makes rooms and stops as upstream does; the backfill's cursor +// fix applies either way. + +type xessengerInboxPage = slidetypes.Edged[slidetypes.Node[slidetypes.WrappedThreadInfo]] + +func (ic *IGClient) xessengerInboxResync(thread *slidetypes.ThreadInfo) *simplevent.ChatResync { + evt := ic.wrapChatResync(thread, false) + evt.CreatePortal = ic.xessengerRecentThread(thread) + return evt +} + +// xessengerRecentThread: active within days_limit, or of unknown activity, which upstream lets through. +func (ic *IGClient) xessengerRecentThread(thread *slidetypes.ThreadInfo) bool { + return !xessengerOlderThan(thread.LastActivityTimestampMS.Time, ic.Main.Config.ThreadBackfill.DaysLimit, time.Now()) +} + +// xessengerNextPage is the cursor of the inbox page after this one and whether to fetch it. Upstream +// fetched the page after the first one again and again, never moving its cursor. The inbox lists +// pinned threads first and then the newest first, so once a page's last unpinned thread is older than +// days_limit, the pages after it are too. +func (ic *IGClient) xessengerNextPage(page xessengerInboxPage) (cursor string, more bool) { + more = page.PageInfo.HasNextPage + for i := len(page.Edges) - 1; more && i >= 0; i-- { + if thread := page.Edges[i].Node.AsIGDirectThread; thread != nil && (thread.IsPin == nil || !*thread.IsPin) { + more = ic.xessengerRecentThread(thread) + break + } + } + return page.PageInfo.EndCursor, more +} + +func xessengerOlderThan(activity time.Time, days int, now time.Time) bool { + return days > 0 && activity.UnixMilli() > 0 && activity.Before(now.AddDate(0, 0, -days)) +} --- /dev/null +++ b/pkg/igconnector/xessenger_thread_scope_test.go @@ -0,0 +1,101 @@ +package igconnector + +import ( + "os" + "path/filepath" + "testing" + "time" + + up "go.mau.fi/util/configupgrade" + "go.mau.fi/util/jsontime" + "gopkg.in/yaml.v3" + + "go.mau.fi/mautrix-meta/pkg/instameow/slidetypes" +) + +func inboxThread(activity time.Time, pinned bool) slidetypes.Node[slidetypes.WrappedThreadInfo] { + return slidetypes.Node[slidetypes.WrappedThreadInfo]{Node: slidetypes.WrappedThreadInfo{ + AsIGDirectThread: &slidetypes.ThreadInfo{LastActivityTimestampMS: jsontime.UnixMilliString{Time: activity}, IsPin: &pinned}, + }} +} + +func TestXessengerInboxMakesRoomsOnlyForRecentThreads(t *testing.T) { + now := time.Now() + ic := &IGClient{Main: &IGConnector{Config: Config{ThreadBackfill: ThreadBackfillConfig{BatchCount: 10, DaysLimit: 90}}}} + for _, c := range []struct { + name string + activity time.Time + create bool + }{ + {"active yesterday", now.AddDate(0, 0, -1), true}, + {"active 89 days ago", now.AddDate(0, 0, -89), true}, + {"quiet for 91 days", now.AddDate(0, 0, -91), false}, + {"quiet since 2017", time.Date(2017, 3, 1, 0, 0, 0, 0, time.UTC), false}, + {"unknown activity", time.Time{}, true}, + {"activity 0", time.UnixMilli(0), true}, + } { + if got := ic.xessengerRecentThread(inboxThread(c.activity, false).Node.AsIGDirectThread); got != c.create { + t.Errorf("%s: create room %v, want %v", c.name, got, c.create) + } + } + upstream := &IGClient{Main: &IGConnector{}} + if !upstream.xessengerRecentThread(inboxThread(now.AddDate(-5, 0, 0), false).Node.AsIGDirectThread) { + t.Fatal("days_limit 0 left a thread without a room") + } + at := time.Date(2026, 11, 13, 0, 0, 0, 0, time.UTC) + if xessengerOlderThan(at.AddDate(0, 0, -90), 90, at) || !xessengerOlderThan(at.AddDate(0, 0, -90).Add(-time.Millisecond), 90, at) { + t.Fatal("older means more than 90 days before now") + } +} + +func TestXessengerInboxBackfillMovesOnAndStopsAtDaysLimit(t *testing.T) { + now := time.Now() + ic := &IGClient{Main: &IGConnector{Config: Config{ThreadBackfill: ThreadBackfillConfig{BatchCount: 10, DaysLimit: 90}}}} + page := func(hasNext bool, threads ...slidetypes.Node[slidetypes.WrappedThreadInfo]) xessengerInboxPage { + return xessengerInboxPage{Edges: threads, PageInfo: slidetypes.PageInfo{EndCursor: "next-cursor", HasNextPage: hasNext}} + } + recent, old := now.AddDate(0, 0, -3), now.AddDate(0, 0, -120) + for _, c := range []struct { + name string + page xessengerInboxPage + more bool + }{ + {"recent page", page(true, inboxThread(recent, false), inboxThread(recent, false)), true}, + {"page reaching back past 90 days", page(true, inboxThread(recent, false), inboxThread(old, false)), false}, + {"old pinned threads first", page(true, inboxThread(old, true), inboxThread(recent, false)), true}, + {"old pinned thread last", page(true, inboxThread(recent, false), inboxThread(old, true)), true}, + {"only pinned threads", page(true, inboxThread(old, true)), true}, + {"last page", page(false, inboxThread(recent, false)), false}, + } { + cursor, more := ic.xessengerNextPage(c.page) + if cursor != "next-cursor" || more != c.more { + t.Errorf("%s: next page %q %v, want %q %v", c.name, cursor, more, "next-cursor", c.more) + } + } + if _, more := (&IGClient{Main: &IGConnector{}}).xessengerNextPage(page(true, inboxThread(old, false))); !more { + t.Fatal("days_limit 0 stopped the backfill") + } +} + +func TestXessengerConfigKeepsThreadBackfillDaysLimit(t *testing.T) { + example, _, upgrader := (&IGConnector{}).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) + } +}