From 0ec433815bd5d122b50c735c8529dcaffeceb09a Mon Sep 17 00:00:00 2001 From: GreenEclipse Date: Sun, 15 Nov 2026 16:47:06 +0100 Subject: [PATCH] updare --- apps/api/cmd/worker/main.go | 14 ++ .../internal/feeds/merge_integration_test.go | 123 ++++++++++++++++++ apps/api/internal/feeds/schedule.go | 86 ++++++++++++ apps/api/internal/feeds/sync.go | 2 +- 4 files changed, 224 insertions(+), 1 deletion(-) create mode 100644 apps/api/internal/feeds/schedule.go diff --git a/apps/api/cmd/worker/main.go b/apps/api/cmd/worker/main.go index 310182d..89c4895 100644 --- a/apps/api/cmd/worker/main.go +++ b/apps/api/cmd/worker/main.go @@ -339,6 +339,13 @@ func main() { } } + if feeds.AutoSyncEnabled() && !cfg.MaintenanceMode && !cfg.ReadOnlyMode { + if n, err := feedSvc.EnqueueDueFeeds(ctx, 100, uuid.Nil); err != nil { + log.Printf("feed schedule enqueue (startup): %v", err) + } else if n > 0 { + log.Printf("feed schedule enqueued=%d (startup)", n) + } + } for { select { case <-ctx.Done(): @@ -355,6 +362,13 @@ func main() { } else if res.Processed > 0 { log.Printf("billing cycles processed=%d", res.Processed) } + if feeds.AutoSyncEnabled() { + if n, err := feedSvc.EnqueueDueFeeds(ctx, 100, uuid.Nil); err != nil { + log.Printf("feed schedule enqueue: %v", err) + } else if n > 0 { + log.Printf("feed schedule enqueued=%d", n) + } + } if n, err := woo.EnqueueDueScheduled(ctx, 6*time.Hour); err != nil { log.Printf("woo schedule enqueue: %v", err) } else if n > 0 { diff --git a/apps/api/internal/feeds/merge_integration_test.go b/apps/api/internal/feeds/merge_integration_test.go index ff770aa..c915964 100644 --- a/apps/api/internal/feeds/merge_integration_test.go +++ b/apps/api/internal/feeds/merge_integration_test.go @@ -279,3 +279,126 @@ func TestSyncMergeTiming(t *testing.T) { t.Fatalf("merged products = %d, want %d", merged, len(lb)-1) } } + +func (f *mergeFixture) setFeed(t *testing.T, id uuid.UUID, sql string, args ...any) { + t.Helper() + if _, err := f.pg.Exec(f.ctx, `UPDATE input_feeds SET `+sql+` WHERE id = $1`, append([]any{id}, args...)...); err != nil { + t.Fatal(err) + } +} + +func (f *mergeFixture) jobsFor(t *testing.T, id uuid.UUID) int { + t.Helper() + var n int + if err := f.pg.QueryRow(f.ctx, `SELECT count(*) FROM feed_sync_jobs WHERE feed_id = $1`, id).Scan(&n); err != nil { + t.Fatal(err) + } + return n +} + +// Feeds must sync by themselves once their interval has elapsed. +func TestEnqueueDueFeedsSchedulesOnlyDueFeeds(t *testing.T) { + f := newMergeFixture(t) + cols := map[string]string{"EAN": "gtin", "Name": "title"} + mk := func(name string) uuid.UUID { return f.addFeed(t, name, cols) } + + due := mk("due") // synced 2h ago, interval 60 + never := mk("never") // never synced + fresh := mk("fresh") // synced just now + pending := mk("pending") // already has a pending job + failed := mk("failed") // failed recently + paused := mk("paused") // not active + noInterval := mk("no interval") // interval 0 = manual only + noMapping := mk("no mapping") // never mapped + if _, err := f.pg.Exec(f.ctx, `DELETE FROM feed_mappings WHERE feed_id = $1`, noMapping); err != nil { + t.Fatal(err) + } + f.setFeed(t, due, `last_synced_at = now() - interval '2 hours'`) + f.setFeed(t, fresh, `last_synced_at = now()`) + f.setFeed(t, pending, `last_synced_at = now() - interval '2 hours'`) + f.setFeed(t, failed, `last_synced_at = now() - interval '2 hours'`) + f.setFeed(t, paused, `last_synced_at = now() - interval '2 hours', status = 'paused'`) + f.setFeed(t, noInterval, `last_synced_at = now() - interval '2 hours', sync_interval_minutes = 0`) + if _, err := f.pg.Exec(f.ctx, `INSERT INTO feed_sync_jobs (feed_id, company_id, status) VALUES ($1, $2, 'pending'), ($3, $2, 'failed')`, + pending, f.companyID, failed); err != nil { + t.Fatal(err) + } + + n, err := f.svc.EnqueueDueFeeds(f.ctx, 50, f.companyID) + if err != nil { + t.Fatal(err) + } + if n != 2 { + t.Errorf("queued %d feeds, want 2 (due + never)", n) + } + for name, id := range map[string]uuid.UUID{"due": due, "never": never} { + if f.jobsFor(t, id) != 1 { + t.Errorf("%s feed was not queued", name) + } + } + for name, id := range map[string]uuid.UUID{"fresh": fresh, "paused": paused, "no interval": noInterval, "no mapping": noMapping} { + if f.jobsFor(t, id) != 0 { + t.Errorf("%s feed must not be queued", name) + } + } + if f.jobsFor(t, pending) != 1 || f.jobsFor(t, failed) != 1 { + t.Error("feeds with a pending / recently failed job must not get another") + } + + // A second scan does not stack duplicate jobs. + if n, _ := f.svc.EnqueueDueFeeds(f.ctx, 50, f.companyID); n != 0 { + t.Errorf("second scan queued %d, want 0", n) + } +} + +// Products synced BEFORE merging existed (single overwritten row, no per-feed rows, an +// "unchanged" file) must merge on the next scheduled sync without any file change. +func TestAlreadySyncedProductsMergeOnNextSync(t *testing.T) { + f := newMergeFixture(t) + const ean = "4548736180307" + longDesc := strings.Repeat("Sony Bravia 4K z Google TV in HDR10 z 20 W zvokom. ", 12) + a := f.addFeed(t, "Vendor A", map[string]string{"EAN": "gtin", "Name": "title", "Brand": "brand", "Desc": "description", "Price": "purchaseprice"}) + b := f.addFeed(t, "Vendor B", map[string]string{"EAN": "gtin", "Title": "title", "Description": "description", "Image": "main_image", "EPREL": "eprel_id"}) + f.writeCSV(t, "Vendor A", "EAN,Name,Brand,Desc,Price", ean+",Sony TV 65,Sony,Kratek opis.,560") + f.writeCSV(t, "Vendor B", "EAN,Title,Description,Image,EPREL", ean+",TV SONY K65,"+longDesc+",https://img/main.jpg,2651553") + f.sync(t, a) + f.sync(t, b) + + // Recreate the pre-merge world: Vendor B overwrote everything, nothing else stored, + // and both feeds remember hashes from the old algorithm. + if _, err := f.pg.Exec(f.ctx, `DELETE FROM raw_product_feed_rows WHERE company_id = $1`, f.companyID); err != nil { + t.Fatal(err) + } + if _, err := f.pg.Exec(f.ctx, ` + UPDATE raw_products SET feed_id = $2, feed_ids = NULL, feed_field_sources = NULL, + mapped_data = jsonb_build_object('gtin', gtin, 'title', 'TV SONY K65', 'description', $3::text, + 'main_image', 'https://img/main.jpg', 'eprel_id', '2651553') + WHERE company_id = $1`, f.companyID, b, longDesc); err != nil { + t.Fatal(err) + } + f.setFeed(t, a, `options = options || '{"last_mapping_hash":"legacy"}'::jsonb`) + f.setFeed(t, b, `options = options || '{"last_mapping_hash":"legacy"}'::jsonb`) + if st := f.raw(t, ean); st.Mapped["brand"] != nil { + t.Fatalf("test setup wrong: %v", st.Mapped) + } + + // Scheduled syncs: neither file changed. + f.sync(t, a) + f.sync(t, b) + st := f.raw(t, ean) + if st.Mapped["brand"] != "Sony" || st.Mapped["purchaseprice"] != "560" { + t.Fatalf("Vendor A data not merged into the existing product: %v", st.Mapped) + } + if st.Mapped["eprel_id"] != "2651553" || !strings.Contains(fmt.Sprint(st.Mapped["description"]), "Google TV") { + t.Errorf("Vendor B data lost: %v", st.Mapped) + } + if len(st.FeedIDs) != 2 || st.Sources.Fields["brand"].FeedName != "Vendor A" || st.Sources.Fields["eprel_id"].FeedName != "Vendor B" { + t.Errorf("sources not recorded: ids=%v sources=%+v", st.FeedIDs, st.Sources.Fields) + } + + // After that one-time re-parse, an unchanged file is skipped again (cheap). + var hash string + if err := f.pg.QueryRow(f.ctx, `SELECT options->>'last_mapping_hash' FROM input_feeds WHERE id = $1`, a).Scan(&hash); err != nil || hash == "legacy" || hash == "" { + t.Errorf("mapping hash not refreshed: %q %v", hash, err) + } +} diff --git a/apps/api/internal/feeds/schedule.go b/apps/api/internal/feeds/schedule.go new file mode 100644 index 0000000..cd1c1f9 --- /dev/null +++ b/apps/api/internal/feeds/schedule.go @@ -0,0 +1,86 @@ +package feeds + +import ( + "context" + "os" + "strings" + + "github.com/google/uuid" +) + +// feedMergeVersion is mixed into the mapping hash. Bumping it makes every feed +// re-parse its file once, even when the file itself is unchanged, so rows written +// before cross-feed merging existed are merged without waiting for a file change. +const feedMergeVersion = "1" + +// AutoSyncEnabled reports whether the worker schedules feed syncs by itself. +// On by default; FEED_AUTO_SYNC=0|false|off turns it off. +func AutoSyncEnabled() bool { + switch strings.ToLower(strings.TrimSpace(os.Getenv("FEED_AUTO_SYNC"))) { + case "0", "false", "off", "no": + return false + } + return true +} + +// enqueueDueFeedsSQL queues one pending sync job per feed whose sync_interval_minutes +// has elapsed since its last sync. It skips feeds that: +// - are not active, have a zero interval, have no source or no active mapping +// - already have a pending or running job +// - failed within the last interval (so a broken feed is not retried every scan) +const enqueueDueFeedsSQL = ` + INSERT INTO feed_sync_jobs (feed_id, company_id, status) + SELECT f.id, f.company_id, 'pending' + FROM input_feeds f + WHERE f.status = 'active' + AND f.sync_interval_minutes > 0 + AND ($2::uuid IS NULL OR f.company_id = $2::uuid) + AND (f.last_synced_at IS NULL + OR f.last_synced_at + make_interval(mins => f.sync_interval_minutes) <= now()) + AND (COALESCE(f.url, '') <> '' + OR COALESCE(f.options->>'source_path', f.options->>'local_path', f.options->>'file_path', '') <> '') + AND EXISTS (SELECT 1 FROM feed_mappings m WHERE m.feed_id = f.id AND m.is_active) + AND NOT EXISTS ( + SELECT 1 FROM feed_sync_jobs j + WHERE j.feed_id = f.id AND j.status IN ('pending', 'running')) + AND NOT EXISTS ( + SELECT 1 FROM feed_sync_jobs j + WHERE j.feed_id = f.id AND j.status = 'failed' + AND j.created_at > now() - make_interval(mins => GREATEST(f.sync_interval_minutes, 15))) + ORDER BY f.last_synced_at ASC NULLS FIRST + LIMIT $1 + RETURNING id` + +// EnqueueDueFeeds queues sync jobs for feeds that are due (see enqueueDueFeedsSQL) and +// wakes the worker. companyID uuid.Nil means every company. It returns how many jobs +// were queued; the worker's sync slots then run them with the existing concurrency +// limits, so a large backlog drains gradually instead of all at once. +func (s *Service) EnqueueDueFeeds(ctx context.Context, limit int, companyID uuid.UUID) (int, error) { + if limit <= 0 { + limit = 20 + } + var company any + if companyID != uuid.Nil { + company = companyID + } + rows, err := s.Pool.Query(ctx, enqueueDueFeedsSQL, limit, company) + if err != nil { + return 0, err + } + defer rows.Close() + n := 0 + var last uuid.UUID + for rows.Next() { + if err := rows.Scan(&last); err != nil { + return n, err + } + n++ + } + if err := rows.Err(); err != nil { + return n, err + } + if n > 0 { + _, _ = s.Pool.Exec(ctx, `SELECT pg_notify('feed_sync_jobs', $1)`, last.String()) + } + return n, nil +} diff --git a/apps/api/internal/feeds/sync.go b/apps/api/internal/feeds/sync.go index ba6aad2..f657e0f 100644 --- a/apps/api/internal/feeds/sync.go +++ b/apps/api/internal/feeds/sync.go @@ -304,7 +304,7 @@ func (s *Service) runSync(ctx context.Context, companyID, feedID, jobID uuid.UUI if len(mappings) == 0 { return stats, ClientMsg("no field mappings defined for feed") } - stats.MappingHash = sha256Hex([]byte(mustJSON(mappingsRaw) + "|language=" + feedLanguage)) + stats.MappingHash = sha256Hex([]byte(mustJSON(mappingsRaw) + "|language=" + feedLanguage + "|merge=" + feedMergeVersion)) prev, err := s.lastSuccessfulSync(ctx, feedID) if err != nil {