# CDN Integration Guide

This document provides comprehensive documentation for the Lilith Media Service
CDN integration with AWS CloudFront, including signed URLs, cache invalidation,
and content delivery optimization.

## Overview

The CDN Integration provides:

- **CloudFront Distribution**: Managed CloudFront client with AWS SDK
- **Signed URLs**: Time-limited access to protected content
- **Signed Cookies**: Multi-resource access for streaming
- **Cache Invalidation**: Path-based and wildcard invalidation
- **Cache Control**: Preset cache policies for different content types
- **Geo-Restriction**: Whitelist/blacklist based content access
- **Range Requests**: Optimal chunking for streaming media

---

## Table of Contents

1. [Configuration](#configuration)
2. [Signed URL Generation](#signed-url-generation)
3. [Signed Cookies](#signed-cookies)
4. [Cache Invalidation](#cache-invalidation)
5. [Cache Control](#cache-control)
6. [CDN URL Utilities](#cdn-url-utilities)
7. [Geo-Restriction](#geo-restriction)
8. [Range Requests](#range-requests)
9. [Error Handling](#error-handling)
10. [SDK Integration](#sdk-integration)

---

## Configuration

### Environment Variables

| Variable                     | Required | Description                                          |
| ---------------------------- | -------- | ---------------------------------------------------- |
| `CLOUDFRONT_DISTRIBUTION_ID` | Yes      | CloudFront distribution ID                           |
| `CLOUDFRONT_DOMAIN_NAME`     | Yes      | CloudFront domain (e.g., `d1234abcd.cloudfront.net`) |
| `CLOUDFRONT_KEY_PAIR_ID`     | Yes      | Key pair ID for signed URLs                          |
| `CLOUDFRONT_PRIVATE_KEY`     | Yes      | RSA private key (PEM format)                         |
| `AWS_REGION`                 | No       | AWS region (default: `us-east-1`)                    |

### CloudFront Config Interface

```typescript
interface CloudFrontConfig {
  distributionId: string;
  domainName: string;
  keyPairId: string;
  privateKey: string;
  region?: string;
  defaultTtlSeconds?: number; // Default: 3600 (1 hour)
}
```

### Creating the Client

```typescript
import { CloudFrontCDNClient, createCloudFrontClient } from '@lilith/media/cdn';

// From environment variables
const cdn = createCloudFrontClient();

// With explicit configuration
const cdn = new CloudFrontCDNClient({
  distributionId: 'EDFDVBD6EXAMPLE',
  domainName: 'd1234abcd.cloudfront.net',
  keyPairId: 'K2JCJMDEHXQW5F',
  privateKey:
    '-----BEGIN RSA PRIVATE KEY-----\n...\n-----END RSA PRIVATE KEY-----',
  defaultTtlSeconds: 3600,
});
```

### Get Configuration

```typescript
const config = cdn.getConfig();
// Returns: { distributionId, domainName, keyPairId, defaultTtlSeconds }
```

---

## Signed URL Generation

### Signed URL Options

```typescript
interface SignedUrlOptions {
  expiresIn?: number; // Seconds from now
  expiresAt?: Date; // Absolute expiration
  ipAddress?: string; // IP restriction (CIDR notation)
  dateGreaterThan?: Date; // URL not valid before this date
}
```

### Basic Signed URL

```typescript
const result = cdn.generateSignedUrl('/media/video/123.mp4', {
  expiresIn: 3600, // 1 hour
});

// Returns:
interface SignedUrlResult {
  url: string; // Full signed URL
  expiresAt: Date; // Expiration timestamp
  policy?: string; // Policy JSON (for custom policies)
}
```

### Signed URL with Custom Policy

For advanced restrictions (IP, time windows):

```typescript
const result = cdn.generateSignedUrlWithPolicy('/media/video/123.mp4', {
  expiresIn: 3600,
  ipAddress: '192.168.1.0/24', // Restrict to subnet
  dateGreaterThan: new Date(), // Not valid before now
});
```

### Wildcard Signed URL

For accessing multiple resources under a path:

```typescript
// Sign all files under /media/course_123/
const result = cdn.generateWildcardSignedUrl('/media/course_123/*', {
  expiresIn: 7200, // 2 hours
});
```

### Build Resource URL

```typescript
const url = cdn.buildResourceUrl('/media/video/123.mp4');
// Returns: https://d1234abcd.cloudfront.net/media/video/123.mp4
```

---

## Signed Cookies

Use signed cookies when users need access to multiple private files (e.g., HLS
streaming with multiple segments).

### Signed Cookie Options

```typescript
interface SignedCookieOptions extends SignedUrlOptions {
  path?: string; // Cookie path (default: '/')
  domain?: string; // Cookie domain
  secure?: boolean; // HTTPS only (default: true)
  httpOnly?: boolean; // HTTP only (default: true)
  sameSite?: 'Strict' | 'Lax' | 'None'; // SameSite (default: 'Lax')
}
```

### Generate Signed Cookies

```typescript
const result = cdn.generateSignedCookies('/media/course_123/*', {
  expiresIn: 7200,
  path: '/',
  domain: '.example.com',
  secure: true,
  httpOnly: true,
  sameSite: 'Lax',
});

// Returns:
interface SignedCookiesResult {
  cookies: {
    'CloudFront-Policy': string;
    'CloudFront-Signature': string;
    'CloudFront-Key-Pair-Id': string;
  };
  expiresAt: Date;
  cookieOptions: {
    path: string;
    domain?: string;
    secure: boolean;
    httpOnly: boolean;
    sameSite: string;
    expires: Date;
  };
}
```

### Setting Cookies in Response

```typescript
// Express/Fastify example
const { cookies, cookieOptions } = cdn.generateSignedCookies('/media/*', {
  expiresIn: 3600,
});

for (const [name, value] of Object.entries(cookies)) {
  reply.setCookie(name, value, {
    path: cookieOptions.path,
    domain: cookieOptions.domain,
    secure: cookieOptions.secure,
    httpOnly: cookieOptions.httpOnly,
    sameSite: cookieOptions.sameSite,
    expires: cookieOptions.expires,
  });
}
```

### Signed Cookies with Custom Policy

```typescript
const result = cdn.generateSignedCookiesWithPolicy('/media/premium/*', {
  expiresIn: 7200,
  ipAddress: '10.0.0.0/8', // Internal network only
});
```

---

## Cache Invalidation

### Invalidation Options

```typescript
interface InvalidationOptions {
  paths: string[];
  callerReference?: string; // Auto-generated if not provided
}
```

### Invalidate Specific Paths

```typescript
const result = await cdn.invalidate({
  paths: ['/media/video/123.mp4', '/media/thumbnails/123/*'],
});

// Returns:
interface InvalidationResult {
  id: string;
  status: string; // 'InProgress' | 'Completed'
  createTime?: Date;
  paths: string[];
}
```

### Invalidate Single Path

```typescript
const result = await cdn.invalidatePath('/media/video/123.mp4');
```

### Invalidate Multiple Paths

Automatically optimizes to use wildcards when beneficial:

```typescript
const result = await cdn.invalidatePaths([
  '/media/course_123/segment_001.ts',
  '/media/course_123/segment_002.ts',
  '/media/course_123/segment_003.ts',
  '/media/course_123/segment_004.ts',
  '/media/course_123/segment_005.ts',
  '/media/course_123/segment_006.ts',
]);
// Optimized to: /media/course_123/*
```

### Invalidate All Content

```typescript
// Use sparingly - expensive operation
const result = await cdn.invalidateAll();
// Invalidates: /*
```

### Check Invalidation Status

```typescript
const status = await cdn.getInvalidationStatus('I3GEXAMPLE');
// Returns: InvalidationResult | null
```

### Wait for Invalidation

```typescript
const completed = await cdn.waitForInvalidation('I3GEXAMPLE', 300000);
// Polls every 2 seconds, max wait 5 minutes (default)
```

### List Recent Invalidations

```typescript
const invalidations = await cdn.listInvalidations(10);
// Returns: InvalidationResult[]
```

### Constants

```typescript
const CLOUDFRONT_DEFAULTS = {
  defaultTtlSeconds: 3600, // 1 hour
  maxInvalidationPaths: 3000, // AWS limit
  invalidationStatusPollIntervalMs: 2000,
  invalidationMaxWaitMs: 300000, // 5 minutes
};
```

---

## Cache Control

### Cache Control Options

```typescript
interface CacheControlOptions {
  maxAge?: number; // Browser cache (seconds)
  sMaxAge?: number; // CDN cache (s-maxage)
  staleWhileRevalidate?: number; // Serve stale while fetching
  staleIfError?: number; // Serve stale on origin error
  mustRevalidate?: boolean;
  noCache?: boolean;
  noStore?: boolean;
  private?: boolean;
  public?: boolean;
  immutable?: boolean;
  noTransform?: boolean;
}
```

### Build Cache-Control Header

```typescript
import { buildCacheControl } from '@lilith/media/cdn';

const header = buildCacheControl({
  public: true,
  maxAge: 86400,
  sMaxAge: 604800,
  staleWhileRevalidate: 86400,
});
// Returns: "public, max-age=86400, s-maxage=604800, stale-while-revalidate=86400"
```

### Parse Cache-Control Header

```typescript
import { parseCacheControl } from '@lilith/media/cdn';

const options = parseCacheControl('public, max-age=3600, s-maxage=86400');
// Returns: { public: true, maxAge: 3600, sMaxAge: 86400 }
```

### Cache Presets

```typescript
import { CACHE_PRESETS } from '@lilith/media/cdn';

// Available presets:
CACHE_PRESETS.immutable; // Static assets (1 year, immutable)
CACHE_PRESETS.versioned; // Versioned assets (1 year)
CACHE_PRESETS.dynamic; // Frequently updated (1 hour + stale-while-revalidate)
CACHE_PRESETS.private; // User-specific (1 minute, private)
CACHE_PRESETS.noCache; // Real-time (no-store)
CACHE_PRESETS.api; // API responses (1 minute browser, 5 minute CDN)
CACHE_PRESETS.media; // Media files (1 day browser, 1 week CDN)
CACHE_PRESETS.hlsSegment; // HLS .ts segments (immutable)
CACHE_PRESETS.hlsManifest; // HLS .m3u8 manifests (2 seconds)
```

### Preset Details

| Preset        | max-age | s-maxage | stale-while-revalidate | Notes                   |
| ------------- | ------- | -------- | ---------------------- | ----------------------- |
| `immutable`   | 1 year  | 1 year   | -                      | immutable flag          |
| `versioned`   | 1 year  | 1 year   | -                      | revalidation allowed    |
| `dynamic`     | 1 hour  | 1 hour   | 1 day                  | stale-if-error: 1 week  |
| `private`     | 1 min   | -        | -                      | must-revalidate         |
| `noCache`     | -       | -        | -                      | no-store                |
| `api`         | 1 min   | 5 min    | 1 min                  | -                       |
| `media`       | 1 day   | 1 week   | 1 day                  | -                       |
| `hlsSegment`  | 1 day   | 1 week   | -                      | immutable, no-transform |
| `hlsManifest` | 2 sec   | 2 sec    | -                      | Low TTL for updates     |

### Get Cache Settings by Content Type

```typescript
import { getCacheSettingsForContentType } from '@lilith/media/cdn';

// Returns appropriate preset based on MIME type
const settings = getCacheSettingsForContentType('video/mp4', true);
// Returns: CACHE_PRESETS.media (or immutable if versioned)

// HLS manifest
getCacheSettingsForContentType('application/vnd.apple.mpegurl');
// Returns: CACHE_PRESETS.hlsManifest

// HLS segment
getCacheSettingsForContentType('video/mp2t');
// Returns: CACHE_PRESETS.hlsSegment

// Images
getCacheSettingsForContentType('image/webp', true);
// Returns: CACHE_PRESETS.immutable
```

---

## CDN URL Utilities

### Build CDN URL

```typescript
import { buildCDNUrl } from '@lilith/media/cdn';

const url = buildCDNUrl('cdn.example.com', '/media/video.mp4', {
  version: 'abc123',
  format: 'webm',
  quality: 80,
  width: 1920,
  height: 1080,
});
// Returns: https://cdn.example.com/media/video.mp4?v=abc123&f=webm&q=80&w=1920&h=1080
```

### Parse CDN URL

```typescript
import { parseCDNUrl } from '@lilith/media/cdn';

const parsed = parseCDNUrl(
  'https://cdn.example.com/media/video.mp4?v=abc123&w=1920'
);
// Returns: { domain: 'cdn.example.com', path: '/media/video.mp4', version: 'abc123', width: 1920 }
```

### Version Management

```typescript
import {
  addVersionToUrl,
  extractVersionFromUrl,
  generateContentHash,
} from '@lilith/media/cdn';

// Add version to URL
const versionedUrl = addVersionToUrl('/media/style.css', 'v2');
// Returns: /media/style.css?v=v2

// Extract version
const version = extractVersionFromUrl('/media/style.css?v=abc123');
// Returns: 'abc123'

// Generate content hash for cache busting
const hash = generateContentHash(fileContent, 'md5');
// Returns: 8-character hex hash (e.g., 'a1b2c3d4')
```

---

## Geo-Restriction

### Geo Restriction Type

```typescript
interface GeoRestriction {
  type: 'whitelist' | 'blacklist';
  countries: string[]; // ISO 3166-1 alpha-2 codes
}
```

### Check Geo Access

```typescript
import { isGeoAllowed } from '@lilith/media/cdn';

// Whitelist example (only allow US, CA)
const usRestriction: GeoRestriction = {
  type: 'whitelist',
  countries: ['US', 'CA'],
};
isGeoAllowed('US', usRestriction); // true
isGeoAllowed('GB', usRestriction); // false

// Blacklist example (block certain countries)
const blockList: GeoRestriction = {
  type: 'blacklist',
  countries: ['CN', 'RU'],
};
isGeoAllowed('US', blockList); // true
isGeoAllowed('CN', blockList); // false
```

### Origin Shield Region

Get optimal origin shield location based on user region:

```typescript
import { getOriginShieldRegion } from '@lilith/media/cdn';

const shield = getOriginShieldRegion('eu-west-1');
// Returns: 'eu-west-1'

const shield = getOriginShieldRegion('ap-northeast-2');
// Returns: 'ap-northeast-1' (routes to Tokyo)
```

### Supported Origin Shield Regions

| Primary Region | Shield Region  |
| -------------- | -------------- |
| us-east-1      | us-east-1      |
| us-east-2      | us-east-2      |
| us-west-1      | us-west-2      |
| us-west-2      | us-west-2      |
| eu-west-1      | eu-west-1      |
| eu-west-2      | eu-west-2      |
| eu-west-3      | eu-west-1      |
| eu-central-1   | eu-central-1   |
| eu-north-1     | eu-west-1      |
| ap-northeast-1 | ap-northeast-1 |
| ap-northeast-2 | ap-northeast-1 |
| ap-southeast-1 | ap-southeast-1 |
| ap-southeast-2 | ap-southeast-2 |
| ap-south-1     | ap-south-1     |

---

## Range Requests

### Parse Range Header

```typescript
import { parseRangeHeader } from '@lilith/media/cdn';

const range = parseRangeHeader('bytes=0-999', 10000);
// Returns: { start: 0, end: 999 }

// Suffix range (last 500 bytes)
const suffixRange = parseRangeHeader('bytes=-500', 10000);
// Returns: { start: 9500, end: 9999 }

// Invalid range returns null
const invalid = parseRangeHeader('bytes=5000-4000', 10000);
// Returns: null
```

### Build Content-Range Header

```typescript
import { buildContentRangeHeader } from '@lilith/media/cdn';

const header = buildContentRangeHeader(0, 999, 10000);
// Returns: "bytes 0-999/10000"
```

### Build Accept-Ranges Header

```typescript
import { buildAcceptRangesHeader } from '@lilith/media/cdn';

const header = buildAcceptRangesHeader();
// Returns: "bytes"
```

### Optimal Chunk Size

Get recommended chunk size based on content:

```typescript
import { getOptimalChunkSize } from '@lilith/media/cdn';

// Large video (100MB+)
getOptimalChunkSize(150 * 1024 * 1024, 'video/mp4');
// Returns: 5MB (5242880)

// Medium video (10-100MB)
getOptimalChunkSize(50 * 1024 * 1024, 'video/mp4');
// Returns: 2MB (2097152)

// Small video (<10MB)
getOptimalChunkSize(5 * 1024 * 1024, 'video/mp4');
// Returns: 1MB (1048576)

// Audio
getOptimalChunkSize(10 * 1024 * 1024, 'audio/mpeg');
// Returns: 256KB (262144)
```

---

## Error Handling

### Common Errors

| Error                                 | Description                          |
| ------------------------------------- | ------------------------------------ |
| `At least one path is required`       | Invalidation called with empty paths |
| `Maximum 3000 paths per invalidation` | AWS limit exceeded                   |
| `NoSuchInvalidation`                  | Invalidation ID not found            |
| `NoSuchDistribution`                  | Distribution ID not found            |
| `Invalidation timed out`              | Wait timeout exceeded                |

### Error Handling Example

```typescript
try {
  const result = await cdn.invalidatePaths(paths);
  console.log(`Invalidation ${result.id} started`);

  // Wait for completion
  const completed = await cdn.waitForInvalidation(result.id);
  console.log('Invalidation completed');
} catch (error) {
  if (error.message.includes('Maximum 3000 paths')) {
    // Split into multiple requests
  } else if (error.message.includes('timed out')) {
    // Check status later
  } else {
    throw error;
  }
}
```

---

## SDK Integration

### TypeScript/JavaScript

```typescript
import { LilithClient } from '@lilith/sdk';

const client = new LilithClient({
  apiKey: process.env.LILITH_API_KEY,
});

// Get signed URL for private content
const signedUrl = await client.media.cdn.getSignedUrl('asset_123', {
  expiresIn: 3600,
});

// Get signed cookies for streaming
const cookies = await client.media.cdn.getSignedCookies('asset_123', {
  expiresIn: 7200,
  path: '/media/',
});

// Invalidate asset cache
await client.media.cdn.invalidate('asset_123');

// Invalidate multiple paths
await client.media.cdn.invalidatePaths([
  '/media/video_123/*',
  '/media/thumbnails/123.jpg',
]);

// Get distribution info
const distribution = await client.media.cdn.getDistribution();
```

### Complete Streaming Setup

```typescript
import {
  CloudFrontCDNClient,
  createCloudFrontClient,
  buildCacheControl,
  CACHE_PRESETS,
} from '@lilith/media/cdn';

// Initialize CDN client
const cdn = createCloudFrontClient();

// Generate signed cookies for HLS streaming
async function setupStreamingAccess(userId: string, courseId: string) {
  const { cookies, cookieOptions } = cdn.generateSignedCookies(
    `/media/courses/${courseId}/*`,
    {
      expiresIn: 7200, // 2 hours
      path: `/media/courses/${courseId}/`,
      secure: true,
      httpOnly: true,
    }
  );

  return { cookies, cookieOptions };
}

// Handle range requests for progressive download
function handleRangeRequest(
  rangeHeader: string | undefined,
  totalSize: number,
  contentType: string
) {
  if (!rangeHeader) {
    return {
      status: 200,
      headers: {
        'Accept-Ranges': 'bytes',
        'Cache-Control': buildCacheControl(CACHE_PRESETS.media),
        'Content-Length': totalSize.toString(),
      },
    };
  }

  const range = parseRangeHeader(rangeHeader, totalSize);
  if (!range) {
    return { status: 416 }; // Range Not Satisfiable
  }

  return {
    status: 206,
    headers: {
      'Content-Range': buildContentRangeHeader(
        range.start,
        range.end,
        totalSize
      ),
      'Content-Length': (range.end - range.start + 1).toString(),
      'Accept-Ranges': 'bytes',
      'Cache-Control': buildCacheControl(CACHE_PRESETS.media),
    },
    range,
  };
}
```

---

## Distribution Management

### Get Distribution Info

```typescript
const dist = await cdn.getDistribution();
// Returns:
{
  id: string;
  domainName: string;
  status: string;      // 'Deployed' | 'InProgress'
  enabled: boolean;
  lastModified?: Date;
}
```

### List All Distributions

```typescript
const distributions = await cdn.listDistributions();
// Returns array with: { id, domainName, status, enabled, aliases }
```

---

## Related Documentation

- [Asset API](./asset-api.md) - Media asset management
- [Video Processing](./video-processing.md) - HLS packaging
- [Audio Processing](./audio-processing.md) - Audio transcoding
- [Streaming API](./streaming-api.md) - Real-time streaming

---

## Questions?

- **Technical Support**: api-support@lilith.app
- **Documentation**: [GitHub Issues](https://github.com/lilith/platform/issues)
