Repository navigation
Add daily Luminate catalog stream tracking - #984
Conversation
|
The latest updates on your projects. Learn more about Vercel for GitHub.
|
|
Important
This repository does not receive automatic reviews because it has fewer than 10 stars. ⚙️ Run configuration
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. Comment |
There was a problem hiding this comment.
13 issues found across 63 files
Confidence score: 3/5
startCatalogStreamRun.tscan consume the catalog’s daily claim when starting the workflow fails, blocking a later refresh or dispatcher retry that day. Make failed starts retryable.manageCatalogStreamTracking.tscan select a different accessible owner after the original owner link is removed, but active-run checks still require the originalowner_id; this can revoke runs despite another valid link. Keep owner selection and run validation consistent.catalogStreamsWorkflow.tsclassifies provider failures by message text, which can misclassify transient Luminate authentication errors. Use the error type to decide whether to retry.
Prompt for AI agents (unresolved issues)
Check if these issues are valid — if so, understand the root cause of each and fix them. When an issue isn't valid or won't be fixed in this PR, reply in its thread with the reason and then resolve the thread. If appropriate, use sub-agents to investigate and fix each issue separately.
<file name="lib/mcp/tools/catalogs/__tests__/registerGetCatalogPlaycountHistoryTool.test.ts">
<violation number="1" location="lib/mcp/tools/catalogs/__tests__/registerGetCatalogPlaycountHistoryTool.test.ts:57">
P3: This test does not verify delegated OAuth is rejected before account resolution: it still passes if the handler calls `resolveAccountId` and then returns an error. Import the mocked resolver and assert it was not called to protect the ordering named by this test.</violation>
</file>
<file name="lib/luminate/getLuminateAccessToken.ts">
<violation number="1" location="lib/luminate/getLuminateAccessToken.ts:54">
P2: Custom agent: **Enforce Clear Code Style and Maintainability Practices**
`auth` is an evolving `any` populated directly from `JSON.parse`, so the authentication payload is not strictly typed. Declare it as `unknown` and narrow it with an explicit response shape/type guard before reading `access_token` and `expires_in`.</violation>
</file>
<file name="lib/catalog/startCatalogStreamRun.ts">
<violation number="1" location="lib/catalog/startCatalogStreamRun.ts:19">
P2: A transient workflow-start failure consumes the catalog’s only daily claim, so a later `refresh` or dispatcher retry that day cannot start collection. Add a recovery path that makes failed starts retryable without creating duplicate workflows.</violation>
</file>
<file name="lib/catalog/manageCatalogStreamTracking.ts">
<violation number="1" location="lib/catalog/manageCatalogStreamTracking.ts:29">
P2: `selectAccountCatalog` can return an arbitrary matching owner, but `assertCatalogStreamRunActive` later requires this exact `owner_id`. If that link is removed while another accessible link remains, runs are revoked and repeated enable cannot rebind the enabled row; resolve a stable owner or validate against all current owners.</violation>
</file>
<file name="app/api/internal/catalog-stream-maintenance/route.ts">
<violation number="1" location="app/api/internal/catalog-stream-maintenance/route.ts:23">
P3: The `catch {}` swallows the `start()` failure without logging, so a 503 on a failed dispatch leaves no trace of the underlying cause. Other dispatch call sites log the error (e.g. `enqueueHistoricalBackfill.ts` logs `"[measurement-jobs] failed to kick backfill drain:", error`). Bind the error and log it in the catch block.</violation>
</file>
<file name="lib/catalog/getCatalogPlaycountHistoryHandler.ts">
<violation number="1" location="lib/catalog/getCatalogPlaycountHistoryHandler.ts:36">
P2: This catch converts every thrown error into a 503 but discards the exception with no server-side log, so failures in `selectCatalogRecordingPage` and `selectPublicPlaycountHistory` (both throw without logging) become invisible in production. Other repo handlers log before returning an error, e.g. `getCatalogMeasurementsHandler` (`console.error("Error fetching catalog measurements:", error)` before its 500). Log the error here; the response message can stay generic.</violation>
</file>
<file name="lib/catalog/validateCatalogPlaycountHistoryQuery.ts">
<violation number="1" location="lib/catalog/validateCatalogPlaycountHistoryQuery.ts:13">
P3: `z.coerce.number()` converts JSON `true` to `1`, so MCP callers can pass booleans for `days`, `page`, or `limit` and have them silently accepted as numeric values. Coerce numeric strings only and reject other input types.</violation>
</file>
<file name="app/workflows/catalogStreamsWorkflow.ts">
<violation number="1" location="app/workflows/catalogStreamsWorkflow.ts:19">
P2: Classifying provider errors by message substring misfires on both sides. `getLuminateAccessToken` throws `RetryableError("Luminate authentication temporarily unavailable")` for transient auth-endpoint 429/5xx; its message contains "Luminate authentication", so after the SDK's automatic step retries are exhausted this catches the run and marks it permanently `failed`/`provider_authentication_failed` even though the credentials are fine. Conversely, a 401 on the recording fetch in `fetchLuminateStreams` becomes `FatalError("Luminate recording unavailable (HTTP 401)")`, which does not match, so a genuinely broken credential on every recording is recorded as isolated per-track `failed` and the run surfaces as `partial` instead of failing with the auth error. Discriminate by error type (e.g. `error instanceof RetryableError` → per-track failure/partial; only `FatalError` auth errors → fail the run) and/or add an explicit error code to the thrown errors instead of matching on message text.</violation>
</file>
<file name="lib/mcp/oauth/registerFullOAuthTools.ts">
<violation number="1" location="lib/mcp/oauth/registerFullOAuthTools.ts:45">
P2: Custom agent: **Flag AI Slop and Fabricated Changes**
Add a regression assertion for the full OAuth catalog that verifies `get_catalog_playcount_history`, `get_catalog_streams`, and `manage_catalog_stream_tracking` are not registered. The current catalog tests cover standard registration or handler rejection, not this OAuth discovery boundary.</violation>
</file>
<file name="app/workflows/dispatchCatalogStreamsStep.ts">
<violation number="1" location="app/workflows/dispatchCatalogStreamsStep.ts:15">
P3: The hardcoded `100`/`99` cursor math here must stay in sync with the `.limit(100)` inside `selectEnabledCatalogStreamTracking` (a different file). Raising or lowering that limit silently shifts the cursor to the wrong row and either skips or re-dispatches subscriptions. The same cross-file magic-number coupling applies to `62` in `fetchCatalogStreamTrackStep` (vs. the 61-day span refine in `luminateStreamRequestSchema`) and `250` in `prepareCatalogStreamRunStep`. Extract these limits as shared constants (e.g. `lib/const.ts`) so the cursor and page size cannot drift apart.</violation>
</file>
<file name="lib/catalog/catalogStreamsHandler.ts">
<violation number="1" location="lib/catalog/catalogStreamsHandler.ts:50">
P2: The catch block discards the error entirely (`catch { ... }`) without logging, so every internal failure — missing Luminate credentials, workflow start failures, transient DB errors from `selectCatalogStreamTracking`/`selectLatestCatalogStreamRun` — becomes an unrecoverable 503 with no server-side trace. Every other catalog handler (`getCatalogsHandler`, `createCatalogHandler`, `deleteCatalogHandler`, `getCatalogSongs`, etc.) logs via `console.error` in its catch block, and the endpoint-level redaction convention requires logging the full error server-side while returning the hardcoded message. Add `} catch (error) { console.error(...); ... }`. The redacted 503 body is correct as-is.
(Based on your team's feedback about redacting internal error details while logging the full error server-side.)</violation>
</file>
<file name="lib/supabase/catalog_stream_runs/selectLatestCatalogStreamRun.ts">
<violation number="1" location="lib/supabase/catalog_stream_runs/selectLatestCatalogStreamRun.ts:8">
P3: This capped newest-row query orders only by `created_at`, so two runs created in the same database transaction time (a cron sweep can claim several catalogs back-to-back) resolve nondeterministically, and `getCatalogStreams`/`manageCatalogStreamTracking` can surface either run as "latest". Append `.order("id", { ascending: false })` after the timestamp order to make ties stable, matching the tie-break pattern used for the other capped latest-row selectors.</violation>
</file>
<file name="lib/catalog/compareSpotifyDailyStreams.ts">
<violation number="1" location="lib/catalog/compareSpotifyDailyStreams.ts:13">
P3: The exported name `compareSpotifyDailyStreams` advertises Spotify, but the only consumer is the Luminate read path and the function is generic date-summing. Rename it (e.g., `compareCatalogDailyStreams`, which also matches `compareCatalogPlaycountHistory` naming) so the contract doesn't mislead future callers.</violation>
</file>
Architecture diagram
sequenceDiagram
participant C as Client/HTTP
participant M as MCP Client
participant H as API Handler
participant A as Auth Context
participant L as Luminate Provider
participant D as Dispatcher
participant W as Workflow Engine
participant DB as Supabase
Note over C,W: Daily Catalog Stream Tracking
C->>H: POST /catalogs/{id}/stream-tracking {action: enable}
rect rgb(245,245,245)
Note over H,A: Auth + Ownership
H->>A: validateAuthContext
A-->>H: accountId
H->>DB: selectAccountCatalog
DB-->>H: catalog ownership ok
end
rect rgb(245,245,245)
Note over H,DB: Enable tracking
H->>DB: upsertCatalogStreamTracking (new revision)
DB-->>H: tracking enabled
H->>DB: claimCatalogStreamRun (day)
DB-->>H: run claimed
end
H->>W: start(catalogStreamsWorkflow, [runId])
Note over W: 62-day backfill window
W->>DB: assertCatalogStreamRunActive
DB-->>W: run active
W->>DB: selectCatalogRecordingPage (limit 250)
DB-->>W: songs list
W->>W: validate size and revision
loop For each ISRC
W->>DB: assertCatalogStreamRunActive(runId, isrc)
DB-->>W: active
W->>L: fetchLuminateStreams (62 days)
L-->>W: days + source_hash
Note over W: memoized fetch result
opt On 401 from provider
L->>W: 401 status
W->>L: refresh access token
L-->>W: new token
W->>L: retry fetch
end
W->>DB: commitCatalogStreamTrack
DB-->>W: committed (true/false)
Note over W,DB: Fenced write - rejects if revoked
end
W->>DB: updateCatalogStreamRun (complete/partial)
C->>H: GET /catalogs/{id}/streams
H->>A: validateAuthContext
A-->>H: accountId
H->>DB: read_catalog_stream_days
DB-->>H: observations with versions
H-->>C: stream history with growth calc
Note over C,M: MCP Tools
M->>H: manage_catalog_stream_tracking
M->>H: get_catalog_streams
H->>A: resolveAccountId
alt Standard auth
A-->>H: accountId
H->>DB: check catalog access
H-->>M: result
else Delegated OAuth
H-->>M: error (hidden/denied)
end
Note over L,DB: Scheduled daily refresh
D->>D: Vercel Cron 09:00 UTC
D->>D: validateCronRequest + LUMINATE config
D->>W: start catalogStreamsMaintenanceWorkflow
W->>DB: selectEnabledCatalogStreamTracking
loop For each enabled catalog
W->>DB: claimCatalogStreamRun
DB-->>W: run claimed
W->>W: catalogStreamsWorkflow(runId)
end
Reply with feedback, questions, or to request a fix.
View guided diff | Turn on auto-fix | Re-trigger cubic
| const workflow = await start(catalogStreamsWorkflow, [run.id]); | ||
| return { state: "started" as const, run_id: run.id, workflow_run_id: workflow.runId }; | ||
| } catch { | ||
| await updateCatalogStreamRun(run.id, "failed", "workflow_start_failed"); |
There was a problem hiding this comment.
P2: A transient workflow-start failure consumes the catalog’s only daily claim, so a later refresh or dispatcher retry that day cannot start collection. Add a recovery path that makes failed starts retryable without creating duplicate workflows.
Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. When an issue isn't valid or won't be fixed in this PR, reply in its thread with the reason and then resolve the thread. At lib/catalog/startCatalogStreamRun.ts, line 19:
<comment>A transient workflow-start failure consumes the catalog’s only daily claim, so a later `refresh` or dispatcher retry that day cannot start collection. Add a recovery path that makes failed starts retryable without creating duplicate workflows.</comment>
<file context>
@@ -0,0 +1,22 @@
+ const workflow = await start(catalogStreamsWorkflow, [run.id]);
+ return { state: "started" as const, run_id: run.id, workflow_run_id: workflow.runId };
+ } catch {
+ await updateCatalogStreamRun(run.id, "failed", "workflow_start_failed");
+ throw new Error("Unable to start catalog stream collection");
+ }
</file context>
| action === "disable" || (action === "enable" && !existing?.enabled) | ||
| ? await upsertCatalogStreamTracking({ | ||
| catalog_id: catalogId, | ||
| owner_id: link.account, |
There was a problem hiding this comment.
P2: selectAccountCatalog can return an arbitrary matching owner, but assertCatalogStreamRunActive later requires this exact owner_id. If that link is removed while another accessible link remains, runs are revoked and repeated enable cannot rebind the enabled row; resolve a stable owner or validate against all current owners.
Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. When an issue isn't valid or won't be fixed in this PR, reply in its thread with the reason and then resolve the thread. At lib/catalog/manageCatalogStreamTracking.ts, line 29:
<comment>`selectAccountCatalog` can return an arbitrary matching owner, but `assertCatalogStreamRunActive` later requires this exact `owner_id`. If that link is removed while another accessible link remains, runs are revoked and repeated enable cannot rebind the enabled row; resolve a stable owner or validate against all current owners.</comment>
<file context>
@@ -0,0 +1,49 @@
+ action === "disable" || (action === "enable" && !existing?.enabled)
+ ? await upsertCatalogStreamTracking({
+ catalog_id: catalogId,
+ owner_id: link.account,
+ enabled: action === "enable",
+ })
</file context>
| const date = new Date(`${value}T00:00:00Z`); | ||
| return Number.isFinite(date.getTime()) && date.toISOString().slice(0, 10) === value; | ||
| }, "since must be a valid UTC date"), | ||
| days: z.coerce.number().int().min(1).max(31), |
There was a problem hiding this comment.
P3: z.coerce.number() converts JSON true to 1, so MCP callers can pass booleans for days, page, or limit and have them silently accepted as numeric values. Coerce numeric strings only and reject other input types.
Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. When an issue isn't valid or won't be fixed in this PR, reply in its thread with the reason and then resolve the thread. At lib/catalog/validateCatalogPlaycountHistoryQuery.ts, line 13:
<comment>`z.coerce.number()` converts JSON `true` to `1`, so MCP callers can pass booleans for `days`, `page`, or `limit` and have them silently accepted as numeric values. Coerce numeric strings only and reject other input types.</comment>
<file context>
@@ -0,0 +1,23 @@
+ const date = new Date(`${value}T00:00:00Z`);
+ return Number.isFinite(date.getTime()) && date.toISOString().slice(0, 10) === value;
+ }, "since must be a valid UTC date"),
+ days: z.coerce.number().int().min(1).max(31),
+ page: z.coerce.number().int().min(1).max(1_000_000).default(1),
+ limit: z.coerce.number().int().min(1).max(25).default(25),
</file context>
| failed++; | ||
| } | ||
| } | ||
| return { next: page.length === 100 ? page[99].catalog_id : null, failed }; |
There was a problem hiding this comment.
P3: The hardcoded 100/99 cursor math here must stay in sync with the .limit(100) inside selectEnabledCatalogStreamTracking (a different file). Raising or lowering that limit silently shifts the cursor to the wrong row and either skips or re-dispatches subscriptions. The same cross-file magic-number coupling applies to 62 in fetchCatalogStreamTrackStep (vs. the 61-day span refine in luminateStreamRequestSchema) and 250 in prepareCatalogStreamRunStep. Extract these limits as shared constants (e.g. lib/const.ts) so the cursor and page size cannot drift apart.
Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. When an issue isn't valid or won't be fixed in this PR, reply in its thread with the reason and then resolve the thread. At app/workflows/dispatchCatalogStreamsStep.ts, line 15:
<comment>The hardcoded `100`/`99` cursor math here must stay in sync with the `.limit(100)` inside `selectEnabledCatalogStreamTracking` (a different file). Raising or lowering that limit silently shifts the cursor to the wrong row and either skips or re-dispatches subscriptions. The same cross-file magic-number coupling applies to `62` in `fetchCatalogStreamTrackStep` (vs. the 61-day span refine in `luminateStreamRequestSchema`) and `250` in `prepareCatalogStreamRunStep`. Extract these limits as shared constants (e.g. `lib/const.ts`) so the cursor and page size cannot drift apart.</comment>
<file context>
@@ -0,0 +1,16 @@
+ failed++;
+ }
+ }
+ return { next: page.length === 100 ? page[99].catalog_id : null, failed };
+}
</file context>
| .from("catalog_stream_runs") | ||
| .select("*") | ||
| .eq("catalog_id", catalogId) | ||
| .order("created_at", { ascending: false }) |
There was a problem hiding this comment.
P3: This capped newest-row query orders only by created_at, so two runs created in the same database transaction time (a cron sweep can claim several catalogs back-to-back) resolve nondeterministically, and getCatalogStreams/manageCatalogStreamTracking can surface either run as "latest". Append .order("id", { ascending: false }) after the timestamp order to make ties stable, matching the tie-break pattern used for the other capped latest-row selectors.
Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. When an issue isn't valid or won't be fixed in this PR, reply in its thread with the reason and then resolve the thread. At lib/supabase/catalog_stream_runs/selectLatestCatalogStreamRun.ts, line 8:
<comment>This capped newest-row query orders only by `created_at`, so two runs created in the same database transaction time (a cron sweep can claim several catalogs back-to-back) resolve nondeterministically, and `getCatalogStreams`/`manageCatalogStreamTracking` can surface either run as "latest". Append `.order("id", { ascending: false })` after the timestamp order to make ties stable, matching the tie-break pattern used for the other capped latest-row selectors.</comment>
<file context>
@@ -0,0 +1,13 @@
+ .from("catalog_stream_runs")
+ .select("*")
+ .eq("catalog_id", catalogId)
+ .order("created_at", { ascending: false })
+ .limit(1)
+ .maybeSingle();
</file context>
| .order("created_at", { ascending: false }) | |
| .order("created_at", { ascending: false }) | |
| .order("id", { ascending: false }) |
| * Caller must select one verified provider identity, scope and export version first. | ||
| * Calendar completeness does not prove provider freshness or full catalog coverage. | ||
| */ | ||
| export function compareSpotifyDailyStreams( |
There was a problem hiding this comment.
P3: The exported name compareSpotifyDailyStreams advertises Spotify, but the only consumer is the Luminate read path and the function is generic date-summing. Rename it (e.g., compareCatalogDailyStreams, which also matches compareCatalogPlaycountHistory naming) so the contract doesn't mislead future callers.
Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. When an issue isn't valid or won't be fixed in this PR, reply in its thread with the reason and then resolve the thread. At lib/catalog/compareSpotifyDailyStreams.ts, line 13:
<comment>The exported name `compareSpotifyDailyStreams` advertises Spotify, but the only consumer is the Luminate read path and the function is generic date-summing. Rename it (e.g., `compareCatalogDailyStreams`, which also matches `compareCatalogPlaycountHistory` naming) so the contract doesn't mislead future callers.</comment>
<file context>
@@ -0,0 +1,55 @@
+ * Caller must select one verified provider identity, scope and export version first.
+ * Calendar completeness does not prove provider freshness or full catalog coverage.
+ */
+export function compareSpotifyDailyStreams(
+ rows: { date: string; streams: number }[],
+ query: { since: string; days: number },
</file context>
There was a problem hiding this comment.
3 existing issues remain and 4 new issues found across 32 files (changes from recent commits).
Confidence score: 3/5
- In
fetchLuminateStreams.ts, transient response-body read failures becomeFatalError, so configured retries are skipped and coverage can be lost. Preserve non-validation read errors so they can be retried. - In
checkLuminateRecordingResponse.ts, a rejectedcancel()can prevent 429/5xx responses from being classified as retryable. Make cancellation best-effort so the HTTP status still controls classification. checkLuminateRecordingResponse.tstreats date-formRetry-Aftervalues as invalid and falls back to a 60-second delay. Parse HTTP dates into a delay before applying the existing cap.- The redacted 503 handlers in
catalogStreamsHandler.ts,startCatalogStreamRun.ts,catalog-stream-maintenance/route.ts, andgetCatalogPlaycountHistoryHandler.tsdiscard exception details, making failures harder to diagnose. Capture and log the errors while keeping responses redacted.
Prompt for AI agents (unresolved issues)
Check if these issues are valid — if so, understand the root cause of each and fix them. When an issue isn't valid or won't be fixed in this PR, reply in its thread with the reason and then resolve the thread. If appropriate, use sub-agents to investigate and fix each issue separately.
<file name="lib/luminate/fetchLuminateStreams.ts">
<violation number="1" location="lib/luminate/fetchLuminateStreams.ts:50">
P2: A transient response-body read failure is caught here and converted to `FatalError`, so the fetch step skips its configured retries and records a coverage gap. Preserve non-validation read errors instead of converting every exception to a fatal invalid-data error.</violation>
</file>
<file name="lib/luminate/checkLuminateRecordingResponse.ts">
<violation number="1" location="lib/luminate/checkLuminateRecordingResponse.ts:5">
P2: A failed `cancel()` rejects before the status check, so an errored 429/5xx response bypasses `RetryableError` and becomes a failed track. Make cancellation best-effort so the HTTP status still controls classification.</violation>
<violation number="2" location="lib/luminate/checkLuminateRecordingResponse.ts:8">
P2: `Retry-After` also permits an HTTP-date, but `Number()` turns that form into `NaN` and the next line retries after 60 seconds. Parse date-valued headers into a delay before applying the existing cap.</violation>
</file>
<file name="lib/catalog/startCatalogStreamRun.ts">
<violation number="1" location="lib/catalog/startCatalogStreamRun.ts:19">
P2: This log drops the workflow-start error, leaving only a generic message and making failures difficult to diagnose. Capture the caught error and include it in `console.error`.
(Based on your team's feedback about retaining server-side error diagnostics.)</violation>
</file>
Requires human review: Auto-approval blocked because this review re-detected 3 unresolved issues already reported by Cubic.
View guided diff | Turn on auto-fix | Re-trigger cubic
| if (!(await checkLuminateRecordingResponse(response))) return null; | ||
| try { | ||
| return { | ||
| ...normalizeLuminateStreams(await readLuminateBody(response, 1000000, "Luminate"), request), |
There was a problem hiding this comment.
P2: A transient response-body read failure is caught here and converted to FatalError, so the fetch step skips its configured retries and records a coverage gap. Preserve non-validation read errors instead of converting every exception to a fatal invalid-data error.
Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. When an issue isn't valid or won't be fixed in this PR, reply in its thread with the reason and then resolve the thread. At lib/luminate/fetchLuminateStreams.ts, line 50:
<comment>A transient response-body read failure is caught here and converted to `FatalError`, so the fetch step skips its configured retries and records a coverage gap. Preserve non-validation read errors instead of converting every exception to a fatal invalid-data error.</comment>
<file context>
@@ -42,34 +44,10 @@ export async function fetchLuminateStreams(input: LuminateStreamRequest) {
try {
return {
- ...normalizeLuminateStreams(JSON.parse(Buffer.concat(chunks).toString("utf8")), request),
+ ...normalizeLuminateStreams(await readLuminateBody(response, 1000000, "Luminate"), request),
retrieved_at: new Date().toISOString(),
};
</file context>
| await response.body?.cancel(); | ||
| if (response.status === 404) return false; | ||
| if (response.status === 429 || response.status >= 500) { | ||
| const seconds = Number(response.headers.get("retry-after")); |
There was a problem hiding this comment.
P2: Retry-After also permits an HTTP-date, but Number() turns that form into NaN and the next line retries after 60 seconds. Parse date-valued headers into a delay before applying the existing cap.
Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. When an issue isn't valid or won't be fixed in this PR, reply in its thread with the reason and then resolve the thread. At lib/luminate/checkLuminateRecordingResponse.ts, line 8:
<comment>`Retry-After` also permits an HTTP-date, but `Number()` turns that form into `NaN` and the next line retries after 60 seconds. Parse date-valued headers into a delay before applying the existing cap.</comment>
<file context>
@@ -0,0 +1,14 @@
+ await response.body?.cancel();
+ if (response.status === 404) return false;
+ if (response.status === 429 || response.status >= 500) {
+ const seconds = Number(response.headers.get("retry-after"));
+ throw new RetryableError("Luminate temporarily unavailable", {
+ retryAfter: `${Number.isFinite(seconds) && seconds > 0 ? Math.min(seconds, 300) : 60}s`,
</file context>
| /** Classify status without reading credential-bearing error bodies. */ | ||
| export async function checkLuminateRecordingResponse(response: Response) { | ||
| if (response.ok) return true; | ||
| await response.body?.cancel(); |
There was a problem hiding this comment.
P2: A failed cancel() rejects before the status check, so an errored 429/5xx response bypasses RetryableError and becomes a failed track. Make cancellation best-effort so the HTTP status still controls classification.
Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. When an issue isn't valid or won't be fixed in this PR, reply in its thread with the reason and then resolve the thread. At lib/luminate/checkLuminateRecordingResponse.ts, line 5:
<comment>A failed `cancel()` rejects before the status check, so an errored 429/5xx response bypasses `RetryableError` and becomes a failed track. Make cancellation best-effort so the HTTP status still controls classification.</comment>
<file context>
@@ -0,0 +1,14 @@
+/** Classify status without reading credential-bearing error bodies. */
+export async function checkLuminateRecordingResponse(response: Response) {
+ if (response.ok) return true;
+ await response.body?.cancel();
+ if (response.status === 404) return false;
+ if (response.status === 429 || response.status >= 500) {
</file context>
| await response.body?.cancel(); | |
| await response.body?.cancel().catch(() => {}); |
| const workflow = await start(catalogStreamsWorkflow, [run.id]); | ||
| return { state: "started" as const, run_id: run.id, workflow_run_id: workflow.runId }; | ||
| } catch { | ||
| console.error("[startCatalogStreamRun] operation failed"); |
There was a problem hiding this comment.
P2: This log drops the workflow-start error, leaving only a generic message and making failures difficult to diagnose. Capture the caught error and include it in console.error.
(Based on your team's feedback about retaining server-side error diagnostics.)
Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. When an issue isn't valid or won't be fixed in this PR, reply in its thread with the reason and then resolve the thread. At lib/catalog/startCatalogStreamRun.ts, line 19:
<comment>This log drops the workflow-start error, leaving only a generic message and making failures difficult to diagnose. Capture the caught error and include it in `console.error`.
(Based on your team's feedback about retaining server-side error diagnostics.) </comment>
<file context>
@@ -16,6 +16,7 @@ export async function startCatalogStreamRun(catalogId: string) {
const workflow = await start(catalogStreamsWorkflow, [run.id]);
return { state: "started" as const, run_id: run.id, workflow_run_id: workflow.runId };
} catch {
+ console.error("[startCatalogStreamRun] operation failed");
await updateCatalogStreamRun(run.id, "failed", "workflow_start_failed");
throw new Error("Unable to start catalog stream collection");
</file context>
Catalog stream history currently depends on public cumulative Spotify counters and manual native exports. This adds opt-in Luminate collection by ISRC, a 62-day initial backfill and automatic daily refreshes, with saved calendar-day history and equal-period growth through shared REST/MCP logic.
The integration stores worldwide aggregate streams across reporting DSPs separately from Spotify-only public counters. Missing dates stay unknown, explicit zeros remain zero, identity changes suppress comparisons, and correction versions are retained. Daily refreshes reuse unchanged values while recording fresh coverage/provenance receipts. Controls share a 10/minute account throttle across REST/MCP; reads use bounded parallel SQL queries; temporary, authentication and revocation failures remain distinct. Source retrieval time is separate from unavailable upstream update time.
/api/catalogs/{catalogId}/stream-tracking: enable, pause, refresh and status./api/catalogs/{catalogId}/streams: paginated daily history, coverage and growth.manage_catalog_stream_tracking,get_catalog_streams; delegated OAuth remains hidden/denied.Validation: 266 final focused tests passed (39 files); OAuth regression suite 188 passed/1 skipped; lint passed with two generated-workflow warnings; production webpack build and OAuth bundle trace checks passed; disposable PostgreSQL 17 service-role tests passed. A bounded real adapter probe returned 28 daily observations and the expected aggregate total for a verified low-volume recording. Private source records and credentials are excluded from Git.
Release dependencies: database PR recoupable/database#93 must be applied before this API; docs https://github.com/recoupable/docs/pull/354. Configure server-only LUMINATE_API_KEY, LUMINATE_USERNAME, LUMINATE_PASSWORD and existing CRON_SECRET before activation. The three scoped database migrations are applied and verified in production, with anonymous/browser table access denied. Server-only provider credentials are configured. API merge and production collection are pending final CI. MVP limit: 250 recordings/catalog; source window ends two UTC dates before collection. A failed daily claim is eligible for a new run the next day. Live authenticated readback and actual cron execution remain release checks.
The existing public playcount history and native CSV parser/comparator remain available as separate sources. Tracking issue: recoupable/app#2177.