Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
37 commits
Select commit Hold shift + click to select a range
d201167
fix(table): give the table view a single scrollport so virtualization…
claude Jun 10, 2026
15cc83c
fix(inspector): stop re-fetching rate limits every tick, guard stale …
claude Jun 10, 2026
c8050d7
fix(transport): add missing AddTracker/RemoveTracker HTTP routes
claude Jun 10, 2026
f083e07
fix(rss): stop validating filter regexes with the JS engine
claude Jun 10, 2026
87e3394
fix(selection): range-select over the visible list, confirm bulk keyb…
claude Jun 10, 2026
d5264c4
fix: assorted minor frontend bugs
claude Jun 10, 2026
3d3730a
fix(transport): cancel ws reconnect timer, bail with no subscribers, …
claude Jun 10, 2026
164f94b
watchfolder: fix Stop double-close panic and per-poll re-add storm
claude Jun 10, 2026
8b932a9
persistence: stop duplicate Save from clobbering user state; add SetP…
claude Jun 10, 2026
0471009
api: persist pause state and completed_at so they survive restarts
claude Jun 10, 2026
90a5d71
rss: persist seen items across restarts; poller hygiene
claude Jun 10, 2026
6a3b7cc
engine: don't revert sequential piece priorities after verify
claude Jun 10, 2026
10e763d
fix(remote): disconnect WS clients and revoke sessions when web inter…
claude Jun 10, 2026
e54c659
fix(events): add Bus.Unsubscribe and release Hub.Run's subscription o…
claude Jun 10, 2026
cf4b4a7
fix(remote): stop the WS session recheck from immortalizing idle sess…
claude Jun 10, 2026
42a2ef2
fix(persistence): detach torrents when deleting an in-use category
claude Jun 10, 2026
dd5a961
fix(remote): route handler errors through the sanitizing writeServiceErr
claude Jun 10, 2026
9b561c8
fix(remote): key ResetUserPassword's rate limit by the acting caller
claude Jun 10, 2026
d934a32
fix(remote): apply the OriginGuard to /api/login (login CSRF)
claude Jun 10, 2026
64f4b18
feat(remote): add POST /api/feeds/{id}/poll backing the SPA's per-fee…
claude Jun 10, 2026
6ff5341
fix(daemon): enforce seeding limits in mosaicd via shared tick loop
claude Jun 10, 2026
baaf7cb
fix(updater): include *.tar.gz in SHA256SUMS manifest
claude Jun 10, 2026
468c1a4
fix(updater): target $APPIMAGE for self-update instead of squashfs mount
claude Jun 10, 2026
ec6a282
fix(updater): honor pre-release identifiers in version comparison
claude Jun 10, 2026
f4b403d
fix(updater): apply channel + enabled toggles at runtime, not just boot
claude Jun 10, 2026
fe2ae76
fix(bootstrap): don't persist ephemeral fallback over a configured li…
claude Jun 10, 2026
635f1cd
fix(desktop): make startup context race-free, drain buffered launch a…
claude Jun 10, 2026
5b307d4
fix(config): reject unknown YAML keys, out-of-range ports, and missin…
claude Jun 10, 2026
44cad21
fix(platform): harden Linux single-instance socket dir and stale-bind…
claude Jun 10, 2026
3ebe270
fix(daemon): force-exit on a second SIGINT/SIGTERM during teardown
claude Jun 10, 2026
b934922
fix(engine): honor user peer cap on resume, dedupe snapshot saves, fi…
claude Jun 10, 2026
546f0be
fix(schedule): support midnight-wrapping rules and re-apply edited ac…
claude Jun 10, 2026
b34fcb9
fix(api): stop synthesizing added_at, serialize zero times as 0, gate…
claude Jun 10, 2026
bd1000b
fix(notifications): rune-aware truncate, safe Stop-before-Start, enfo…
claude Jun 10, 2026
abec112
fix(rss): validate filter regex on create and update
claude Jun 10, 2026
58fbced
fix(persistence): detach rss_filters when deleting a category
claude Jun 10, 2026
b3ff243
fix(api): persist cumulative transfer totals so ratio seed limits sur…
claude Jun 10, 2026
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
325 changes: 215 additions & 110 deletions app.go

Large diffs are not rendered by default.

19 changes: 19 additions & 0 deletions backend/api/feeds.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ package api
import (
"context"
"fmt"
"regexp"

"mosaic/backend/persistence"
)
Expand Down Expand Up @@ -181,10 +182,25 @@ func (s *Service) ListFiltersByFeed(ctx context.Context, feedID int) ([]FilterDT
return out, nil
}

