# Architecture Documentation

Tobuzz Extractor is built as a stateless, high-performance media resolver designed for Cloudflare Workers edge execution with native `nodejs_compat` runtime support. It implements a provider-agnostic extraction and preflight media validation pipeline.

---

## Data Flow Pipeline

```
                     Client Request
             (GET /api/resolve/533535)
                         │
                         ▼
             Cloudflare Worker Handler
                  (src/worker.ts)
                         │
                         ▼
         Request Parser & Provider Filter
               (src/core/request.ts)
                         │
                         ▼
     Resolution Cache (KV / In-Memory Deduplication)
                (src/core/cache.ts)
                         │
                         ▼
      Provider Priority & Fallback Orchestration
               (src/core/resolver.ts)
                         │
         ┌───────────────┼───────────────┐
         ▼               ▼               ▼
      VidNest         Vidsrc.su       Vidsrc.to
   (Priority 1)     (Priority 2)    (Priority 3)
 (src/providers/ (src/providers/ (src/providers/
     vidnest)        vidsrcsu)       vidsrcto)
         │               │               │
         └───────────────┼───────────────┘
                         │
                         ▼
             Candidate Discovery
                         │
                         ▼
            Candidate Ranking & Filtering
             (Progressive > HLS > DASH)
                         │
                         ▼
            Preflight Media Validation
             (src/core/validation.ts)
                         │
                         ▼
             Proxy & URL Rewriting
             (src/core/proxy.ts)
                         │
                         ▼
            Normalized Playable Source
           (Cloudflare Worker JSON Response)
```

---

## Core Architectural Modules

### 1. Edge Entry Point & Request Routing (`src/worker.ts`, `src/core/request.ts`)
- **Cloudflare Worker Fetch**: Dispatches requests for `/api/health`, `/api/resolve/*`, and `/api/media-proxy` using standard Web `Request`/`Response` APIs.
- **Parameter Normalization**: `parseResolveParams` handles path segment parsing (`/api/resolve/{tmdbId}` and `/api/resolve/{tmdbId}/{season}/{episode}`).
- **Provider Filtering**: Parses query parameters (`only`, `provider`, `providers`, `exclude`) to select candidate providers from `ProviderRegistry`.

### 2. Provider Registry & Isolation (`src/providers/registry.ts`, `src/core/provider.ts`)
- Every provider implements the unified `MediaProvider` interface:
  ```typescript
  export interface MediaProvider {
    readonly id: string;
    readonly displayName: string;
    resolve(request: MediaRequest, context: ResolveContext): Promise<PlayableSource>;
  }
  ```
- **Registered Providers**:
  - `vidnest`: Multi-server API provider with Base64 alphabet payload decryption and audio language preference ranking.
  - `vidsrcsu`: HMAC request signing with WebAssembly (`wasm`) payload decryption against `themoviedb.vidsrc.su`.
  - `vidsrcto`: Embedded player navigation (`cloudorchestranova.com`), WebAssembly ChaCha20 cipher decryption, stream host token fetching (`/generate.php`), and proxy unwrapping.
- **Provider Isolation Principle**: Custom Base64 alphabets, WebAssembly binaries, iframe regexes, and endpoint path schemas live strictly inside provider directories (`src/providers/<provider>/`) and never leak into core orchestration.

### 3. Orchestration Engine (`src/core/resolver.ts`)
- Iterates through selected providers sequentially.
- Enforces request-wide timeouts and captures individual provider execution timing (`durationMs`) and error details.
- Returns a standardized `ResolveResult` object.

### 4. Media Preflight Validation Engine (`src/core/validation.ts`)
- **Unwrapping Proxied Sources**: If a candidate URL uses `/api/media-proxy`, `unwrapProxiedSource` extracts the target URL and referer to validate the underlying upstream stream.
- **Deep HLS Validation**:
  - Checks master playlist structure (`#EXTM3U`, `#EXT-X-STREAM-INF`).
  - Fetches first variant media playlist.
  - Validates segment reachability (`#EXTINF`) using bounded HTTP GET requests.
  - Validates key reachability (`#EXT-X-KEY`) for encrypted streams.
  - Rejects HTML error pages, 401/403 IP block responses, and fake playlists.
- **Candidate Ranking**: Ranks progressive MP4 > HLS > DASH > other.

### 5. Media Proxy & Playlist Rewriter (`src/worker.ts`, `src/core/proxy.ts`)
- Proxies playlist manifests and segments under edge worker egress IP.
- Rewrites relative and absolute URIs in HLS playlists (`.m3u8`) to route segment and key requests back through `/api/media-proxy`.
- Dynamically resolves stream host authorization tokens (`__TOKEN__` placeholders) using in-memory cached token fetching (`getOrFetchProxyToken`).
- Enforces SSRF security bounds (`isApprovedMediaHost`).

---

## Edge Runtime Guarantees & Constraints

- **Stateless & Scalable Execution**: Every request runs in an isolated V8 isolate. Distributed caching is supported through Cloudflare KV namespaces (`CACHE_KV`).
- **No Headless Browsers**: Puppeteer, Playwright, or heavy browser binaries are not required. Extraction relies on lightweight HTTP requests, string regex parsing, and WebAssembly / WebCrypto engines.
- **Bounded Resources**: Upstream HTTP requests use tight timeouts (`fetchWithTimeout`). Total pipeline resolution execution budget is strictly capped at 8.5s (`DEFAULT_TOTAL_BUDGET_MS`), guaranteeing structured JSON responses without gateway timeouts.

