Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
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
59 changes: 59 additions & 0 deletions api/swagger/swagger-v1.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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"
Expand Down Expand Up @@ -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"
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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
Expand Down
2 changes: 1 addition & 1 deletion api/v1_notifications.go
Original file line number Diff line number Diff line change
Expand Up @@ -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"`
}
Expand Down
5 changes: 2 additions & 3 deletions api/v1_users_weekly_rotation.go
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down Expand Up @@ -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
}
Expand Down
5 changes: 5 additions & 0 deletions indexer/indexer.go
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
246 changes: 246 additions & 0 deletions jobs/create_weekly_rotation_featured_notifications.go
Original file line number Diff line number Diff line change
@@ -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
}
Loading