// validateFilterRegex rejects patterns that won't compile. The poller
// compiles each filter per poll and skips (with a log) any that fail — so an
// invalid pattern stored here would be accepted silently and simply never
// match. The message prefix is registered in remote/handlers.go's
// userFacingValidationPrefixes so the SPA gets a 400 with the parse error.
func validateFilterRegex(pattern string) error {
if _, err := regexp.Compile(pattern); err != nil {
return fmt.Errorf("filter regex is invalid: %v", err)
}
return nil
}

func (s *Service) CreateFilter(ctx context.Context, dto FilterDTO) (int, error) {
if !CallerFrom(ctx).CanManageRSS() {
return 0, ErrForbidden
}
if err := validateFilterRegex(dto.Regex); err != nil {
return 0, err
}
return s.filters.Create(ctx, persistence.Filter{
FeedID: dto.FeedID, Regex: dto.Regex, CategoryID: dto.CategoryID,
SavePath: dto.SavePath, Enabled: dto.Enabled,
Expand All @@ -195,6 +211,9 @@ func (s *Service) UpdateFilter(ctx context.Context, dto FilterDTO) error {
if !CallerFrom(ctx).CanManageRSS() {
return ErrForbidden
}
if err := validateFilterRegex(dto.Regex); err != nil {
return err
}
return s.filters.Update(ctx, persistence.Filter{
ID: dto.ID, FeedID: dto.FeedID, Regex: dto.Regex, CategoryID: dto.CategoryID,
SavePath: dto.SavePath, Enabled: dto.Enabled,
Expand Down
79 changes: 60 additions & 19 deletions backend/api/rss_poller.go
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ type RSSPoller struct {
adder TorrentAdder
feeds *persistence.Feeds
filters *persistence.Filters
parser *gofeed.Parser
seen *persistence.RSSSeen
httpC *http.Client

mu sync.Mutex
Expand All @@ -36,22 +36,42 @@ type RSSPoller struct {
stop chan struct{}
}

// rssSeenCap bounds the persisted seen-set per feed: Add prunes the oldest
// rows beyond it, so the table tracks the ~1000 most recent items per feed.
const rssSeenCap = 1000

// rssBodyCap bounds how much of a feed body we parse — same idea as the
// 10 MB torrent-fetch cap below (blocklists get 50 MB elsewhere).
const rssBodyCap = 10 << 20

// NewRSSPoller starts a goroutine that ticks every 60 seconds and polls feeds
// whose LastPolled + IntervalMin has elapsed. Call Close() to stop the poller.
func NewRSSPoller(adder TorrentAdder, feeds *persistence.Feeds, filters *persistence.Filters) *RSSPoller {
func NewRSSPoller(adder TorrentAdder, feeds *persistence.Feeds, filters *persistence.Filters, seen *persistence.RSSSeen) *RSSPoller {
p := &RSSPoller{
adder: adder, feeds: feeds, filters: filters,
parser: gofeed.NewParser(),
adder: adder, feeds: feeds, filters: filters, seen: seen,
httpC: safeHTTPClient(30 * time.Second),
seenByID: make(map[int]map[string]struct{}),
stop: make(chan struct{}),
}
// Hydrate the seen cache from the DB before polling starts, so a restart
// doesn't re-add every matching item still present in the feeds.
p.loadSeen(WithCaller(context.Background(), SystemCaller))
go p.run()
return p
}

// loadSeen replaces the in-memory seen cache with the persisted sets.
func (p *RSSPoller) loadSeen(ctx context.Context) {
loaded, err := p.seen.All(ctx)
if err != nil {
log.Warn().Err(err).Msg("rss: load persisted seen items failed; matching items may be re-added")
return
}
p.mu.Lock()
p.seenByID = loaded
p.mu.Unlock()
}

func (p *RSSPoller) Close() { close(p.stop) }

// PollNow polls a single feed immediately, regardless of its
Expand Down Expand Up @@ -138,7 +158,11 @@ func (p *RSSPoller) pollOne(ctx context.Context, f persistence.Feed) error {
return fmt.Errorf("rss: HTTP %d", resp.StatusCode)
}

feed, err := p.parser.Parse(resp.Body)
// Fresh parser per Parse: gofeed.Parser lazily initializes its
// translators without synchronization, so sharing one instance between
// the run() goroutine and PollNow/GetFeedItems request goroutines races.
// Body is capped — a feed shouldn't be anywhere near 10 MB.
feed, err := gofeed.NewParser().Parse(io.LimitReader(resp.Body, rssBodyCap))
if err != nil {
if uerr := p.feeds.UpdatePollResult(ctx, f.ID, time.Now(), f.ETag); uerr != nil {
log.Warn().Err(uerr).Int("feed", f.ID).Msg("rss: update poll result failed")
Expand All @@ -150,7 +174,22 @@ func (p *RSSPoller) pollOne(ctx context.Context, f persistence.Feed) error {
if err != nil {
return err
}
enabledFilters := filterEnabled(filters)
// Compile each filter's regex once per poll instead of once per item;
// invalid patterns are logged once here rather than silently skipped on
// every item.
type compiledFilter struct {
persistence.Filter
re *regexp.Regexp
}
var enabledFilters []compiledFilter
for _, fil := range filterEnabled(filters) {
re, err := regexp.Compile(fil.Regex)
if err != nil {
log.Warn().Err(err).Int("feed_id", f.ID).Str("regex", fil.Regex).Msg("rss: invalid filter regex; filter skipped")
continue
}
enabledFilters = append(enabledFilters, compiledFilter{Filter: fil, re: re})
}

matched := 0
for _, item := range feed.Items {
Expand All @@ -166,11 +205,7 @@ func (p *RSSPoller) pollOne(ctx context.Context, f persistence.Feed) error {
}

for _, fil := range enabledFilters {
re, err := regexp.Compile(fil.Regex)
if err != nil {
continue
}
if !re.MatchString(item.Title) {
if !fil.re.MatchString(item.Title) {
continue
}

Expand All @@ -196,7 +231,7 @@ func (p *RSSPoller) pollOne(ctx context.Context, f persistence.Feed) error {
id = string(tid)
} else {
// No torrent source found — mark seen so we don't retry forever.
p.markSeen(f.ID, key)
p.markSeen(ctx, f.ID, key)
break
}

Expand All @@ -206,7 +241,7 @@ func (p *RSSPoller) pollOne(ctx context.Context, f persistence.Feed) error {
}
}
matched++
p.markSeen(f.ID, key)
p.markSeen(ctx, f.ID, key)
break // first matching filter wins
}
}
Expand All @@ -232,16 +267,21 @@ func (p *RSSPoller) alreadySeen(feedID int, key string) bool {
return ok
}

func (p *RSSPoller) markSeen(feedID int, key string) {
func (p *RSSPoller) markSeen(ctx context.Context, feedID int, key string) {
p.mu.Lock()
defer p.mu.Unlock()
if p.seenByID[feedID] == nil {
p.seenByID[feedID] = make(map[string]struct{})
}
if len(p.seenByID[feedID]) >= rssSeenCap {
p.seenByID[feedID] = make(map[string]struct{})
}
p.seenByID[feedID][key] = struct{}{}
p.mu.Unlock()
// Persist so dedup survives restarts; Add caps the table at the newest
// rssSeenCap rows per feed. The in-memory set is deliberately NOT capped
// or wiped — wiping it (the old behavior) re-added up to a full feed's
// worth of items on the next poll. Log-don't-fail: the in-memory set
// still dedups for the rest of this session.
if err := p.seen.Add(ctx, feedID, key, rssSeenCap); err != nil {
log.Warn().Err(err).Int("feed_id", feedID).Msg("rss: persist seen item failed")
}
}

func filterEnabled(all []persistence.Filter) []persistence.Filter {
Expand Down Expand Up @@ -365,7 +405,8 @@ func (p *RSSPoller) GetFeedItems(ctx context.Context, feedID int) ([]FeedItemDTO
if resp.StatusCode >= 400 {
return nil, fmt.Errorf("rss: HTTP %d", resp.StatusCode)
}
feed, err := p.parser.Parse(resp.Body)
// Fresh parser + capped body, same as pollOne (see comment there).
feed, err := gofeed.NewParser().Parse(io.LimitReader(resp.Body, rssBodyCap))
if err != nil {
return nil, err
}
Expand Down
45 changes: 41 additions & 4 deletions backend/api/rss_poller_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -42,25 +42,25 @@ func newPollerForTest(t *testing.T) (*RSSPoller, *Service, *persistence.Feeds, *
// handle to it, so build a fresh DB for poller dependencies. The poller's
// SetTorrentCategory / AddMagnet calls go through svc.* which uses svc's
// own DB, but tests only assert on the engine list (not the categories).
feeds, filters := newRSSDAOs(t)
feeds, filters, seen := newRSSDAOs(t)
p := &RSSPoller{
adder: svc,
feeds: feeds,
filters: filters,
parser: gofeed.NewParser(),
seen: seen,
httpC: &http.Client{Timeout: 5 * time.Second},
seenByID: make(map[int]map[string]struct{}),
stop: make(chan struct{}),
}
return p, svc, feeds, filters
}

func newRSSDAOs(t *testing.T) (*persistence.Feeds, *persistence.Filters) {
func newRSSDAOs(t *testing.T) (*persistence.Feeds, *persistence.Filters, *persistence.RSSSeen) {
t.Helper()
db, err := persistence.Open(sysCtx(), t.TempDir()+"/rss.db")
require.NoError(t, err)
t.Cleanup(func() { _ = db.Close() })
return persistence.NewFeeds(db), persistence.NewFilters(db)
return persistence.NewFeeds(db), persistence.NewFilters(db), persistence.NewRSSSeen(db)
}

func TestRSSPoller_PollOne_MatchesAndAddsMagnet(t *testing.T) {
Expand Down Expand Up @@ -151,6 +151,43 @@ func TestRSSPoller_PollOne_DedupViaSeenSet(t *testing.T) {
require.Len(t, rows, 2)
}

// TestRSSPoller_SeenSurvivesRestart pins the persisted dedup: a second poller
// hydrated from the same DB (simulating a process restart) must not re-add
// items the first poller already handled.
func TestRSSPoller_SeenSurvivesRestart(t *testing.T) {
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
_, _ = w.Write([]byte(rssFeedXML))
}))
defer srv.Close()

p, _, feeds, filters := newPollerForTest(t)
ctx := sysCtx()

feedID, _ := feeds.Create(ctx, persistence.Feed{URL: srv.URL, Name: "n", IntervalMin: 1, Enabled: true})
_, _ = filters.Create(ctx, persistence.Filter{FeedID: feedID, Regex: `.*`, Enabled: true})

f, _ := feeds.Get(ctx, feedID)
require.NoError(t, p.pollOne(ctx, f))

// "Restart": new poller against the same seen DAO, fresh in-memory cache.
svc2, _ := newTestService(t)
p2 := &RSSPoller{
adder: svc2,
feeds: feeds,
filters: filters,
seen: p.seen,
httpC: &http.Client{Timeout: 5 * time.Second},
seenByID: make(map[int]map[string]struct{}),
stop: make(chan struct{}),
}
p2.loadSeen(ctx)
require.NoError(t, p2.pollOne(ctx, f))

rows, err := svc2.ListTorrents(ctx)
require.NoError(t, err)
require.Empty(t, rows, "items seen before the restart must not be re-added")
}

func TestRSSPoller_Tick_SkipsDisabledAndNotDue(t *testing.T) {
hits := 0
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
Expand Down
37 changes: 30 additions & 7 deletions backend/api/schedule_engine.go
Original file line number Diff line number Diff line change
Expand Up @@ -18,11 +18,22 @@ type ScheduleEngine struct {
location *time.Location

mu sync.RWMutex
lastApplied int // rule ID we last applied (0 = none/cleared)
lastApplied appliedRule // rule + limits we last applied (zero = none/cleared)

stop chan struct{}
}

// appliedRule is the change-detection key for tick: the active rule's ID plus
// the limit values we applied for it. Keying on ID alone meant editing the
// currently-active rule's limits did nothing until the rule deactivated and
// reactivated — the edited values weren't re-applied because "same rule".
type appliedRule struct {
id int
downKbps int
upKbps int
altOnly bool
}

func NewScheduleEngine(svc *Service, rules *persistence.ScheduleRules, loc *time.Location) *ScheduleEngine {
if loc == nil {
loc = time.Local
Expand Down Expand Up @@ -68,23 +79,23 @@ func (se *ScheduleEngine) tick(ctx context.Context) {
if r.DaysMask&dayBit == 0 {
continue
}
if minutes < r.StartMin || minutes >= r.EndMin {
if !ruleWindowContains(r.StartMin, r.EndMin, minutes) {
continue
}
active = r
break
}

se.mu.Lock()
prevID := se.lastApplied
nextID := 0
prev := se.lastApplied
var next appliedRule
if active != nil {
nextID = active.ID
next = appliedRule{id: active.ID, downKbps: active.DownKbps, upKbps: active.UpKbps, altOnly: active.AltOnly}
}
se.lastApplied = nextID
se.lastApplied = next
se.mu.Unlock()

if prevID == nextID {
if prev == next {
return
}

Expand All @@ -105,3 +116,15 @@ func (se *ScheduleEngine) tick(ctx context.Context) {
log.Info().Int("rule_id", active.ID).Int("down", active.DownKbps).Int("up", active.UpKbps).
Msg("schedule_engine: applied rule")
}

// ruleWindowContains reports whether a rule's [startMin, endMin) window
// contains the given minutes-since-midnight. startMin > endMin means the
// window wraps midnight (e.g. 22:00–06:00, StartMin=1320 EndMin=360): the
// rule is active past the start OR before the end. startMin == endMin is an
// empty window, matching the pre-wrap behavior.
func ruleWindowContains(startMin, endMin, minutes int) bool {
if startMin <= endMin {
return minutes >= startMin && minutes < endMin
}
return minutes >= startMin || minutes < endMin
}
Loading
Loading