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 }