Skip to content

Encode chargeable social scrape states - #1039

Merged
sidneyswift merged 2 commits into
mainfrom
codex/scrape-chargeable-states
Oct 17, 2026
Merged

sidneyswift merged 2 commits into
mainfrom
codex/scrape-chargeable-states

Conversation

@sidneyswift

@sidneyswift sidneyswift commented Oct 17, 2026 •

Copy link
Copy Markdown
Contributor

Social scrape results currently allow a run ID and failure to coexist, so callers infer chargeability from nullable fields and persistence needs a cast. This change makes attempts explicitly started or failed, bills and registers only started runs, and keeps the existing batch and single-social HTTP response shapes, pricing, and debit ordering. A malformed provider result without a run ID now becomes a failed attempt; unsupported platforms still return null internally.

The regression gate checks both contradictory type examples and the actual constructors/consumers under strict null checks, scoped to the five changed modules. Route fixtures exercise the real POST exports through dispatch and the deduction wrapper with synthetic accounts, providers, and persistence. The full-report parse-failure check also identifies the failed section's runtime and verifies it is never charged. lib/apify/README.md records entry routes, expectations, and fixture limits.

Known pre-existing redaction follow-up: Cubic's P2 finding identifies raw provider exception text in the public response. In both baseline 067238da and this PR, scrapeProfileUrl copies error.message, the artist batch serializes that error, and the single-social handler returns it. These unchanged paths may expose provider or backend details. This structural refactor deliberately preserves existing response behavior; the fixture assertion documents that behavior and does not endorse it as safe. Replacing public exception text with a generic message, retaining diagnostic detail server-side, and updating both endpoint contracts and tests remains a separate, unresolved redaction follow-up.

Validation:

  • Frozen-lockfile dependency install; 37 focused tests passed.
  • Exact-head GitHub CI unit suite passed: 1,187 files passed, 11 skipped; 6,440 tests passed, 13 skipped. CI format, lint, and MCP OAuth compatibility also passed.
  • Repository lint, changed-file formatting, and git diff --check passed.
  • Deliberate duplicate debit, widened started/error type, and actual started constructor with runId: null each failed the relevant regression gate; mutations restored.
  • Full TypeScript check has the same 196 pre-existing diagnostics as clean main 067238da with matching locked dependencies; no new diagnostics. The focused strict-null gate passes.

Local commands ran on Node 23.6.1; CI uses its configured runtime. Fixture checks make no provider requests or real charges and do not verify deployed HTTP authentication or account balances.

@vercel

vercel Bot commented Oct 17, 2026 •

Copy link
Copy Markdown
Contributor

The latest updates on your projects. Learn more about Vercel for GitHub.

Project Deployment Actions Updated
api Ready Ready Preview Oct 17, 2026 12:40am UTC

Request Review

@coderabbitai

coderabbitai Bot commented Oct 17, 2026

Copy link
Copy Markdown

Important

  • 🔍 Trigger review

This repository does not receive automatic reviews because it has fewer than 10 stars.

⚙️ Run configuration
  • Configuration used: Repository: recoupable/api/.coderabbit.yaml
  • Review profile: CHILL
  • Plan: Advanced
  • Run ID: d2e2d6e6-f58a-4835-aecf-83a79c4204b4
  • Autofix · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts

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.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

@cubic-dev-ai cubic-dev-ai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

1 issue found across 13 files

Confidence score: 3/5

  • The batch response can expose raw provider or backend exception details to API clients, and this test locks that behavior in (lib/apify/__tests__/socialScrapeBillingRoutes.test.ts). Return a generic failure message and update the production error path.
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/apify/__tests__/socialScrapeBillingRoutes.test.ts">

<violation number="1" location="lib/apify/__tests__/socialScrapeBillingRoutes.test.ts:127">
P2: This assertion locks raw provider exception text into the public batch response. Require a generic failure message and update the production error path so provider or backend details are never returned to API clients.

