跳到正文
DEV Community· yang rocky·· 4 小時前AI 評分49

Make Me Rap 如何以關鍵影格預覽實現 AI 影片先看後付

Pay-After-Keyframe AI Video Rendering on Cloudflare Workers, D1, R2, and Containers

AI 導讀

Make Me Rap 採用 Cloudflare Workers、D1、私有 R2 儲存空間及 Cloudflare Container,將結帳與狀態管理和長時間影片生成分開,並以已儲存的外部請求 ID 避免逾時後重複提交 GPU 渲染。用戶可先免費查看關鍵影格預覽,確認畫面後才結帳;成品須通過安全及媒體檢查,永久失敗時則自動退款。

正文

When you run an AI video generation app on the edge, two failure modes destroy your margins fast: charging a user before they know whether the visual result looks right, and accidentally double-submitting an expensive GPU render when a webhook or polling request times out.

When we built Make Me Rap — a browser studio that turns a user's photo, theme, outfit, scene, and voice choice into a full 768p lip-synced rap music video — we chose a split Cloudflare architecture: a Cloudflare Worker (running React / Next.js App Router on Vite) backed by D1 and private R2 buckets for all auth, checkout, and state transitions, paired with a dedicated Cloudflare Container render coordinator that claims paid jobs and orchestrates long-running video generation.

Here are the four concrete architecture patterns that kept our checkout, moderation, and GPU rendering pipeline deterministic and leak-free.


1. Split Edge Control Plane vs. Container Render Plane

Cloudflare Workers excel at fast SSR, OAuth/session validation, D1 transactions, and PayPal checkout webhooks — not holding open long-lived video rendering connections or polling upstream video models for 60+ seconds.

Instead of cramming render loops into ctx.waitUntil(), we split responsibilities cleanly:

Browser
  └──> Cloudflare Worker (SSR, Auth, D1 state machine, R2 presigned/private IO, PayPal Orders v2)
            ├── D1: users, sessions, jobs, billing_checkouts, payment_events, workers
            ├── R2 (private): uploaded photos, template masters, finished MP4s
            └── Worker API (/api/worker/ready, /claim, /jobs)
                     ▲
                     │ periodic heartbeat + atomic claim
Cloudflare Container (render coordinator)
  └── swaps vocal track -> submits ONCE to upstream video model -> validates output -> uploads to R2

Two small details made the Worker ↔ Container boundary rock solid:

  • Capability-based heartbeats (ready levels): The container continuously reports a ready capability tier into D1's workers table. Before accepting a checkout for a new template combination, the edge Worker checks for a fresh heartbeat matching the required capability level — preventing users from paying when the render container is restarting or degraded.
  • Strictly single-submit upstream job tracking: When the container submits a render job to an upstream video generation API, it persists the external request ID immediately. If a network read times out, the worker only polls the saved request ID and never re-submits a second billable GPU render.

2. Pay-After-Keyframe: Free Preview Before Checkout

Asking users to pay blind for AI video often leads to refund disputes when the lighting, crop, or outfit doesn't match expectations. Conversely, running a full 15-second video render for every anonymous visitor destroys unit economics.

Our middle ground in Make Me Rap is pay_after_keyframe:

  1. The user chooses a rap theme, outfit, scene, and voice, then uploads a photo.
  2. Every uploaded image runs through automated safety moderation first (MODERATION_REQUIRED=true in production; any moderation error fails closed rather than silently bypassing).
  3. We generate a free visual keyframe preview so the user sees the exact framing and look before spending a dollar.
  4. Only after approving the preview does the order page open checkout (Apple Pay, Google Pay, PayPal, and cards — see Make Me Rap Pricing).

3. Server-Authoritative Checkout & Capture Idempotency

Never trust client-supplied prices or treat a front-end onApprove callback as the sole source of truth:

  • Server-side pricing table: When /api/billing/checkout creates a PayPal Orders v2 checkout, it reads the price solely from server-side configuration (PRICING_JSON), binds the checkout row to the authenticated user_id and job_id, and stores the order state in billing_checkouts.
  • Ownership + amount verification before capture: Before /api/billing/capture captures funds, it verifies both job ownership and exact order amount against D1, incrementing capture_attempts and recording structured refusal diagnostics (failure_issue, failure_debug_id) if an issuer declines the transaction.
  • Webhook deduplication: Incoming PayPal webhooks are deduplicated by event ID in payment_events so duplicate retries never double-queue a render job.
  • Client-side checkout telemetry: Browser wallet popups (Apple Pay / Google Pay / PayPal) can fail before ever hitting /capture. Logging lightweight interrupted-checkout events (method, stage, code) to a 90-day payment_client_events table made diagnosing wallet friction dramatically easier than guessing from server logs alone.

4. Fail-Closed Post-Render Checks & Automatic Refunds

Once the render container produces an MP4:

  1. It runs frame-sampled safety checks plus technical media validation (codec, duration, audio stream integrity) before marking the job deliverable in private R2 storage.
  2. If an external moderation check hits a transient upstream outage, the job enters a 15-minute recovery window so temporary blips self-heal instead of killing a completed render.
  3. If a job permanently fails (or exceeds the recovery window), the billing layer triggers an automatic refund rather than leaving a paid user stuck in a "Processing…" spinner.

Takeaways for Edge + AI Video Builders

  • Keep state, pricing, auth, and idempotency keys in your relational edge database (D1) — never in memory inside a container or browser callback.
  • Persist every external GPU request ID before waiting on completion so timeouts always resolve via polling, never duplicate billing.
  • Separate cheap visual verification (keyframe) from expensive full-motion rendering, and let users see the keyframe before paying.

If you want to see the end-to-end flow live in the browser, you can try a free preview on Make Me Rap.

來源:DEV Community · dev.to