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
6 changes: 6 additions & 0 deletions api/dbv1/models.go

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 2 additions & 0 deletions api/server.go
Original file line number Diff line number Diff line change
Expand Up @@ -465,6 +465,7 @@ func NewApiServer(config config.Config) *ApiServer {
g.Post("/users/:userId/mute", app.requireAuthMiddleware, app.requireWriteScope, app.postV1UserMute)
g.Delete("/users/:userId/mute", app.requireAuthMiddleware, app.requireWriteScope, app.deleteV1UserMute)
g.Put("/users/:userId", app.requireAuthMiddleware, app.requireWriteScope, app.putV1User)
g.Post("/users/:userId/notifications/campaigns/:campaignId/open", app.requireAuthMiddleware, app.requireAuthForUserId, app.v1NotificationCampaignPushOpen)

// Tracks
g.Get("/tracks", app.v1Tracks)
Expand Down Expand Up @@ -626,6 +627,7 @@ func NewApiServer(config config.Config) *ApiServer {
// Notifications
g.Get("/notifications/:userId", app.requireUserIdMiddleware, app.v1Notifications)
g.Get("/notifications/:userId/playlist_updates", app.requireUserIdMiddleware, app.v1NotificationsPlaylistUpdates)
g.Get("/notifications/campaigns/:campaignId/opens", app.v1NotificationCampaignPushOpenMetrics)

// Protocol dashboard
g.Get("/dashboard_wallet_users", app.v1DashboardWalletUsers)
Expand Down
2 changes: 1 addition & 1 deletion api/swagger/swagger-v1.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -18347,7 +18347,7 @@ components:
type: string
route:
type: string
dashboard_announcement_id:
notification_campaign_id:
type: string
nullable: true
supporter_rank_up_notification_action:
Expand Down
88 changes: 88 additions & 0 deletions api/v1_notification_campaign_push_open.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,88 @@
package api

import (
"crypto/subtle"

"github.com/gofiber/fiber/v2"
"github.com/google/uuid"
)

const notificationCampaignOpenMetricsHeader = "X-Notification-Campaign-Metrics-Secret"

// POST /v1/users/:userId/notifications/campaigns/:campaignId/open
// Records a first-party push open for an internal notification campaign id (e.g. Supabase announcement / engagement send UUID).
func (app *ApiServer) v1NotificationCampaignPushOpen(c *fiber.Ctx) error {
if app.writePool == nil {
return fiber.NewError(fiber.StatusServiceUnavailable, "write database unavailable")
}

campaignID, err := uuid.Parse(c.Params("campaignId"))
if err != nil {
return fiber.NewError(fiber.StatusBadRequest, "invalid campaignId (expected UUID)")
}

userID := app.getUserId(c)
if userID <= 0 {
return fiber.NewError(fiber.StatusBadRequest, "invalid userId")
}

ctx := c.Context()
cmd, err := app.writePool.Exec(ctx, `
INSERT INTO notification_campaign_push_open (campaign_id, user_id, opened_at)
VALUES ($1, $2, now())
ON CONFLICT (campaign_id, user_id) DO NOTHING
`, campaignID, userID)
if err != nil {
return err
}

firstOpen := cmd.RowsAffected() > 0
return c.JSON(fiber.Map{
"data": fiber.Map{
"first_open": firstOpen,
},
})
}

// GET /v1/notifications/campaigns/:campaignId/opens
// Server-to-server: returns distinct opener count for metrics sync (protected by shared secret).
func (app *ApiServer) v1NotificationCampaignPushOpenMetrics(c *fiber.Ctx) error {
secret := app.config.NotificationCampaignOpenMetricsSecret
if secret == "" {
return fiber.NewError(fiber.StatusNotFound, "not found")
}

got := c.Get(notificationCampaignOpenMetricsHeader)
if !constantTimeStringEqual(got, secret) {
return fiber.NewError(fiber.StatusUnauthorized, "unauthorized")
}

campaignID, err := uuid.Parse(c.Params("campaignId"))
if err != nil {
return fiber.NewError(fiber.StatusBadRequest, "invalid campaignId (expected UUID)")
}

ctx := c.Context()
var count int64
err = app.pool.QueryRow(ctx, `
SELECT COUNT(*)::bigint
FROM notification_campaign_push_open
WHERE campaign_id = $1
`, campaignID).Scan(&count)
if err != nil {
return err
}

return c.JSON(fiber.Map{
"data": fiber.Map{
"unique_opens": count,
},
})
}

func constantTimeStringEqual(a, b string) bool {
if len(a) != len(b) {
return false
}
return subtle.ConstantTimeCompare([]byte(a), []byte(b)) == 1
}
45 changes: 24 additions & 21 deletions config/config.go
Original file line number Diff line number Diff line change
Expand Up @@ -56,30 +56,33 @@ type Config struct {
UploadNodes []string
// Optional API secret to be used for api.audius.co frontends
AudiusApiSecret string
// Shared secret for notifications-dashboard (or other internal jobs) to read notification campaign push open counts
NotificationCampaignOpenMetricsSecret string
}

var Cfg = Config{
Git: os.Getenv("GIT_SHA"),
Env: os.Getenv("ENV"),
LogLevel: os.Getenv("logLevel"),
ReadDbUrl: os.Getenv("readDbUrl"),
ReadDbReplicas: strings.Split(os.Getenv("readDbReplicas"), ","),
WriteDbUrl: os.Getenv("writeDbUrl"),
RunMigrations: os.Getenv("runMigrations") == "true",
EsUrl: os.Getenv("elasticsearchUrl"),
DelegatePrivateKey: os.Getenv("delegatePrivateKey"),
AxiomToken: os.Getenv("axiomToken"),
AxiomDataset: os.Getenv("axiomDataset"),
NetworkTakeRate: 10,
AudiusdURL: os.Getenv("audiusdUrl"),
OpenAudioURLs: []string{},
BirdeyeToken: os.Getenv("birdeyeToken"),
SolanaIndexerWorkers: 50,
SolanaIndexerRetryInterval: 5 * time.Minute,
CommsMessagePush: true,
LaunchpadDeterministicSecret: os.Getenv("launchpadDeterministicSecret"),
UnsplashKeys: strings.Split(os.Getenv("unsplashKeys"), ","),
AudiusApiSecret: os.Getenv("audiusApiSecret"),
Git: os.Getenv("GIT_SHA"),
Env: os.Getenv("ENV"),
LogLevel: os.Getenv("logLevel"),
ReadDbUrl: os.Getenv("readDbUrl"),
ReadDbReplicas: strings.Split(os.Getenv("readDbReplicas"), ","),
WriteDbUrl: os.Getenv("writeDbUrl"),
RunMigrations: os.Getenv("runMigrations") == "true",
EsUrl: os.Getenv("elasticsearchUrl"),
DelegatePrivateKey: os.Getenv("delegatePrivateKey"),
AxiomToken: os.Getenv("axiomToken"),
AxiomDataset: os.Getenv("axiomDataset"),
NetworkTakeRate: 10,
AudiusdURL: os.Getenv("audiusdUrl"),
OpenAudioURLs: []string{},
BirdeyeToken: os.Getenv("birdeyeToken"),
SolanaIndexerWorkers: 50,
SolanaIndexerRetryInterval: 5 * time.Minute,
CommsMessagePush: true,
LaunchpadDeterministicSecret: os.Getenv("launchpadDeterministicSecret"),
UnsplashKeys: strings.Split(os.Getenv("unsplashKeys"), ","),
AudiusApiSecret: os.Getenv("audiusApiSecret"),
NotificationCampaignOpenMetricsSecret: os.Getenv("notificationCampaignOpenMetricsSecret"),
}

func init() {
Expand Down
20 changes: 20 additions & 0 deletions sql/01_schema.sql
Original file line number Diff line number Diff line change
Expand Up @@ -7173,6 +7173,18 @@ CREATE TABLE public.notification_seen (
);


--
-- Name: notification_campaign_push_open; Type: TABLE; Schema: public; Owner: -
-- Internal notification campaign id (e.g. Supabase announcement / engagement send UUID) + discovery user_id; first open per pair.
--

CREATE TABLE public.notification_campaign_push_open (
campaign_id uuid NOT NULL,
user_id integer NOT NULL,
opened_at timestamp with time zone DEFAULT now() NOT NULL
);


--
-- Name: oauth_authorization_codes; Type: TABLE; Schema: public; Owner: -
--
Expand Down Expand Up @@ -9985,6 +9997,14 @@ ALTER TABLE ONLY public.notification_seen
ADD CONSTRAINT notification_seen_pkey PRIMARY KEY (user_id, seen_at);


--
-- Name: notification_campaign_push_open notification_campaign_push_open_pkey; Type: CONSTRAINT; Schema: public; Owner: -
--

ALTER TABLE ONLY public.notification_campaign_push_open
ADD CONSTRAINT notification_campaign_push_open_pkey PRIMARY KEY (campaign_id, user_id);


--
-- Name: oauth_authorization_codes oauth_authorization_codes_pkey; Type: CONSTRAINT; Schema: public; Owner: -
--
Expand Down
20 changes: 20 additions & 0 deletions sql/migrations/20260316_notification_campaign_push_open.sql
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
-- Run against Discovery Postgres (same DB as API read/write pools).
-- Idempotent: safe to run once in environments that do not use full 01_schema dumps.

CREATE TABLE IF NOT EXISTS public.notification_campaign_push_open (
campaign_id uuid NOT NULL,
user_id integer NOT NULL,
opened_at timestamp with time zone DEFAULT now() NOT NULL
);

DO $$
BEGIN
IF NOT EXISTS (
SELECT 1 FROM pg_constraint
WHERE conname = 'notification_campaign_push_open_pkey'
) THEN
ALTER TABLE ONLY public.notification_campaign_push_open
ADD CONSTRAINT notification_campaign_push_open_pkey
PRIMARY KEY (campaign_id, user_id);
END IF;
END $$;
Loading