-
Notifications
You must be signed in to change notification settings - Fork 9
feat(research): measurements read collection (chat#1796) #669
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,27 @@ | ||
| import { NextRequest, NextResponse } from "next/server"; | ||
| import { getCorsHeaders } from "@/lib/networking/getCorsHeaders"; | ||
| import { getAlbumMeasurementsHandler } from "@/lib/research/measurements/getAlbumMeasurementsHandler"; | ||
|
|
||
| export const maxDuration = 60; | ||
|
|
||
| /** | ||
| * OPTIONS /api/research/albums/{id}/measurements — CORS preflight. | ||
| * | ||
| * @returns CORS-enabled 200 response | ||
| */ | ||
| export async function OPTIONS() { | ||
| return new NextResponse(null, { status: 200, headers: getCorsHeaders() }); | ||
| } | ||
|
|
||
| /** | ||
| * GET /api/research/albums/{id}/measurements — latest measured count per track. | ||
| * | ||
| * @param request - The incoming HTTP request. | ||
| * @param options - Route options containing params. | ||
| * @param options.params - Route params containing the album id. | ||
| * @returns JSON album measurements or error | ||
| */ | ||
| export async function GET(request: NextRequest, options: { params: Promise<{ id: string }> }) { | ||
| const { id } = await options.params; | ||
| return getAlbumMeasurementsHandler(request, id); | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,28 @@ | ||
| import { NextRequest, NextResponse } from "next/server"; | ||
| import { getCorsHeaders } from "@/lib/networking/getCorsHeaders"; | ||
| import { getTrackMeasurementsHandler } from "@/lib/research/measurements/getTrackMeasurementsHandler"; | ||
|
|
||
| export const maxDuration = 60; | ||
|
|
||
| /** | ||
| * OPTIONS /api/research/tracks/{id}/measurements — CORS preflight. | ||
| * | ||
| * @returns CORS-enabled 200 response | ||
| */ | ||
| export async function OPTIONS() { | ||
| return new NextResponse(null, { status: 200, headers: getCorsHeaders() }); | ||
| } | ||
|
|
||
| /** | ||
| * GET /api/research/tracks/{id}/measurements — a track's measured series, or a | ||
| * derived `aggregate=run_rate` projection. | ||
| * | ||
| * @param request - The incoming HTTP request. | ||
| * @param options - Route options containing params. | ||
| * @param options.params - Route params containing the track id. | ||
| * @returns JSON measurements or error | ||
| */ | ||
| export async function GET(request: NextRequest, options: { params: Promise<{ id: string }> }) { | ||
| const { id } = await options.params; | ||
| return getTrackMeasurementsHandler(request, id); | ||
| } |
56 changes: 56 additions & 0 deletions
56
lib/research/measurements/__tests__/getAlbumMeasurements.test.ts
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,56 @@ | ||
| import { describe, it, expect, vi, beforeEach } from "vitest"; | ||
| import { getAlbumMeasurements } from "../getAlbumMeasurements"; | ||
| import { getAlbumPlaycounts } from "@/lib/research/playcounts/getAlbumPlaycounts"; | ||
|
|
||
| vi.mock("@/lib/research/playcounts/getAlbumPlaycounts", () => ({ getAlbumPlaycounts: vi.fn() })); | ||
|
|
||
| describe("getAlbumMeasurements", () => { | ||
| beforeEach(() => vi.clearAllMocks()); | ||
|
|
||
| it("remaps the album playcounts read into the measurements shape", async () => { | ||
| vi.mocked(getAlbumPlaycounts).mockResolvedValue({ | ||
| data: { | ||
| status: "success", | ||
| album: { spotify_album_id: "AL1" }, | ||
| playcounts: [ | ||
| { | ||
| isrc: "I1", | ||
| spotify_track_id: "T1", | ||
| name: "Song", | ||
| platform_displayed_play_count: 500, | ||
| captured_at: "2026-06-12T00:00:00+00:00", | ||
| data_source: "apify_spotify_playcount", | ||
| }, | ||
| ], | ||
| }, | ||
| }); | ||
|
|
||
| const r = await getAlbumMeasurements({ accountId: "acc_1", spotifyAlbumId: "AL1" }); | ||
|
|
||
| expect(getAlbumPlaycounts).toHaveBeenCalledWith({ accountId: "acc_1", spotifyAlbumId: "AL1" }); | ||
| expect(r).toEqual({ | ||
| data: { | ||
| status: "success", | ||
| id: "AL1", | ||
| platform: "spotify", | ||
| metric: "platform_displayed_play_count", | ||
| measurements: [ | ||
| { | ||
| isrc: "I1", | ||
| spotify_track_id: "T1", | ||
| name: "Song", | ||
| value: 500, | ||
| captured_at: "2026-06-12T00:00:00+00:00", | ||
| data_source: "apify_spotify_playcount", | ||
| }, | ||
| ], | ||
| }, | ||
| }); | ||
| }); | ||
|
|
||
| it("propagates a 404 from the underlying read", async () => { | ||
| vi.mocked(getAlbumPlaycounts).mockResolvedValue({ error: "No snapshot", status: 404 }); | ||
| const r = await getAlbumMeasurements({ accountId: "acc_1", spotifyAlbumId: "AL1" }); | ||
| expect(r).toEqual({ error: "No snapshot", status: 404 }); | ||
| }); | ||
| }); |
52 changes: 52 additions & 0 deletions
52
lib/research/measurements/__tests__/getAlbumMeasurementsHandler.test.ts
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,52 @@ | ||
| import { describe, it, expect, vi, beforeEach } from "vitest"; | ||
| import { NextRequest, NextResponse } from "next/server"; | ||
| import { getAlbumMeasurementsHandler } from "../getAlbumMeasurementsHandler"; | ||
| import { validateGetAlbumMeasurementsRequest } from "../validateGetAlbumMeasurementsRequest"; | ||
| import { getAlbumMeasurements } from "../getAlbumMeasurements"; | ||
|
|
||
| vi.mock("@/lib/networking/getCorsHeaders", () => ({ getCorsHeaders: vi.fn(() => ({})) })); | ||
| vi.mock("../validateGetAlbumMeasurementsRequest", () => ({ | ||
| validateGetAlbumMeasurementsRequest: vi.fn(), | ||
| })); | ||
| vi.mock("../getAlbumMeasurements", () => ({ getAlbumMeasurements: vi.fn() })); | ||
|
|
||
| const req = () => new NextRequest("http://x/api/research/albums/AL1/measurements"); | ||
| const validated = { accountId: "acc_1", spotifyAlbumId: "AL1" } as never; | ||
|
|
||
| describe("getAlbumMeasurementsHandler", () => { | ||
| beforeEach(() => vi.clearAllMocks()); | ||
|
|
||
| it("returns the album measurements payload on success", async () => { | ||
| vi.mocked(validateGetAlbumMeasurementsRequest).mockResolvedValue(validated); | ||
| vi.mocked(getAlbumMeasurements).mockResolvedValue({ | ||
| data: { status: "success", id: "AL1", measurements: [] }, | ||
| }); | ||
| const res = await getAlbumMeasurementsHandler(req(), "AL1"); | ||
| expect(res.status).toBe(200); | ||
| expect(await res.json()).toMatchObject({ id: "AL1" }); | ||
| }); | ||
|
|
||
| it("short-circuits with the validation response", async () => { | ||
| vi.mocked(validateGetAlbumMeasurementsRequest).mockResolvedValue( | ||
| NextResponse.json({ status: "error" }, { status: 401 }) as never, | ||
| ); | ||
| const res = await getAlbumMeasurementsHandler(req(), "AL1"); | ||
| expect(res.status).toBe(401); | ||
| expect(getAlbumMeasurements).not.toHaveBeenCalled(); | ||
| }); | ||
|
|
||
| it("maps error results to error responses", async () => { | ||
| vi.mocked(validateGetAlbumMeasurementsRequest).mockResolvedValue(validated); | ||
| vi.mocked(getAlbumMeasurements).mockResolvedValue({ error: "No snapshot", status: 404 }); | ||
| const res = await getAlbumMeasurementsHandler(req(), "AL1"); | ||
| expect(res.status).toBe(404); | ||
| }); | ||
|
|
||
| it("returns 500 on unexpected errors", async () => { | ||
| const consoleError = vi.spyOn(console, "error").mockImplementation(() => {}); | ||
| vi.mocked(validateGetAlbumMeasurementsRequest).mockRejectedValue(new Error("boom")); | ||
| const res = await getAlbumMeasurementsHandler(req(), "AL1"); | ||
| expect(res.status).toBe(500); | ||
| consoleError.mockRestore(); | ||
| }); | ||
| }); | ||
117 changes: 117 additions & 0 deletions
117
lib/research/measurements/__tests__/getTrackMeasurements.test.ts
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,117 @@ | ||
| import { describe, it, expect, vi, beforeEach } from "vitest"; | ||
| import { getTrackMeasurements } from "../getTrackMeasurements"; | ||
| import { resolveTrackIsrc } from "../resolveTrackIsrc"; | ||
| import { selectSongMeasurements } from "@/lib/supabase/song_measurements/selectSongMeasurements"; | ||
| import { computePlaycountDeltas } from "@/lib/research/playcounts/computePlaycountDeltas"; | ||
| import { deductCredits } from "@/lib/research/deductCredits"; | ||
|
|
||
| vi.mock("../resolveTrackIsrc", () => ({ resolveTrackIsrc: vi.fn() })); | ||
| vi.mock("@/lib/supabase/song_measurements/selectSongMeasurements", () => ({ | ||
| selectSongMeasurements: vi.fn(), | ||
| })); | ||
| vi.mock("@/lib/research/playcounts/computePlaycountDeltas", () => ({ | ||
| computePlaycountDeltas: vi.fn(), | ||
| })); | ||
| vi.mock("@/lib/research/deductCredits", () => ({ deductCredits: vi.fn() })); | ||
|
|
||
| const base = { | ||
| accountId: "acc_1", | ||
| id: "USQY51771120", | ||
| platform: "spotify", | ||
| metric: "platform_displayed_play_count", | ||
| windowDays: 365, | ||
| }; | ||
|
|
||
| // newest-first store rows for one song | ||
| const rows = [ | ||
| { | ||
| song: "I", | ||
| platform: "spotify", | ||
| metric: "m", | ||
| value: 300, | ||
| captured_at: "2026-06-12T00:00:00+00:00", | ||
| data_source: "apify_spotify_playcount", | ||
| }, | ||
| { | ||
| song: "I", | ||
| platform: "spotify", | ||
| metric: "m", | ||
| value: 100, | ||
| captured_at: "2025-06-12T00:00:00+00:00", | ||
| data_source: "songstats", | ||
| }, | ||
| ]; | ||
|
|
||
| describe("getTrackMeasurements", () => { | ||
| beforeEach(() => { | ||
| vi.clearAllMocks(); | ||
| vi.mocked(resolveTrackIsrc).mockResolvedValue("I"); | ||
| vi.mocked(selectSongMeasurements).mockResolvedValue(rows as never); | ||
| }); | ||
|
|
||
| it("404s when the id resolves to no ISRC", async () => { | ||
| vi.mocked(resolveTrackIsrc).mockResolvedValue(null); | ||
| const r = await getTrackMeasurements({ ...base }); | ||
| expect(r).toEqual({ error: "Unknown track id", status: 404 }); | ||
| expect(deductCredits).not.toHaveBeenCalled(); | ||
| }); | ||
|
|
||
| it("404s when the track has no measurements yet", async () => { | ||
| vi.mocked(selectSongMeasurements).mockResolvedValue([] as never); | ||
| const r = await getTrackMeasurements({ ...base }); | ||
| expect((r as { status: number }).status).toBe(404); | ||
| expect(deductCredits).not.toHaveBeenCalled(); | ||
| }); | ||
|
|
||
| it("returns the ascending daily series by default and charges one credit", async () => { | ||
| const r = await getTrackMeasurements({ ...base }); | ||
| expect(computePlaycountDeltas).not.toHaveBeenCalled(); | ||
| expect(deductCredits).toHaveBeenCalledWith("acc_1"); | ||
| expect(r).toEqual({ | ||
| data: { | ||
| status: "success", | ||
| id: "USQY51771120", | ||
| platform: "spotify", | ||
| metric: "platform_displayed_play_count", | ||
| series: [ | ||
| { date: "2025-06-12", value: 100, data_source: "songstats" }, | ||
| { date: "2026-06-12", value: 300, data_source: "apify_spotify_playcount" }, | ||
| ], | ||
| }, | ||
| }); | ||
| }); | ||
|
|
||
| it("returns a run_rate aggregate over the trailing window when aggregate=run_rate", async () => { | ||
| vi.mocked(computePlaycountDeltas).mockReturnValue([ | ||
| { | ||
| platform: "spotify", | ||
| metric: "platform_displayed_play_count", | ||
| since: { captured_at: "2025-06-12T00:00:00+00:00", value: 100 }, | ||
| until: { captured_at: "2026-06-12T00:00:00+00:00", value: 300 }, | ||
| delta: 200, | ||
| days: 365, | ||
| run_rate_annualized: 200, | ||
| }, | ||
| ]); | ||
|
|
||
| const r = await getTrackMeasurements({ ...base, aggregate: "run_rate" }); | ||
|
|
||
| // window start = latest date (2026-06-12) minus 365d | ||
| expect(computePlaycountDeltas).toHaveBeenCalledWith(rows, { since: "2025-06-12" }); | ||
| expect(r).toEqual({ | ||
| data: { | ||
| status: "success", | ||
| id: "USQY51771120", | ||
| platform: "spotify", | ||
| metric: "platform_displayed_play_count", | ||
| aggregate: { kind: "run_rate", window_days: 365, delta: 200, run_rate_annualized: 200 }, | ||
| }, | ||
| }); | ||
| }); | ||
|
|
||
| it("returns a null aggregate when history is insufficient for a run-rate", async () => { | ||
| vi.mocked(computePlaycountDeltas).mockReturnValue([]); | ||
| const r = await getTrackMeasurements({ ...base, aggregate: "run_rate" }); | ||
| expect((r as { data: { aggregate: unknown } }).data.aggregate).toBeNull(); | ||
| }); | ||
| }); |
58 changes: 58 additions & 0 deletions
58
lib/research/measurements/__tests__/getTrackMeasurementsHandler.test.ts
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,58 @@ | ||
| import { describe, it, expect, vi, beforeEach } from "vitest"; | ||
| import { NextRequest, NextResponse } from "next/server"; | ||
| import { getTrackMeasurementsHandler } from "../getTrackMeasurementsHandler"; | ||
| import { validateGetTrackMeasurementsRequest } from "../validateGetTrackMeasurementsRequest"; | ||
| import { getTrackMeasurements } from "../getTrackMeasurements"; | ||
|
|
||
| vi.mock("@/lib/networking/getCorsHeaders", () => ({ getCorsHeaders: vi.fn(() => ({})) })); | ||
| vi.mock("../validateGetTrackMeasurementsRequest", () => ({ | ||
| validateGetTrackMeasurementsRequest: vi.fn(), | ||
| })); | ||
| vi.mock("../getTrackMeasurements", () => ({ getTrackMeasurements: vi.fn() })); | ||
|
|
||
| const req = () => new NextRequest("http://x/api/research/tracks/I/measurements"); | ||
| const validated = { | ||
| accountId: "acc_1", | ||
| id: "I", | ||
| platform: "spotify", | ||
| metric: "platform_displayed_play_count", | ||
| windowDays: 365, | ||
| } as never; | ||
|
|
||
| describe("getTrackMeasurementsHandler", () => { | ||
| beforeEach(() => vi.clearAllMocks()); | ||
|
|
||
| it("returns the measurements payload on success", async () => { | ||
| vi.mocked(validateGetTrackMeasurementsRequest).mockResolvedValue(validated); | ||
| vi.mocked(getTrackMeasurements).mockResolvedValue({ | ||
| data: { status: "success", id: "I", series: [] }, | ||
| }); | ||
| const res = await getTrackMeasurementsHandler(req(), "I"); | ||
| expect(res.status).toBe(200); | ||
| expect(await res.json()).toMatchObject({ status: "success", id: "I" }); | ||
| }); | ||
|
|
||
| it("short-circuits with the validation response", async () => { | ||
| vi.mocked(validateGetTrackMeasurementsRequest).mockResolvedValue( | ||
| NextResponse.json({ status: "error" }, { status: 401 }) as never, | ||
| ); | ||
| const res = await getTrackMeasurementsHandler(req(), "I"); | ||
| expect(res.status).toBe(401); | ||
| expect(getTrackMeasurements).not.toHaveBeenCalled(); | ||
| }); | ||
|
|
||
| it("maps error results to error responses", async () => { | ||
| vi.mocked(validateGetTrackMeasurementsRequest).mockResolvedValue(validated); | ||
| vi.mocked(getTrackMeasurements).mockResolvedValue({ error: "Unknown track id", status: 404 }); | ||
| const res = await getTrackMeasurementsHandler(req(), "I"); | ||
| expect(res.status).toBe(404); | ||
| }); | ||
|
|
||
| it("returns 500 on unexpected errors", async () => { | ||
| const consoleError = vi.spyOn(console, "error").mockImplementation(() => {}); | ||
| vi.mocked(validateGetTrackMeasurementsRequest).mockRejectedValue(new Error("boom")); | ||
| const res = await getTrackMeasurementsHandler(req(), "I"); | ||
| expect(res.status).toBe(500); | ||
| consoleError.mockRestore(); | ||
| }); | ||
| }); |
36 changes: 36 additions & 0 deletions
36
lib/research/measurements/__tests__/resolveTrackIsrc.test.ts
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,36 @@ | ||
| import { describe, it, expect, vi, beforeEach } from "vitest"; | ||
| import { resolveTrackIsrc } from "../resolveTrackIsrc"; | ||
| import { selectSongIdentifiers } from "@/lib/supabase/song_identifiers/selectSongIdentifiers"; | ||
|
|
||
| vi.mock("@/lib/supabase/song_identifiers/selectSongIdentifiers", () => ({ | ||
| selectSongIdentifiers: vi.fn(), | ||
| })); | ||
|
|
||
| describe("resolveTrackIsrc", () => { | ||
| beforeEach(() => vi.clearAllMocks()); | ||
|
|
||
| it("returns an ISRC-shaped id unchanged without a lookup", async () => { | ||
| const out = await resolveTrackIsrc("USQY51771120"); | ||
| expect(out).toBe("USQY51771120"); | ||
| expect(selectSongIdentifiers).not.toHaveBeenCalled(); | ||
| }); | ||
|
|
||
| it("resolves a Spotify track id to its ISRC via the identifier mappings", async () => { | ||
| vi.mocked(selectSongIdentifiers).mockResolvedValue([ | ||
| { song: "USQY51771120", platform: "spotify", identifier_type: "track_id", value: "6Rmabc" }, | ||
| ]); | ||
| const out = await resolveTrackIsrc("6Rmabc"); | ||
| expect(selectSongIdentifiers).toHaveBeenCalledWith({ | ||
| platform: "spotify", | ||
| identifierType: "track_id", | ||
| values: ["6Rmabc"], | ||
| }); | ||
| expect(out).toBe("USQY51771120"); | ||
| }); | ||
|
|
||
| it("returns null when a non-ISRC id maps to nothing", async () => { | ||
| vi.mocked(selectSongIdentifiers).mockResolvedValue([]); | ||
| // a 22-char Spotify-style id (not ISRC-shaped) that has no mapping | ||
| expect(await resolveTrackIsrc("6rqhFgbbKwnb9MLmUQDhG6")).toBeNull(); | ||
| }); | ||
| }); |
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
P2: 500 error test does not verify the response body is a safe hardcoded string ("Internal error") and does not assert exception details ("boom") are absent from the response.
Prompt for AI agents