From 2e44ab391b19b6c954964e2cde6aac7a735f8698 Mon Sep 17 00:00:00 2001 From: Dylan Jeffers Date: Mon, 9 Nov 2026 12:12:20 -0800 Subject: [PATCH] feat(api): tell artists how many Weekly Rotations featured their tracks New WeeklyRotationFeaturedNotificationsJob writes one weekly_rotation_featured notification per artist per period. It runs on rollover Wednesday (from 18:00 UTC, for 24h) and reports the period that just closed, because mixes are stored lazily on each listener's first request and a period's counts are only final once it ends. A track counts if it sat in the first weeklyrotation.ShownSize (30) slots of a stored mix and is still live; rotation_count is the number of distinct listeners whose mix included any of the artist's tracks. Data: {year, week, track_id (most-featured), track_count, rotation_count}. ShownSize moves into the weeklyrotation package so the endpoint's repeat suppression and the job agree on what "in the rotation" means. Co-Authored-By: Claude Opus 5.5 --- api/swagger/swagger-v1.yaml | 59 +++++ api/v1_notifications.go | 2 +- api/v1_users_weekly_rotation.go | 5 +- indexer/indexer.go | 5 + ..._weekly_rotation_featured_notifications.go | 246 ++++++++++++++++++ ...ly_rotation_featured_notifications_test.go | 211 +++++++++++++++ weeklyrotation/period.go | 5 + 7 files changed, 529 insertions(+), 4 deletions(-) create mode 100644 jobs/create_weekly_rotation_featured_notifications.go create mode 100644 jobs/create_weekly_rotation_featured_notifications_test.go diff --git a/api/swagger/swagger-v1.yaml b/api/swagger/swagger-v1.yaml index 79115de6..7816c024 100644 --- a/api/swagger/swagger-v1.yaml +++ b/api/swagger/swagger-v1.yaml @@ -8530,6 +8530,7 @@ paths: - comment_reaction - listen_streak_reminder - weekly_rotation + - weekly_rotation_featured - fan_remix_contest_started - fan_remix_contest_ended - fan_remix_contest_ending_soon @@ -17383,6 +17384,7 @@ components: - $ref: "#/components/schemas/comment_reaction_notification" - $ref: "#/components/schemas/listen_streak_reminder_notification" - $ref: "#/components/schemas/weekly_rotation_notification" + - $ref: "#/components/schemas/weekly_rotation_featured_notification" - $ref: "#/components/schemas/fan_remix_contest_started_notification" - $ref: "#/components/schemas/fan_remix_contest_ended_notification" - $ref: "#/components/schemas/fan_remix_contest_ending_soon_notification" @@ -17433,6 +17435,7 @@ components: comment_reaction: "#/components/schemas/comment_reaction_notification" listen_streak_reminder: "#/components/schemas/listen_streak_reminder_notification" weekly_rotation: "#/components/schemas/weekly_rotation_notification" + weekly_rotation_featured: "#/components/schemas/weekly_rotation_featured_notification" fan_remix_contest_started: "#/components/schemas/fan_remix_contest_started_notification" fan_remix_contest_ended: "#/components/schemas/fan_remix_contest_ended_notification" fan_remix_contest_ending_soon: "#/components/schemas/fan_remix_contest_ending_soon_notification" @@ -18086,6 +18089,26 @@ components: type: array items: $ref: "#/components/schemas/weekly_rotation_notification_action" + weekly_rotation_featured_notification: + required: + - actions + - group_id + - is_seen + - type + type: object + properties: + type: + type: string + group_id: + type: string + is_seen: + type: boolean + seen_at: + type: integer + actions: + type: array + items: + $ref: "#/components/schemas/weekly_rotation_featured_notification_action" comment_thread_notification_action: required: - data @@ -19321,6 +19344,22 @@ components: type: integer data: $ref: "#/components/schemas/weekly_rotation_notification_action_data" + weekly_rotation_featured_notification_action: + required: + - data + - specifier + - timestamp + - type + type: object + properties: + specifier: + type: string + type: + type: string + timestamp: + type: integer + data: + $ref: "#/components/schemas/weekly_rotation_featured_notification_action_data" comment_reaction_notification_action_data: required: - entity_id @@ -19826,6 +19865,26 @@ components: type: integer week: type: integer + weekly_rotation_featured_notification_action_data: + description: How many listeners' Weekly Rotations included the artist's tracks in the period that just closed (an ISO (year, week) pair). track_id is the most-featured track; when track_count is 1 it is the only one. + required: + - year + - week + - track_id + - track_count + - rotation_count + type: object + properties: + year: + type: integer + week: + type: integer + track_id: + type: integer + track_count: + type: integer + rotation_count: + type: integer artist_remix_contest_submissions_notification_action_data: required: - entity_id diff --git a/api/v1_notifications.go b/api/v1_notifications.go index db1d99a6..411483b4 100644 --- a/api/v1_notifications.go +++ b/api/v1_notifications.go @@ -56,7 +56,7 @@ const ( type GetNotificationsQueryParams struct { Limit int `query:"limit" default:"20" validate:"min=0,max=100"` - Types []string `query:"types" validate:"dive,oneof=announcement follow repost save remix cosign create tip_receive tip_send challenge_reward repost_of_repost save_of_repost tastemaker reaction supporter_dethroned supporter_rank_up supporting_rank_up milestone track_added_to_playlist tier_change trending trending_playlist trending_underground usdc_purchase_buyer usdc_purchase_seller track_added_to_purchased_album request_manager approve_manager_request track_collaborator_invite track_collaborator_accept claimable_reward comment comment_thread comment_mention comment_reaction listen_streak_reminder weekly_rotation fan_remix_contest_started fan_remix_contest_ended fan_remix_contest_ending_soon fan_remix_contest_winners_selected fan_remix_contest_submission artist_remix_contest_ended artist_remix_contest_ending_soon artist_remix_contest_submissions fan_club_text_post remix_contest_update"` + Types []string `query:"types" validate:"dive,oneof=announcement follow repost save remix cosign create tip_receive tip_send challenge_reward repost_of_repost save_of_repost tastemaker reaction supporter_dethroned supporter_rank_up supporting_rank_up milestone track_added_to_playlist tier_change trending trending_playlist trending_underground usdc_purchase_buyer usdc_purchase_seller track_added_to_purchased_album request_manager approve_manager_request track_collaborator_invite track_collaborator_accept claimable_reward comment comment_thread comment_mention comment_reaction listen_streak_reminder weekly_rotation weekly_rotation_featured fan_remix_contest_started fan_remix_contest_ended fan_remix_contest_ending_soon fan_remix_contest_winners_selected fan_remix_contest_submission artist_remix_contest_ended artist_remix_contest_ending_soon artist_remix_contest_submissions fan_club_text_post remix_contest_update"` GroupID string `query:"group_id" validate:"omitempty"` Timestamp float64 `query:"timestamp" validate:"omitempty,min=0"` } diff --git a/api/v1_users_weekly_rotation.go b/api/v1_users_weekly_rotation.go index 7312b442..e6a74345 100644 --- a/api/v1_users_weekly_rotation.go +++ b/api/v1_users_weekly_rotation.go @@ -31,11 +31,10 @@ const ( // limit is a prefix of the same list. weeklyRotationStoredSize = 50 - // Tracks in the first weeklyRotationSeenSize slots (what clients show) + // Tracks in the first weeklyrotation.ShownSize slots (what clients show) // of the last weeklyRotationLookbackPeriods mixes are not repeated. // Without this an unplayed track that keeps trending comes back every // week. - weeklyRotationSeenSize = 30 weeklyRotationLookbackPeriods = 2 // Long-form sets and DJ mixes stay in the mix but never open it. @@ -194,7 +193,7 @@ func (app *ApiServer) loadWeeklyRotationMix( WHERE m.user_id = $1 AND m.period_start >= $2::date - $3::int * 7 AND m.period_start < $2::date - `, userId, periodStart, weeklyRotationLookbackPeriods, weeklyRotationSeenSize).Scan(&recent) + `, userId, periodStart, weeklyRotationLookbackPeriods, weeklyrotation.ShownSize).Scan(&recent) if err != nil { return nil, err } diff --git a/indexer/indexer.go b/indexer/indexer.go index 7bc1055d..51235636 100644 --- a/indexer/indexer.go +++ b/indexer/indexer.go @@ -244,6 +244,11 @@ func (ci *CoreIndexer) startParityJobs(ctx context.Context) { jobs.NewWeeklyRotationNotificationsJob(ci.Config, ci.pool). ScheduleEvery(ctx, 30*time.Second) + // Tells artists how many Weekly Rotations their tracks were in during + // the period that just closed. Same pacing as the listener announcement. + jobs.NewWeeklyRotationFeaturedNotificationsJob(ci.Config, ci.pool). + ScheduleEvery(ctx, 30*time.Second) + // Backfill missing track bpm / musical_key from content-node audio // analyses. Mirrors apps' repair_audio_analyses celery task, whose beat // schedule ran every 3 minutes. Needs the SDK for content-node discovery. diff --git a/jobs/create_weekly_rotation_featured_notifications.go b/jobs/create_weekly_rotation_featured_notifications.go new file mode 100644 index 00000000..72474db5 --- /dev/null +++ b/jobs/create_weekly_rotation_featured_notifications.go @@ -0,0 +1,246 @@ +package jobs + +import ( + "context" + "fmt" + "sync" + "time" + + "api.audius.co/config" + "api.audius.co/database" + "api.audius.co/logging" + "api.audius.co/weeklyrotation" + "github.com/jackc/pgx/v5" + "go.uber.org/zap" +) + +// WeeklyRotationFeaturedNotificationsJob tells artists how many listeners' +// Weekly Rotations their tracks were in. One weekly_rotation_featured +// notification per artist per period; pedalboard turns the row into a push, +// gated by the push_weekly_rotation_featured remote-config variable. +// +// Mixes are computed lazily, on a listener's first request of a period, so a +// period's counts are only final once it has ended. The job therefore runs on +// rollover Wednesday and reports the period that just closed: the 2026-38 +// rollover announces the 2026-37 counts. A track counts if it was in the first +// weeklyrotation.ShownSize slots of a stored mix (what clients show) and is +// still live; the rotation count is the number of distinct listeners' mixes +// that included any of the artist's tracks. +// +// Sends start at weeklyRotationFeaturedSendHourUTC on rollover day and last +// for weeklyRotationFeaturedSendWindow; stage sends all period. Each run +// inserts up to batchSize rows walking owner_id upward from an in-memory +// cursor, so pedalboard and SNS see a stream rather than a burst. Once a run +// comes back short the period is drained and later runs skip the aggregate. +// uq_notification (group_id, specifier) makes reruns, restarts and multiple +// replicas safe. +type WeeklyRotationFeaturedNotificationsJob struct { + pool database.DbPool + logger *zap.Logger + env string + now func() time.Time + batchSize int + + mutex sync.Mutex + isRunning bool + + // Fan-out cursor for the period currently being reported. + cursorPeriod string + cursorOwnerId int32 + drained bool +} + +const ( + // weeklyRotationFeaturedSendHourUTC is the hour (UTC) on rollover day the + // artist fan-out begins. Two hours after the listener announcement + // (weeklyRotationSendHourUTC) so the two fan-outs don't overlap. + weeklyRotationFeaturedSendHourUTC = 18 + // weeklyRotationFeaturedSendWindow is how long after that the job keeps + // sending. + weeklyRotationFeaturedSendWindow = 24 * time.Hour + // weeklyRotationFeaturedBatchSize is the most rows one run inserts. + weeklyRotationFeaturedBatchSize = 1000 +) + +func NewWeeklyRotationFeaturedNotificationsJob(cfg config.Config, pool database.DbPool) *WeeklyRotationFeaturedNotificationsJob { + return &WeeklyRotationFeaturedNotificationsJob{ + pool: pool, + logger: logging.NewZapLogger(cfg).Named("WeeklyRotationFeaturedNotificationsJob"), + env: cfg.Env, + now: time.Now, + batchSize: weeklyRotationFeaturedBatchSize, + } +} + +// ScheduleEvery runs the job every `interval` until the context is cancelled. +func (j *WeeklyRotationFeaturedNotificationsJob) ScheduleEvery(ctx context.Context, interval time.Duration) *WeeklyRotationFeaturedNotificationsJob { + go func() { + ticker := time.NewTicker(interval) + defer ticker.Stop() + for { + select { + case <-ticker.C: + j.Run(ctx) + case <-ctx.Done(): + j.logger.Info("Job shutting down") + return + } + } + }() + return j +} + +// Run executes the job once. +func (j *WeeklyRotationFeaturedNotificationsJob) Run(ctx context.Context) { + if err := j.run(ctx); err != nil { + j.logger.Error("Job run failed", zap.Error(err)) + } +} + +// sendWindow returns the instants between which the period before the one +// containing `now` is reported. +func (j *WeeklyRotationFeaturedNotificationsJob) sendWindow(now time.Time) (start, end time.Time) { + year, week := weeklyrotation.Period(now) + periodStart := weeklyrotation.PeriodStart(year, week) + if j.env == "stage" { + return periodStart, periodStart.AddDate(0, 0, 7) + } + start = periodStart.Add(weeklyRotationFeaturedSendHourUTC * time.Hour) + return start, start.Add(weeklyRotationFeaturedSendWindow) +} + +func (j *WeeklyRotationFeaturedNotificationsJob) run(ctx context.Context) error { + start := time.Now() + j.mutex.Lock() + if j.isRunning { + j.mutex.Unlock() + return fmt.Errorf("job is already running") + } + j.isRunning = true + j.mutex.Unlock() + defer func() { + j.mutex.Lock() + j.isRunning = false + j.mutex.Unlock() + }() + + now := j.now() + windowStart, windowEnd := j.sendWindow(now) + if now.Before(windowStart) || !now.Before(windowEnd) { + return nil + } + + // The period being reported is the one that just ended. + year, week := weeklyrotation.Period(now.AddDate(0, 0, -7)) + period := weeklyrotation.PeriodKey(year, week) + if j.cursorPeriod != period { + j.cursorPeriod = period + j.cursorOwnerId = 0 + j.drained = false + } + if j.drained { + return nil + } + + // featured: one row per (listener, artist, track) in the shown slots of + // the period's mixes, live tracks only. The aggregate is restricted to + // owners past the cursor; LIMIT applies to the SELECT, so at most + // batch_size rows are attempted, and RETURNING reports what landed. + rows, err := j.pool.Query(ctx, ` + WITH featured AS ( + SELECT DISTINCT m.user_id AS listener_id, t.owner_id, t.track_id + FROM weekly_rotation_mixes m + CROSS JOIN LATERAL UNNEST(m.track_ids[1:@shown_size::int]) AS mix(track_id) + JOIN tracks t ON t.track_id = mix.track_id + AND t.is_current + AND NOT t.is_delete + AND NOT t.is_unlisted + AND t.is_available + WHERE m.period_start = @period_start::date + AND t.owner_id > @after_owner_id + ), + per_track AS ( + SELECT owner_id, track_id, COUNT(*) AS rotations + FROM featured + GROUP BY owner_id, track_id + ), + per_artist AS ( + SELECT + f.owner_id, + COUNT(DISTINCT f.track_id) AS track_count, + COUNT(DISTINCT f.listener_id) AS rotation_count, + ( + SELECT pt.track_id FROM per_track pt + WHERE pt.owner_id = f.owner_id + ORDER BY pt.rotations DESC, pt.track_id + LIMIT 1 + ) AS top_track_id + FROM featured f + GROUP BY f.owner_id + ) + INSERT INTO notification (specifier, group_id, blocknumber, user_ids, type, data, timestamp) + SELECT + a.owner_id::text, + @group_prefix || a.owner_id::text, + NULL, + ARRAY[a.owner_id], + 'weekly_rotation_featured', + jsonb_build_object( + 'year', @year::int, + 'week', @week::int, + 'track_id', a.top_track_id, + 'track_count', a.track_count, + 'rotation_count', a.rotation_count + ), + @now + FROM per_artist a + JOIN users u ON u.user_id = a.owner_id + AND u.is_current + AND NOT u.is_deactivated + AND u.is_available + WHERE NOT EXISTS ( + SELECT 1 FROM notification n + WHERE n.group_id = @group_prefix || a.owner_id::text + ) + ORDER BY a.owner_id + LIMIT @batch_size + ON CONFLICT (group_id, specifier) DO NOTHING + RETURNING user_ids[1] + `, pgx.NamedArgs{ + "group_prefix": "weekly_rotation_featured:" + period + ":", + "year": year, + "week": week, + "period_start": weeklyrotation.PeriodStart(year, week), + "shown_size": weeklyrotation.ShownSize, + "now": now, + "after_owner_id": j.cursorOwnerId, + "batch_size": j.batchSize, + }) + if err != nil { + return fmt.Errorf("insert weekly_rotation_featured notifications: %w", err) + } + ownerIds, err := pgx.CollectRows(rows, pgx.RowTo[int32]) + if err != nil { + return fmt.Errorf("collect weekly_rotation_featured notifications: %w", err) + } + for _, id := range ownerIds { + if id > j.cursorOwnerId { + j.cursorOwnerId = id + } + } + // A short batch means nothing past the cursor was left to send. (A + // conflict with another replica can also shorten it; that replica then + // covers the rest.) + if len(ownerIds) < j.batchSize { + j.drained = true + } + + if len(ownerIds) > 0 { + j.logger.Info("Inserted weekly_rotation_featured notifications", + zap.String("period", period), + zap.Int("count", len(ownerIds)), + zap.Int32("cursor", j.cursorOwnerId), + zap.Duration("duration", time.Since(start))) + } + return nil +} diff --git a/jobs/create_weekly_rotation_featured_notifications_test.go b/jobs/create_weekly_rotation_featured_notifications_test.go new file mode 100644 index 00000000..1a075b54 --- /dev/null +++ b/jobs/create_weekly_rotation_featured_notifications_test.go @@ -0,0 +1,211 @@ +package jobs + +import ( + "context" + "testing" + "time" + + "api.audius.co/database" + "api.audius.co/weeklyrotation" + "github.com/jackc/pgx/v5/pgxpool" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +// 2026-09-16 is the Wednesday that opens period 2026-38, so this is the first +// send instant for reporting period 2026-37. +var weeklyRotationFeaturedSendInstant = time.Date(2026, time.September, 16, 18, 0, 0, 0, time.UTC) + +func seedWeeklyRotationMix(t *testing.T, pool *pgxpool.Pool, userId int32, year, week int, trackIds []int32) { + t.Helper() + _, err := pool.Exec(context.Background(), ` + INSERT INTO weekly_rotation_mixes (user_id, period_start, track_ids) + VALUES ($1, $2, $3)`, + userId, weeklyrotation.PeriodStart(year, week), trackIds) + require.NoError(t, err) +} + +func seedWeeklyRotationFeatured(t *testing.T, pool *pgxpool.Pool) { + database.Seed(pool, database.FixtureMap{ + "users": { + {"user_id": 1, "handle": "listener1", "wallet": "0x01"}, + {"user_id": 2, "handle": "listener2", "wallet": "0x02"}, + {"user_id": 3, "handle": "listener3", "wallet": "0x03"}, + {"user_id": 10, "handle": "one_track", "wallet": "0x10"}, + {"user_id": 20, "handle": "two_tracks", "wallet": "0x20"}, + {"user_id": 30, "handle": "deactivated", "wallet": "0x30", "is_deactivated": true}, + {"user_id": 40, "handle": "past_shown", "wallet": "0x40"}, + {"user_id": 50, "handle": "deleted_track", "wallet": "0x50"}, + {"user_id": 60, "handle": "other_period", "wallet": "0x60"}, + }, + "tracks": { + {"track_id": 101, "owner_id": 10, "title": "solo"}, + {"track_id": 201, "owner_id": 20, "title": "a"}, + {"track_id": 202, "owner_id": 20, "title": "b"}, + {"track_id": 301, "owner_id": 30, "title": "gone owner"}, + {"track_id": 401, "owner_id": 40, "title": "slot 31"}, + {"track_id": 501, "owner_id": 50, "title": "deleted", "is_delete": true}, + {"track_id": 601, "owner_id": 60, "title": "this week"}, + {"track_id": 999, "owner_id": 30, "title": "filler"}, + }, + }) + + // Listener 3: 201 in slot 1, filler (deactivated owner) up to the last + // shown slot, then 401 in the first slot clients don't show. + listener3 := []int32{201} + for len(listener3) < weeklyrotation.ShownSize { + listener3 = append(listener3, 999) + } + listener3 = append(listener3, 401) + + // Period 2026-37 (the one being reported). + seedWeeklyRotationMix(t, pool, 1, 2026, 37, []int32{101, 201, 301, 501}) + seedWeeklyRotationMix(t, pool, 2, 2026, 37, []int32{202, 101}) + seedWeeklyRotationMix(t, pool, 3, 2026, 37, listener3) + // Period 2026-38 (in progress, not reported yet). + seedWeeklyRotationMix(t, pool, 1, 2026, 38, []int32{601}) +} + +func newWeeklyRotationFeaturedJob(pool database.DbPool, now time.Time) *WeeklyRotationFeaturedNotificationsJob { + job := NewWeeklyRotationFeaturedNotificationsJob(newTestConfig(), pool) + job.now = func() time.Time { return now } + return job +} + +func TestWeeklyRotationFeaturedNotifications_FanOut(t *testing.T) { + pool := database.CreateTestDatabase(t, "test_jobs") + defer pool.Close() + ctx := context.Background() + seedWeeklyRotationFeatured(t, pool) + + now := weeklyRotationFeaturedSendInstant.Add(30 * time.Minute) + job := newWeeklyRotationFeaturedJob(pool, now) + require.NoError(t, job.run(ctx)) + + rows, err := pool.Query(ctx, ` + SELECT specifier, group_id, user_ids, data, timestamp + FROM notification WHERE type = 'weekly_rotation_featured' ORDER BY specifier::int`) + require.NoError(t, err) + defer rows.Close() + + type row struct { + specifier string + groupID string + userIDs []int32 + data map[string]any + ts time.Time + } + var got []row + for rows.Next() { + var r row + require.NoError(t, rows.Scan(&r.specifier, &r.groupID, &r.userIDs, &r.data, &r.ts)) + got = append(got, r) + } + // Owners 30 (deactivated), 40 (only past the shown slots), 50 (deleted + // track) and 60 (other period) get nothing. + require.Len(t, got, 2) + + // One track in two listeners' rotations. + assert.Equal(t, "10", got[0].specifier) + assert.Equal(t, "weekly_rotation_featured:2026-37:10", got[0].groupID) + assert.Equal(t, []int32{10}, got[0].userIDs) + assert.Equal(t, map[string]any{ + "year": float64(2026), "week": float64(37), + "track_id": float64(101), "track_count": float64(1), "rotation_count": float64(2), + }, got[0].data) + assert.WithinDuration(t, now, got[0].ts, time.Second) + + // Two tracks across three rotations; 201 was in two, so it leads. + assert.Equal(t, "20", got[1].specifier) + assert.Equal(t, map[string]any{ + "year": float64(2026), "week": float64(37), + "track_id": float64(201), "track_count": float64(2), "rotation_count": float64(3), + }, got[1].data) + + // Idempotent: the same job is drained, and a restart adds nothing. + assert.True(t, job.drained) + require.NoError(t, job.run(ctx)) + fresh := newWeeklyRotationFeaturedJob(pool, now) + require.NoError(t, fresh.run(ctx)) + assert.Equal(t, 2, countNotifications(t, ctx, pool, "weekly_rotation_featured")) + + // The next rollover reports 2026-38. + nextWeek := newWeeklyRotationFeaturedJob(pool, now.AddDate(0, 0, 7)) + require.NoError(t, nextWeek.run(ctx)) + assert.Equal(t, 3, countNotifications(t, ctx, pool, "weekly_rotation_featured")) + var groupID string + require.NoError(t, pool.QueryRow(ctx, + `SELECT group_id FROM notification WHERE group_id LIKE 'weekly_rotation_featured:2026-38:%'`).Scan(&groupID)) + assert.Equal(t, "weekly_rotation_featured:2026-38:60", groupID) +} + +func TestWeeklyRotationFeaturedNotifications_SendWindow(t *testing.T) { + pool := database.CreateTestDatabase(t, "test_jobs") + defer pool.Close() + ctx := context.Background() + seedWeeklyRotationFeatured(t, pool) + + cases := []struct { + name string + now time.Time + sent bool + }{ + {"rollover instant, before send hour", weeklyRotationFeaturedSendInstant.Add(-18 * time.Hour), false}, + {"one second before send hour", weeklyRotationFeaturedSendInstant.Add(-time.Second), false}, + {"send hour", weeklyRotationFeaturedSendInstant, true}, + {"one second before the window closes", weeklyRotationFeaturedSendInstant.Add(24*time.Hour - time.Second), true}, + {"window closed (Thursday 18:00)", weeklyRotationFeaturedSendInstant.Add(24 * time.Hour), false}, + {"the following Monday", weeklyRotationFeaturedSendInstant.AddDate(0, 0, 5), false}, + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + _, err := pool.Exec(ctx, `DELETE FROM notification WHERE type = 'weekly_rotation_featured'`) + require.NoError(t, err) + + job := newWeeklyRotationFeaturedJob(pool, tc.now) + require.NoError(t, job.run(ctx)) + want := 0 + if tc.sent { + want = 2 + } + assert.Equal(t, want, countNotifications(t, ctx, pool, "weekly_rotation_featured")) + }) + } +} + +func TestWeeklyRotationFeaturedNotifications_StageSendsAllWeek(t *testing.T) { + pool := database.CreateTestDatabase(t, "test_jobs") + defer pool.Close() + ctx := context.Background() + seedWeeklyRotationFeatured(t, pool) + + // Rollover instant itself, well before the production send hour. + job := newWeeklyRotationFeaturedJob(pool, weeklyRotationFeaturedSendInstant.Add(-18*time.Hour)) + job.env = "stage" + require.NoError(t, job.run(ctx)) + assert.Equal(t, 2, countNotifications(t, ctx, pool, "weekly_rotation_featured")) +} + +func TestWeeklyRotationFeaturedNotifications_Pacing(t *testing.T) { + pool := database.CreateTestDatabase(t, "test_jobs") + defer pool.Close() + ctx := context.Background() + seedWeeklyRotationFeatured(t, pool) + + job := newWeeklyRotationFeaturedJob(pool, weeklyRotationFeaturedSendInstant) + job.batchSize = 1 + + require.NoError(t, job.run(ctx)) + assert.Equal(t, 1, countNotifications(t, ctx, pool, "weekly_rotation_featured")) + assert.Equal(t, int32(10), job.cursorOwnerId) + assert.False(t, job.drained) + + require.NoError(t, job.run(ctx)) + assert.Equal(t, 2, countNotifications(t, ctx, pool, "weekly_rotation_featured")) + assert.Equal(t, int32(20), job.cursorOwnerId) + + // The next run comes back empty and marks the period drained. + require.NoError(t, job.run(ctx)) + assert.Equal(t, 2, countNotifications(t, ctx, pool, "weekly_rotation_featured")) + assert.True(t, job.drained) +} diff --git a/weeklyrotation/period.go b/weeklyrotation/period.go index f2386d82..cfda8cab 100644 --- a/weeklyrotation/period.go +++ b/weeklyrotation/period.go @@ -19,6 +19,11 @@ import ( // the seed, share links and notification group ids. const RolloverOffsetDays = 2 +// ShownSize is how many slots of a stored mix clients show (the endpoint's +// default limit). A track only counts as "in" someone's rotation, for repeat +// suppression and for telling its artist, if it is within these slots. +const ShownSize = 30 + // Period returns the (ISO year, ISO week) pair that identifies the period // containing t. Shifting t back by the rollover offset before taking the // ISO week means Wednesday..Tuesday map to one ISO week.