Files
descrybe/apps/api/internal/feeds/merge_integration_test.go
T

404 lines
16 KiB
Go
Raw Normal View History

2026-11-15 10:04:44 +01:00
package feeds
import (
"context"
"encoding/json"
"fmt"
"os"
"path/filepath"
"strconv"
"strings"
"testing"
"time"
"github.com/google/uuid"
"github.com/jackc/pgx/v5/pgxpool"
)
type mergeFixture struct {
ctx context.Context
pg *pgxpool.Pool
svc *Service
companyID uuid.UUID
dir string
}
func newMergeFixture(t *testing.T) *mergeFixture {
t.Helper()
dsn := strings.TrimSpace(os.Getenv("DATABASE_URL"))
if dsn == "" {
t.Skip("DATABASE_URL not set")
}
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Minute)
t.Cleanup(cancel)
pg, err := pgxpool.New(ctx, dsn)
if err != nil {
t.Fatal(err)
}
t.Cleanup(pg.Close)
companyID := uuid.New()
if _, err := pg.Exec(ctx, `INSERT INTO companies (id, name) VALUES ($1, $2)`, companyID, "merge-"+companyID.String()[:8]); err != nil {
t.Fatalf("seed company: %v", err)
}
t.Cleanup(func() { _, _ = pg.Exec(context.Background(), `DELETE FROM companies WHERE id = $1`, companyID) })
dir := t.TempDir()
if err := os.MkdirAll(filepath.Join(dir, companyID.String()), 0o755); err != nil {
t.Fatal(err)
}
return &mergeFixture{ctx: ctx, pg: pg, svc: &Service{Pool: pg, UploadDir: dir}, companyID: companyID, dir: dir}
}
// addFeed creates a CSV feed whose columns are mapped to the given canonical fields.
func (f *mergeFixture) addFeed(t *testing.T, name string, columns map[string]string) uuid.UUID {
t.Helper()
rel := f.companyID.String() + "/" + strings.ReplaceAll(strings.ToLower(name), " ", "-") + ".csv"
opts, _ := json.Marshal(map[string]any{"source_path": rel})
var feedID uuid.UUID
if err := f.pg.QueryRow(f.ctx, `
INSERT INTO input_feeds (company_id, name, url, feed_type, status, sync_interval_minutes, options)
VALUES ($1, $2, '', 'csv', 'active', 60, $3::jsonb) RETURNING id`, f.companyID, name, string(opts)).Scan(&feedID); err != nil {
t.Fatalf("seed feed: %v", err)
}
var mappings []map[string]string
for src, tgt := range columns {
mappings = append(mappings, map[string]string{"source": src, "target": tgt})
}
mb, _ := json.Marshal(mappings)
if _, err := f.pg.Exec(f.ctx, `INSERT INTO feed_mappings (feed_id, company_id, mappings) VALUES ($1, $2, $3::jsonb)`,
feedID, f.companyID, string(mb)); err != nil {
t.Fatalf("seed mapping: %v", err)
}
return feedID
}
func (f *mergeFixture) writeCSV(t *testing.T, name string, lines ...string) {
t.Helper()
p := filepath.Join(f.dir, f.companyID.String(), strings.ReplaceAll(strings.ToLower(name), " ", "-")+".csv")
if err := os.WriteFile(p, []byte(strings.Join(lines, "\n")+"\n"), 0o644); err != nil {
t.Fatal(err)
}
}
type rawState struct {
Mapped map[string]any
FeedID uuid.UUID
FeedIDs []string
Sources feedFieldSources
Status string
}
func (f *mergeFixture) raw(t *testing.T, gtin string) rawState {
t.Helper()
var st rawState
var mapped, ids, src []byte
if err := f.pg.QueryRow(f.ctx, `
SELECT mapped_data, feed_id, COALESCE(feed_ids, '[]'::jsonb), COALESCE(feed_field_sources, '{}'::jsonb), processing_status
FROM raw_products WHERE company_id = $1 AND gtin = $2`, f.companyID, gtin).Scan(&mapped, &st.FeedID, &ids, &src, &st.Status); err != nil {
t.Fatalf("load raw %s: %v", gtin, err)
}
_ = json.Unmarshal(mapped, &st.Mapped)
_ = json.Unmarshal(ids, &st.FeedIDs)
_ = json.Unmarshal(src, &st.Sources)
return st
}
func (f *mergeFixture) sync(t *testing.T, feedID uuid.UUID) time.Duration {
t.Helper()
start := time.Now()
if _, err := f.svc.Sync(f.ctx, f.companyID, feedID); err != nil {
t.Fatalf("sync: %v", err)
}
return time.Since(start)
}
func TestSyncMergesSameEANAcrossFeeds(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)
vendorA := f.addFeed(t, "Vendor A", map[string]string{
"EAN": "gtin", "Name": "name", "Brand": "brand", "Desc": "description", "Price": "price",
})
vendorB := f.addFeed(t, "Vendor B", map[string]string{
"EAN": "gtin", "Title": "name", "Description": "description", "Image": "main_image",
"More": "more_images", "EPREL": "eprel_id",
})
// 1) Vendor A alone: thin data.
f.writeCSV(t, "Vendor A", "EAN,Name,Brand,Desc,Price", ean+",Sony TV 65,Sony,Kratek opis.,560")
f.sync(t, vendorA)
st := f.raw(t, ean)
if st.FeedID != vendorA || st.Mapped["description"] != "Kratek opis." {
t.Fatalf("after A: feed=%v mapped=%v", st.FeedID, st.Mapped)
}
// Pretend the product was already processed, to prove a content change resets it.
if _, err := f.pg.Exec(f.ctx, `UPDATE raw_products SET is_processed = true, processing_status = 'processed' WHERE company_id = $1 AND gtin = $2`, f.companyID, ean); err != nil {
t.Fatal(err)
}
if _, err := f.pg.Exec(f.ctx, `INSERT INTO processed_products (company_id, raw_product_id, product_id, name) SELECT company_id, id, gtin, 'x' FROM raw_products WHERE company_id = $1 AND gtin = $2`, f.companyID, ean); err != nil {
t.Fatal(err)
}
// 2) Vendor B brings the description, images and EPREL id.
f.writeCSV(t, "Vendor B",
"EAN,Title,Description,Image,More,EPREL",
ean+",TV SONY K65,"+longDesc+",https://img/main.jpg,https://img/1.jpg;https://img/2.jpg,2651553")
f.sync(t, vendorB)
st = f.raw(t, ean)
if got := st.Mapped["description"]; !strings.Contains(fmt.Sprint(got), "Google TV") {
t.Fatalf("richest description did not win: %v", got)
}
for k, want := range map[string]string{
"brand": "Sony", "price": "560", "main_image": "https://img/main.jpg", "eprel_id": "2651553",
"name": "TV SONY K65", // Vendor B has more filled fields (5 vs 4), so it wins the conflicting name
} {
if st.Mapped[k] != want {
t.Errorf("merged %s = %v, want %q", k, st.Mapped[k], want)
}
}
if len(st.FeedIDs) != 2 {
t.Errorf("feed_ids = %v, want both feeds", st.FeedIDs)
}
if st.FeedID != vendorB {
t.Errorf("owner feed = %v, want richest feed B", st.FeedID)
}
if st.Sources.Primary.FeedName != "Vendor B" || st.Sources.Fields["name"].FeedName != "Vendor B" ||
len(st.Sources.Fields["name"].Also) != 1 || st.Sources.Fields["name"].Also[0].FeedName != "Vendor A" {
t.Errorf("name conflict not recorded: primary=%+v name=%+v", st.Sources.Primary, st.Sources.Fields["name"])
}
if st.Sources.Fields["description"].FeedName != "Vendor B" || !st.Sources.Fields["description"].Conflict {
t.Errorf("description source = %+v", st.Sources.Fields["description"])
}
if st.Sources.Fields["eprel_id"].FeedName != "Vendor B" || st.Sources.Fields["brand"].FeedName != "Vendor A" {
t.Errorf("sources = %+v", st.Sources.Fields)
}
if n := f.count(t, `SELECT count(*) FROM raw_product_feed_rows WHERE company_id = $1 AND gtin = $2`, ean); n != 2 {
t.Errorf("feed rows = %d, want 2", n)
}
if st.Status != "unprocessed" {
t.Errorf("changed content must reset processing, got %q", st.Status)
}
if n := f.count(t, `SELECT count(*) FROM processed_products WHERE company_id = $1`, ""); n != 0 {
t.Errorf("stale processed_products row survived: %d", n)
}
// 3) The regression the old code had: Vendor A re-syncs with a new price and must
// NOT wipe what Vendor B contributed.
f.writeCSV(t, "Vendor A", "EAN,Name,Brand,Desc,Price", ean+",Sony TV 65,Sony,Kratek opis.,499")
f.sync(t, vendorA)
st = f.raw(t, ean)
if st.Mapped["price"] != "499" {
t.Errorf("price update from A lost: %v", st.Mapped["price"])
}
if st.Mapped["eprel_id"] != "2651553" || st.Mapped["main_image"] != "https://img/main.jpg" ||
!strings.Contains(fmt.Sprint(st.Mapped["description"]), "Google TV") {
t.Errorf("Vendor B data lost after Vendor A re-sync: %v", st.Mapped)
}
// 4) Re-syncing unchanged data is stable (no flip-flopping between feeds).
f.writeCSV(t, "Vendor B",
"EAN,Title,Description,Image,More,EPREL",
ean+",TV SONY K65,"+longDesc+",https://img/main.jpg,https://img/1.jpg;https://img/2.jpg,2651553 ")
f.sync(t, vendorB)
again := f.raw(t, ean)
if again.FeedID != vendorB || fmt.Sprint(again.Mapped) != fmt.Sprint(st.Mapped) {
t.Errorf("unchanged re-sync altered product:\nbefore=%v\nafter=%v", st.Mapped, again.Mapped)
}
// A product only one feed carries is untouched by the merge.
f.writeCSV(t, "Vendor A", "EAN,Name,Brand,Desc,Price",
ean+",Sony TV 65,Sony,Kratek opis.,499", "9999999999994,Solo,Acme,Samo A,1")
f.sync(t, vendorA)
solo := f.raw(t, "9999999999994")
if solo.Mapped["name"] != "Solo" || len(solo.FeedIDs) != 1 || solo.FeedID != vendorA {
t.Errorf("single-feed product wrong: %+v", solo)
}
}
func (f *mergeFixture) count(t *testing.T, q, gtin string) int {
t.Helper()
var n int
var err error
if gtin == "" {
err = f.pg.QueryRow(f.ctx, q, f.companyID).Scan(&n)
} else {
err = f.pg.QueryRow(f.ctx, q, f.companyID, gtin).Scan(&n)
}
if err != nil {
t.Fatal(err)
}
return n
}
// TestSyncMergeTiming measures how long a resync takes with merging. Run with
// MERGE_TIMING_N=20000 for a bigger catalog; defaults to 5000 EANs per feed.
func TestSyncMergeTiming(t *testing.T) {
if os.Getenv("MERGE_TIMING") == "" {
t.Skip("set MERGE_TIMING=1 to run")
}
f := newMergeFixture(t)
n := 5000
if v, err := strconv.Atoi(os.Getenv("MERGE_TIMING_N")); err == nil && v > 0 {
n = v
}
a := f.addFeed(t, "Vendor A", map[string]string{"EAN": "gtin", "Name": "name", "Brand": "brand", "Desc": "description"})
b := f.addFeed(t, "Vendor B", map[string]string{"EAN": "gtin", "Title": "name", "Description": "description", "Image": "main_image", "EPREL": "eprel_id"})
var la, lb []string
la = append(la, "EAN,Name,Brand,Desc")
lb = append(lb, "EAN,Title,Description,Image,EPREL")
for i := 0; i < n; i++ {
ean := fmt.Sprintf("%013d", 4000000000000+i)
la = append(la, fmt.Sprintf("%s,Product %d,Brand,Short %d", ean, i, i))
if i%2 == 0 { // half of the catalog is carried by both vendors
lb = append(lb, fmt.Sprintf("%s,Product %d full,%s,https://img/%d.jpg,%d", ean, i,
strings.Repeat("Long enriched description. ", 20), i, 1000000+i))
}
}
f.writeCSV(t, "Vendor A", la...)
f.writeCSV(t, "Vendor B", lb...)
d1 := f.sync(t, a)
d2 := f.sync(t, b)
// Change every price/name so the resync is a full content update, not a hash skip.
for i := range la[1:] {
la[i+1] += "!"
}
f.writeCSV(t, "Vendor A", la...)
d3 := f.sync(t, a)
d4 := f.sync(t, a) // identical file: content-hash skip
t.Logf("EANs per feed: A=%d B=%d (overlap=%d)", n, len(lb)-1, len(lb)-1)
t.Logf("first sync A: %v (%.0f rows/s)", d1, float64(n)/d1.Seconds())
t.Logf("first sync B (merge): %v (%.0f rows/s)", d2, float64(len(lb)-1)/d2.Seconds())
t.Logf("changed resync A: %v (%.0f rows/s)", d3, float64(n)/d3.Seconds())
t.Logf("unchanged resync A: %v", d4)
merged := f.count(t, `SELECT count(*) FROM raw_products WHERE company_id = $1 AND jsonb_array_length(COALESCE(feed_ids,'[]'::jsonb)) = 2`, "")
if merged != len(lb)-1 {
t.Fatalf("merged products = %d, want %d", merged, len(lb)-1)
}
}
2026-11-15 16:47:06 +01:00
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)
}
}