(Based on your team's feedback about redacting internal error details.)</violation>
</file>
Architecture diagram
sequenceDiagram
    participant HTTP as HTTP Client
    participant Artist as Artist Scrape Route
    participant Single as Single Social Route
    participant Auth as Auth Validation
    participant Batch as scrapeProfileUrlBatch
    participant SingleScrape as scrapeProfileUrl
    participant Providers as Platform Providers
    participant Deduct as deductSocialScrapeCredits
    participant Credits as ensureSocialScrapeCredits
    participant Runs as upsertApifyScraperRuns
    participant DB as Supabase

    Note over HTTP,DB: Social Scrape Billing Flow - Discriminated Attempt States

    alt POST /api/artist/socials/scrape (batch)
        HTTP->>Artist: POST with artist_account_id + optional posts
        Artist->>Auth: validateAuthContext()
        Auth-->>Artist: accountId + authToken
        Artist->>Artist: checkAccountArtistAccess()
        Artist->>Artist: selectAccountSocials() for artist
        Artist->>Batch: scrapeProfileUrlBatch(profiles, posts)
        Batch->>SingleScrape: scrapeProfileUrl() per profile
        SingleScrape->>Providers: startXProfileScraping(username, posts)
        
        alt Provider returns valid runInfo
            Providers-->>SingleScrape: { runId, datasetId }
            SingleScrape-->>Batch: { state: "started", runId, datasetId }
        else Provider returns null or missing runId
            Providers-->>SingleScrape: null/{ runId: "" }
            SingleScrape-->>Batch: { state: "failed", error: "Failed to start scrape" }
        else Provider throws
            Providers--xSingleScrape: Error
            SingleScrape-->>Batch: { state: "failed", error: message }
        end
        
        alt Platform unsupported
            SingleScrape-->>Batch: null (filtered out)
        end
        
        Batch-->>Artist: started/failed results with profileUrl
        Artist->>Artist: Filter state === "started"
        
        alt At least one started run
            Artist->>Credits: ensureSocialScrapeCredits(accountId, totalCost)
            Credits-->>Artist: null (sufficient)
            Artist->>Deduct: deductSocialScrapeCredits(accountId, startedCount * cost)
            Deduct-->>Artist: success
            Artist->>Runs: upsertApifyScraperRuns(started runs only)
            Runs->>DB: INSERT run records
            Artist-->>HTTP: 200 [{ runId, datasetId, error }]
        else All runs failed
            Artist-->>HTTP: 200 [{ runId: null, datasetId: null, error }]
        end
        
    else POST /api/socials/{id}/scrape (single)
        HTTP->>Single: POST with posts query param
        Single->>Auth: validateAuthContext()
        Auth-->>Single: accountId + authToken
        Single->>Single: checkAccountArtistAccess()
        Single->>Single: selectSocials() for social id
        Single->>SingleScrape: scrapeProfileUrl(profileUrl, username, posts)
        SingleScrape->>Providers: startXProfileScraping(username, posts)
        
        alt Provider returns valid runInfo
            Providers-->>SingleScrape: { runId, datasetId }
            SingleScrape-->>Single: { state: "started", runId, datasetId }
            Single->>Deduct: deductSocialScrapeCredits(accountId, cost)
            Single->>Runs: registerRootApifyRun({ runId })
            Runs->>DB: INSERT run record
            Single-->>HTTP: 200 { runId, datasetId }
        else Provider returns null or throws
            Providers-->>SingleScrape: null/Error
            SingleScrape-->>Single: { state: "failed", error }
            Single-->>HTTP: 500 { status: "error", error }
        end
    end
Loading

Reply with feedback, questions, or to request a fix.

View guided diff | Turn on auto-fix | Re-trigger cubic

expect(response.status).toBe(200);
expect(await response.json()).toEqual([
{ runId: null, datasetId: null, error: "Failed to start scrape" },
{ runId: null, datasetId: null, error: "Provider unavailable" },

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2: This assertion locks raw provider exception text into the public batch response. Require a generic failure message and update the production error path so provider or backend details are never returned to API clients.

(Based on your team's feedback about redacting internal error details.)

View Feedback

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/apify/__tests__/socialScrapeBillingRoutes.test.ts, line 127:

<comment>This assertion locks raw provider exception text into the public batch response. Require a generic failure message and update the production error path so provider or backend details are never returned to API clients.

(Based on your team's feedback about redacting internal error details.) </comment>

<file context>
@@ -0,0 +1,177 @@
+    expect(response.status).toBe(200);
+    expect(await response.json()).toEqual([
+      { runId: null, datasetId: null, error: "Failed to start scrape" },
+      { runId: null, datasetId: null, error: "Provider unavailable" },
+      { runId: null, datasetId: null, error: "Failed to start scrape" },
+    ]);
</file context>

This branch was successfully deployed

1 active deployment
Preview — d11e996e Deployed Oct 17, 2026 by vercel[bot]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant