mirror of
https://github.com/ksyasuda/dotfiles.git
synced 2026-03-20 06:11:27 -07:00
update skills
This commit is contained in:
@@ -0,0 +1,90 @@
|
||||
# Cloudflare Argo Smart Routing Skill Reference
|
||||
|
||||
## Overview
|
||||
|
||||
Cloudflare Argo Smart Routing is a performance optimization service that detects real-time network issues and routes web traffic across the most efficient network path. It continuously monitors network conditions and intelligently routes traffic through the fastest, most reliable routes in Cloudflare's network.
|
||||
|
||||
**Note on Smart Shield:** Argo Smart Routing is being integrated into Cloudflare's Smart Shield product for enhanced DDoS protection and performance. Existing Argo customers maintain full functionality with gradual migration to Smart Shield features.
|
||||
|
||||
## Quick Start
|
||||
|
||||
### Enable via cURL
|
||||
```bash
|
||||
curl -X PATCH "https://api.cloudflare.com/client/v4/zones/{zone_id}/argo/smart_routing" \
|
||||
-H "Authorization: Bearer YOUR_API_TOKEN" \
|
||||
-H "Content-Type: application/json" \
|
||||
-d '{"value": "on"}'
|
||||
```
|
||||
|
||||
### Enable via TypeScript SDK
|
||||
```typescript
|
||||
import Cloudflare from 'cloudflare';
|
||||
|
||||
const client = new Cloudflare({ apiToken: process.env.CLOUDFLARE_API_TOKEN });
|
||||
|
||||
const result = await client.argo.smartRouting.edit({
|
||||
zone_id: 'your-zone-id',
|
||||
value: 'on',
|
||||
});
|
||||
|
||||
console.log(`Argo enabled: ${result.value}`);
|
||||
```
|
||||
|
||||
## Core Concepts
|
||||
|
||||
### What It Does
|
||||
- **Intelligent routing**: Detects congestion, outages, packet loss in real-time
|
||||
- **Global optimization**: Routes across 300+ Cloudflare data centers
|
||||
- **Automatic failover**: Switches paths when issues detected (typically <1s)
|
||||
- **Works with existing setup**: No origin changes required
|
||||
|
||||
### Billing Model
|
||||
- Usage-based: Charged per GB of traffic (excluding DDoS/WAF mitigated traffic)
|
||||
- Requires billing configuration before enabling
|
||||
- Available on Enterprise+ plans (check zone eligibility)
|
||||
|
||||
### When to Use
|
||||
- **High-traffic production sites** with global user base
|
||||
- **Latency-sensitive applications** (APIs, real-time services)
|
||||
- **Sites behind Cloudflare proxy** (orange-clouded DNS records)
|
||||
- **Combined with Tiered Cache** for maximum performance gains
|
||||
|
||||
### When NOT to Use
|
||||
- Development/staging environments (cost control)
|
||||
- Low-traffic sites (<1TB/month) where cost may exceed benefit
|
||||
- Sites with primarily single-region traffic
|
||||
|
||||
## Should I Enable Argo?
|
||||
|
||||
| Your Situation | Recommendation |
|
||||
|----------------|----------------|
|
||||
| Global production app, >1TB/month traffic | ✅ Enable - likely ROI positive |
|
||||
| Enterprise plan, latency-critical APIs | ✅ Enable - performance matters |
|
||||
| Regional site, <100GB/month traffic | ⚠️ Evaluate - cost may not justify |
|
||||
| Development/staging environment | ❌ Disable - use in production only |
|
||||
| Not yet configured billing | ❌ Configure billing first |
|
||||
|
||||
## Reading Order by Task
|
||||
|
||||
| Your Goal | Start With | Then Read |
|
||||
|-----------|------------|-----------|
|
||||
| Enable Argo for first time | Quick Start above → [configuration.md](configuration.md) | [gotchas.md](gotchas.md) |
|
||||
| Use TypeScript/Python SDK | [api.md](api.md) | [patterns.md](patterns.md) |
|
||||
| Terraform/IaC setup | [configuration.md](configuration.md) | - |
|
||||
| Enable for Spectrum TCP app | [patterns.md](patterns.md) → Spectrum section | [api.md](api.md) |
|
||||
| Troubleshoot enablement issue | [gotchas.md](gotchas.md) | [api.md](api.md) |
|
||||
| Manage billing/usage | [patterns.md](patterns.md) → Billing section | [gotchas.md](gotchas.md) |
|
||||
|
||||
## In This Reference
|
||||
|
||||
- **[api.md](api.md)** - API endpoints, SDK methods, error handling, Python/TypeScript examples
|
||||
- **[configuration.md](configuration.md)** - Terraform setup, environment config, billing configuration
|
||||
- **[patterns.md](patterns.md)** - Tiered Cache integration, Spectrum TCP apps, billing management, validation patterns
|
||||
- **[gotchas.md](gotchas.md)** - Common errors, permission issues, limits, best practices
|
||||
|
||||
## See Also
|
||||
|
||||
- [Cloudflare Argo Smart Routing Docs](https://developers.cloudflare.com/argo-smart-routing/)
|
||||
- [Cloudflare Smart Shield](https://developers.cloudflare.com/smart-shield/)
|
||||
- [Spectrum Documentation](https://developers.cloudflare.com/spectrum/)
|
||||
- [Tiered Cache](https://developers.cloudflare.com/cache/how-to/tiered-cache/)
|
||||
@@ -0,0 +1,240 @@
|
||||
## API Reference
|
||||
|
||||
**Note on Smart Shield:** Argo Smart Routing is being integrated into Cloudflare's Smart Shield product. API endpoints remain stable; existing integrations continue to work without changes.
|
||||
|
||||
### Base Endpoint
|
||||
```
|
||||
https://api.cloudflare.com/client/v4
|
||||
```
|
||||
|
||||
### Authentication
|
||||
Use API tokens with Zone:Argo Smart Routing:Edit permissions:
|
||||
|
||||
```bash
|
||||
# Headers required
|
||||
X-Auth-Email: user@example.com
|
||||
Authorization: Bearer YOUR_API_TOKEN
|
||||
```
|
||||
|
||||
### Get Argo Smart Routing Status
|
||||
|
||||
**Endpoint:** `GET /zones/{zone_id}/argo/smart_routing`
|
||||
|
||||
**Description:** Retrieves current Argo Smart Routing enablement status.
|
||||
|
||||
**cURL Example:**
|
||||
```bash
|
||||
curl -X GET "https://api.cloudflare.com/client/v4/zones/{zone_id}/argo/smart_routing" \
|
||||
-H "Authorization: Bearer YOUR_API_TOKEN" \
|
||||
-H "Content-Type: application/json"
|
||||
```
|
||||
|
||||
**Response:**
|
||||
```json
|
||||
{
|
||||
"result": {
|
||||
"id": "smart_routing",
|
||||
"value": "on",
|
||||
"editable": true,
|
||||
"modified_on": "2024-01-11T12:00:00Z"
|
||||
},
|
||||
"success": true,
|
||||
"errors": [],
|
||||
"messages": []
|
||||
}
|
||||
```
|
||||
|
||||
**TypeScript SDK Example:**
|
||||
```typescript
|
||||
import Cloudflare from 'cloudflare';
|
||||
|
||||
const client = new Cloudflare({
|
||||
apiToken: process.env.CLOUDFLARE_API_TOKEN
|
||||
});
|
||||
|
||||
const status = await client.argo.smartRouting.get({ zone_id: 'your-zone-id' });
|
||||
console.log(`Argo status: ${status.value}, editable: ${status.editable}`);
|
||||
```
|
||||
|
||||
**Python SDK Example:**
|
||||
```python
|
||||
from cloudflare import Cloudflare
|
||||
|
||||
client = Cloudflare(api_token=os.environ.get('CLOUDFLARE_API_TOKEN'))
|
||||
|
||||
status = client.argo.smart_routing.get(zone_id='your-zone-id')
|
||||
print(f"Argo status: {status.value}, editable: {status.editable}")
|
||||
```
|
||||
|
||||
### Update Argo Smart Routing Status
|
||||
|
||||
**Endpoint:** `PATCH /zones/{zone_id}/argo/smart_routing`
|
||||
|
||||
**Description:** Enable or disable Argo Smart Routing for a zone.
|
||||
|
||||
**Request Body:**
|
||||
```json
|
||||
{
|
||||
"value": "on" // or "off"
|
||||
}
|
||||
```
|
||||
|
||||
**cURL Example:**
|
||||
```bash
|
||||
curl -X PATCH "https://api.cloudflare.com/client/v4/zones/{zone_id}/argo/smart_routing" \
|
||||
-H "Authorization: Bearer YOUR_API_TOKEN" \
|
||||
-H "Content-Type: application/json" \
|
||||
-d '{"value": "on"}'
|
||||
```
|
||||
|
||||
**TypeScript SDK Example:**
|
||||
```typescript
|
||||
const result = await client.argo.smartRouting.edit({
|
||||
zone_id: 'your-zone-id',
|
||||
value: 'on',
|
||||
});
|
||||
console.log(`Updated: ${result.value} at ${result.modified_on}`);
|
||||
```
|
||||
|
||||
**Python SDK Example:**
|
||||
```python
|
||||
result = client.argo.smart_routing.edit(
|
||||
zone_id='your-zone-id',
|
||||
value='on'
|
||||
)
|
||||
print(f"Updated: {result.value} at {result.modified_on}")
|
||||
```
|
||||
|
||||
## Checking Editability Before Updates
|
||||
|
||||
**Critical:** Always check the `editable` field before attempting to enable/disable Argo. When `editable: false`, the zone has restrictions (billing not configured, insufficient permissions, or plan limitations).
|
||||
|
||||
**Pattern:**
|
||||
```typescript
|
||||
async function safelyEnableArgo(client: Cloudflare, zoneId: string): Promise<boolean> {
|
||||
const status = await client.argo.smartRouting.get({ zone_id: zoneId });
|
||||
|
||||
if (!status.editable) {
|
||||
console.error('Cannot modify Argo: editable=false (check billing/permissions)');
|
||||
return false;
|
||||
}
|
||||
|
||||
if (status.value === 'on') {
|
||||
console.log('Argo already enabled');
|
||||
return true;
|
||||
}
|
||||
|
||||
await client.argo.smartRouting.edit({ zone_id: zoneId, value: 'on' });
|
||||
console.log('Argo enabled successfully');
|
||||
return true;
|
||||
}
|
||||
```
|
||||
|
||||
**Python Pattern:**
|
||||
```python
|
||||
def safely_enable_argo(client: Cloudflare, zone_id: str) -> bool:
|
||||
status = client.argo.smart_routing.get(zone_id=zone_id)
|
||||
|
||||
if not status.editable:
|
||||
print('Cannot modify Argo: editable=false (check billing/permissions)')
|
||||
return False
|
||||
|
||||
if status.value == 'on':
|
||||
print('Argo already enabled')
|
||||
return True
|
||||
|
||||
client.argo.smart_routing.edit(zone_id=zone_id, value='on')
|
||||
print('Argo enabled successfully')
|
||||
return True
|
||||
```
|
||||
|
||||
## Error Handling
|
||||
|
||||
The TypeScript SDK provides typed error classes for robust error handling:
|
||||
|
||||
```typescript
|
||||
import Cloudflare from 'cloudflare';
|
||||
import { APIError, APIConnectionError, RateLimitError } from 'cloudflare';
|
||||
|
||||
async function enableArgoWithErrorHandling(client: Cloudflare, zoneId: string) {
|
||||
try {
|
||||
const result = await client.argo.smartRouting.edit({
|
||||
zone_id: zoneId,
|
||||
value: 'on',
|
||||
});
|
||||
return result;
|
||||
} catch (error) {
|
||||
if (error instanceof RateLimitError) {
|
||||
console.error('Rate limited. Retry after:', error.response?.headers.get('retry-after'));
|
||||
// Implement exponential backoff
|
||||
} else if (error instanceof APIError) {
|
||||
console.error('API error:', error.status, error.message);
|
||||
if (error.status === 403) {
|
||||
console.error('Permission denied - check API token scopes');
|
||||
} else if (error.status === 400) {
|
||||
console.error('Bad request - verify zone_id and payload');
|
||||
}
|
||||
} else if (error instanceof APIConnectionError) {
|
||||
console.error('Connection failed:', error.message);
|
||||
// Retry with exponential backoff
|
||||
} else {
|
||||
console.error('Unexpected error:', error);
|
||||
}
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
**Python Error Handling:**
|
||||
```python
|
||||
from cloudflare import Cloudflare, APIError, RateLimitError
|
||||
|
||||
def enable_argo_with_error_handling(client: Cloudflare, zone_id: str):
|
||||
try:
|
||||
result = client.argo.smart_routing.edit(zone_id=zone_id, value='on')
|
||||
return result
|
||||
except RateLimitError as e:
|
||||
print(f"Rate limited. Retry after: {e.response.headers.get('retry-after')}")
|
||||
raise
|
||||
except APIError as e:
|
||||
print(f"API error: {e.status} - {e.message}")
|
||||
if e.status == 403:
|
||||
print('Permission denied - check API token scopes')
|
||||
elif e.status == 400:
|
||||
print('Bad request - verify zone_id and payload')
|
||||
raise
|
||||
except Exception as e:
|
||||
print(f"Unexpected error: {e}")
|
||||
raise
|
||||
```
|
||||
|
||||
## Response Schema
|
||||
|
||||
All Argo Smart Routing API responses follow this structure:
|
||||
|
||||
```typescript
|
||||
interface ArgoSmartRoutingResponse {
|
||||
result: {
|
||||
id: 'smart_routing';
|
||||
value: 'on' | 'off';
|
||||
editable: boolean;
|
||||
modified_on: string; // ISO 8601 timestamp
|
||||
};
|
||||
success: boolean;
|
||||
errors: Array<{
|
||||
code: number;
|
||||
message: string;
|
||||
}>;
|
||||
messages: Array<string>;
|
||||
}
|
||||
```
|
||||
|
||||
## Key Response Fields
|
||||
|
||||
| Field | Type | Description |
|
||||
|-------|------|-------------|
|
||||
| `value` | `"on" \| "off"` | Current enablement status |
|
||||
| `editable` | `boolean` | Whether changes are allowed (check before PATCH) |
|
||||
| `modified_on` | `string` | ISO timestamp of last modification |
|
||||
| `success` | `boolean` | Whether request succeeded |
|
||||
| `errors` | `Array` | Error details if `success: false`
|
||||
@@ -0,0 +1,197 @@
|
||||
## Configuration Management
|
||||
|
||||
**Note on Smart Shield Evolution:** Argo Smart Routing is being integrated into Smart Shield. Configuration methods below remain valid; Terraform and IaC patterns unchanged.
|
||||
|
||||
### Infrastructure as Code (Terraform)
|
||||
|
||||
```hcl
|
||||
# terraform/argo.tf
|
||||
# Note: Use Cloudflare Terraform provider
|
||||
|
||||
resource "cloudflare_argo" "example" {
|
||||
zone_id = var.zone_id
|
||||
smart_routing = "on"
|
||||
tiered_caching = "on"
|
||||
}
|
||||
|
||||
variable "zone_id" {
|
||||
description = "Cloudflare Zone ID"
|
||||
type = string
|
||||
}
|
||||
|
||||
output "argo_enabled" {
|
||||
value = cloudflare_argo.example.smart_routing
|
||||
description = "Argo Smart Routing status"
|
||||
}
|
||||
```
|
||||
|
||||
### Environment-Based Configuration
|
||||
|
||||
```typescript
|
||||
// config/argo.ts
|
||||
interface ArgoEnvironmentConfig {
|
||||
enabled: boolean;
|
||||
tieredCache: boolean;
|
||||
monitoring: {
|
||||
usageAlerts: boolean;
|
||||
threshold: number;
|
||||
};
|
||||
}
|
||||
|
||||
const configs: Record<string, ArgoEnvironmentConfig> = {
|
||||
production: {
|
||||
enabled: true,
|
||||
tieredCache: true,
|
||||
monitoring: {
|
||||
usageAlerts: true,
|
||||
threshold: 1000, // GB
|
||||
},
|
||||
},
|
||||
staging: {
|
||||
enabled: true,
|
||||
tieredCache: false,
|
||||
monitoring: {
|
||||
usageAlerts: false,
|
||||
threshold: 100, // GB
|
||||
},
|
||||
},
|
||||
development: {
|
||||
enabled: false,
|
||||
tieredCache: false,
|
||||
monitoring: {
|
||||
usageAlerts: false,
|
||||
threshold: 0,
|
||||
},
|
||||
},
|
||||
};
|
||||
|
||||
export function getArgoConfig(env: string): ArgoEnvironmentConfig {
|
||||
return configs[env] || configs.development;
|
||||
}
|
||||
```
|
||||
|
||||
### Pulumi Configuration
|
||||
|
||||
```typescript
|
||||
// pulumi/argo.ts
|
||||
import * as cloudflare from '@pulumi/cloudflare';
|
||||
|
||||
const zone = new cloudflare.Zone('example-zone', {
|
||||
zone: 'example.com',
|
||||
plan: 'enterprise',
|
||||
});
|
||||
|
||||
const argoSettings = new cloudflare.Argo('argo-config', {
|
||||
zoneId: zone.id,
|
||||
smartRouting: 'on',
|
||||
tieredCaching: 'on',
|
||||
});
|
||||
|
||||
export const argoEnabled = argoSettings.smartRouting;
|
||||
export const zoneId = zone.id;
|
||||
```
|
||||
|
||||
## Billing Configuration
|
||||
|
||||
Before enabling Argo Smart Routing, ensure billing is configured for the account:
|
||||
|
||||
**Prerequisites:**
|
||||
1. Valid payment method on file
|
||||
2. Enterprise or higher plan
|
||||
3. Zone must have billing enabled
|
||||
|
||||
**Check Billing Status via Dashboard:**
|
||||
1. Navigate to Account → Billing
|
||||
2. Verify payment method configured
|
||||
3. Check zone subscription status
|
||||
|
||||
**Note:** Attempting to enable Argo without billing configured will result in `editable: false` in API responses.
|
||||
|
||||
## Environment Variable Setup
|
||||
|
||||
**Required Environment Variables:**
|
||||
```bash
|
||||
# .env
|
||||
CLOUDFLARE_API_TOKEN=your_api_token_here
|
||||
CLOUDFLARE_ZONE_ID=your_zone_id_here
|
||||
CLOUDFLARE_ACCOUNT_ID=your_account_id_here
|
||||
|
||||
# Optional
|
||||
ARGO_ENABLED=true
|
||||
ARGO_TIERED_CACHE=true
|
||||
```
|
||||
|
||||
**TypeScript Configuration Loader:**
|
||||
```typescript
|
||||
// config/env.ts
|
||||
import { z } from 'zod';
|
||||
|
||||
const envSchema = z.object({
|
||||
CLOUDFLARE_API_TOKEN: z.string().min(1),
|
||||
CLOUDFLARE_ZONE_ID: z.string().min(1),
|
||||
CLOUDFLARE_ACCOUNT_ID: z.string().min(1),
|
||||
ARGO_ENABLED: z.string().optional().default('false'),
|
||||
ARGO_TIERED_CACHE: z.string().optional().default('false'),
|
||||
});
|
||||
|
||||
export const env = envSchema.parse(process.env);
|
||||
|
||||
export const argoConfig = {
|
||||
enabled: env.ARGO_ENABLED === 'true',
|
||||
tieredCache: env.ARGO_TIERED_CACHE === 'true',
|
||||
};
|
||||
```
|
||||
|
||||
## CI/CD Integration
|
||||
|
||||
**GitHub Actions Example:**
|
||||
```yaml
|
||||
# .github/workflows/deploy-argo.yml
|
||||
name: Deploy Argo Configuration
|
||||
|
||||
on:
|
||||
push:
|
||||
branches: [main]
|
||||
paths:
|
||||
- 'terraform/argo.tf'
|
||||
|
||||
jobs:
|
||||
deploy:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v3
|
||||
|
||||
- name: Setup Terraform
|
||||
uses: hashicorp/setup-terraform@v2
|
||||
|
||||
- name: Terraform Init
|
||||
run: terraform init
|
||||
working-directory: ./terraform
|
||||
|
||||
- name: Terraform Apply
|
||||
run: terraform apply -auto-approve
|
||||
working-directory: ./terraform
|
||||
env:
|
||||
CLOUDFLARE_API_TOKEN: ${{ secrets.CLOUDFLARE_API_TOKEN }}
|
||||
TF_VAR_zone_id: ${{ secrets.CLOUDFLARE_ZONE_ID }}
|
||||
```
|
||||
|
||||
## Enterprise Preview Program
|
||||
|
||||
For early access to Argo Smart Routing features and Smart Shield integration:
|
||||
|
||||
**Eligibility:**
|
||||
- Enterprise plan customers
|
||||
- Active Cloudflare support contract
|
||||
- Production traffic >100GB/month
|
||||
|
||||
**How to Join:**
|
||||
1. Contact Cloudflare account team or support
|
||||
2. Request Argo/Smart Shield preview access
|
||||
3. Receive preview zone configuration
|
||||
|
||||
**Preview Features:**
|
||||
- Enhanced analytics and reporting
|
||||
- Smart Shield DDoS integration
|
||||
- Advanced routing policies
|
||||
- Priority support for routing issues
|
||||
@@ -0,0 +1,111 @@
|
||||
## Best Practices Summary
|
||||
|
||||
**Smart Shield Note:** Argo Smart Routing evolving into Smart Shield. Best practices below remain applicable; monitor Cloudflare changelog for Smart Shield updates.
|
||||
|
||||
1. **Always check editability** before attempting to enable/disable Argo
|
||||
2. **Set up billing notifications** to avoid unexpected costs
|
||||
3. **Combine with Tiered Cache** for maximum performance benefit
|
||||
4. **Use in production only** - disable for dev/staging to control costs
|
||||
5. **Monitor analytics** - require 500+ requests in 48h for detailed metrics
|
||||
6. **Handle errors gracefully** - check for billing, permissions, zone compatibility
|
||||
7. **Test configuration changes** in staging before production
|
||||
8. **Use TypeScript SDK** for type safety and better developer experience
|
||||
9. **Implement retry logic** for API calls in production systems
|
||||
10. **Document zone-specific settings** for team visibility
|
||||
|
||||
## Common Errors
|
||||
|
||||
### "Argo unavailable"
|
||||
|
||||
**Problem:** API returns error "Argo Smart Routing is unavailable for this zone"
|
||||
|
||||
**Cause:** Zone not eligible or billing not set up
|
||||
|
||||
**Solution:**
|
||||
1. Verify zone has Enterprise or higher plan
|
||||
2. Check billing is configured in Account → Billing
|
||||
3. Ensure payment method is valid and current
|
||||
4. Contact Cloudflare support if eligibility unclear
|
||||
|
||||
### "Cannot enable/disable"
|
||||
|
||||
**Problem:** API call succeeds but status remains unchanged, or `editable: false` in GET response
|
||||
|
||||
**Cause:** Insufficient permissions or zone restrictions
|
||||
|
||||
**Solution:**
|
||||
1. Check API token has `Zone:Argo Smart Routing:Edit` permission
|
||||
2. Verify `editable: true` in GET response before attempting PATCH
|
||||
3. If `editable: false`, check:
|
||||
- Billing configured for account
|
||||
- Zone plan includes Argo (Enterprise+)
|
||||
- No active zone holds or suspensions
|
||||
- API token has correct scopes
|
||||
|
||||
### `editable: false` Error
|
||||
|
||||
**Problem:** GET request returns `"editable": false`, preventing enable/disable
|
||||
|
||||
**Cause:** Zone-level restrictions from billing, plan, or permissions
|
||||
|
||||
**Solution Pattern:**
|
||||
```typescript
|
||||
const status = await client.argo.smartRouting.get({ zone_id: zoneId });
|
||||
|
||||
if (!status.editable) {
|
||||
// Don't attempt to modify - will fail
|
||||
console.error('Cannot modify Argo settings:');
|
||||
console.error('- Check billing is configured');
|
||||
console.error('- Verify zone has Enterprise+ plan');
|
||||
console.error('- Confirm API token has Edit permission');
|
||||
throw new Error('Argo is not editable for this zone');
|
||||
}
|
||||
|
||||
// Safe to proceed with enable/disable
|
||||
await client.argo.smartRouting.edit({ zone_id: zoneId, value: 'on' });
|
||||
```
|
||||
|
||||
### Rate Limiting
|
||||
|
||||
**Problem:** `429 Too Many Requests` error from API
|
||||
|
||||
**Cause:** Exceeded API rate limits (typically 1200 requests per 5 minutes)
|
||||
|
||||
**Solution:**
|
||||
```typescript
|
||||
import { RateLimitError } from 'cloudflare';
|
||||
|
||||
try {
|
||||
await client.argo.smartRouting.edit({ zone_id: zoneId, value: 'on' });
|
||||
} catch (error) {
|
||||
if (error instanceof RateLimitError) {
|
||||
const retryAfter = error.response?.headers.get('retry-after');
|
||||
console.log(`Rate limited. Retry after ${retryAfter} seconds`);
|
||||
|
||||
// Implement exponential backoff
|
||||
await new Promise(resolve => setTimeout(resolve, (retryAfter || 60) * 1000));
|
||||
// Retry request
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
## Limits
|
||||
|
||||
| Resource/Limit | Value | Notes |
|
||||
|----------------|-------|-------|
|
||||
| Min requests for analytics | 500 in 48h | For detailed metrics via GraphQL |
|
||||
| Zones supported | Enterprise+ | Check zone plan in dashboard |
|
||||
| Billing requirement | Must be configured | Before enabling; verify payment method |
|
||||
| API rate limit | 1200 req / 5 min | Per API token across all endpoints |
|
||||
| Spectrum apps | No hard limit | Each app can enable Argo independently |
|
||||
| Traffic counting | Proxied only | Only orange-clouded DNS records count |
|
||||
| DDoS/WAF exemption | Yes | Mitigated traffic excluded from billing |
|
||||
| Analytics latency | 1-5 minutes | Real-time metrics not available |
|
||||
|
||||
## Additional Resources
|
||||
|
||||
- [Official Argo Smart Routing Docs](https://developers.cloudflare.com/argo-smart-routing/)
|
||||
- [Cloudflare Smart Shield](https://developers.cloudflare.com/smart-shield/)
|
||||
- [API Authentication](https://developers.cloudflare.com/fundamentals/api/get-started/create-token/)
|
||||
- [Cloudflare TypeScript SDK](https://github.com/cloudflare/cloudflare-typescript)
|
||||
- [Cloudflare Python SDK](https://github.com/cloudflare/cloudflare-python)
|
||||
@@ -0,0 +1,104 @@
|
||||
# Integration Patterns
|
||||
|
||||
## Enable Argo + Tiered Cache
|
||||
|
||||
```typescript
|
||||
async function enableOptimalPerformance(client: Cloudflare, zoneId: string) {
|
||||
await Promise.all([
|
||||
client.argo.smartRouting.edit({ zone_id: zoneId, value: 'on' }),
|
||||
client.argo.tieredCaching.edit({ zone_id: zoneId, value: 'on' }),
|
||||
]);
|
||||
}
|
||||
```
|
||||
|
||||
**Flow:** Visitor → Edge (Lower-Tier) → [Cache Miss] → Upper-Tier → [Cache Miss + Argo] → Origin
|
||||
|
||||
**Impact:** Argo ~30% latency reduction + Tiered Cache 50-80% origin offload
|
||||
|
||||
## Usage Analytics (GraphQL)
|
||||
|
||||
```graphql
|
||||
query ArgoAnalytics($zoneTag: string!) {
|
||||
viewer {
|
||||
zones(filter: { zoneTag: $zoneTag }) {
|
||||
httpRequestsAdaptiveGroups(limit: 1000) {
|
||||
sum { argoBytes, bytes }
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
**Billing:** ~$0.10/GB. DDoS-mitigated and WAF-blocked traffic NOT charged.
|
||||
|
||||
## Spectrum TCP Integration
|
||||
|
||||
Enable Argo for non-HTTP traffic (databases, game servers, IoT):
|
||||
|
||||
```typescript
|
||||
// Update existing app
|
||||
await client.spectrum.apps.update(appId, { zone_id: zoneId, argo_smart_routing: true });
|
||||
|
||||
// Create new app with Argo
|
||||
await client.spectrum.apps.create({
|
||||
zone_id: zoneId,
|
||||
dns: { type: 'CNAME', name: 'tcp.example.com' },
|
||||
origin_direct: ['tcp://origin.example.com:3306'],
|
||||
protocol: 'tcp/3306',
|
||||
argo_smart_routing: true,
|
||||
});
|
||||
```
|
||||
|
||||
**Use cases:** MySQL/PostgreSQL (3306/5432), game servers, MQTT (1883), SSH (22)
|
||||
|
||||
## Pre-Flight Validation
|
||||
|
||||
```typescript
|
||||
async function validateArgoEligibility(client: Cloudflare, zoneId: string) {
|
||||
const status = await client.argo.smartRouting.get({ zone_id: zoneId });
|
||||
const zone = await client.zones.get({ zone_id: zoneId });
|
||||
|
||||
const issues: string[] = [];
|
||||
if (!status.editable) issues.push('Zone not editable');
|
||||
if (['free', 'pro'].includes(zone.plan.legacy_id)) issues.push('Requires Business+ plan');
|
||||
if (zone.status !== 'active') issues.push('Zone not active');
|
||||
|
||||
return { canEnable: issues.length === 0, issues };
|
||||
}
|
||||
```
|
||||
|
||||
## Post-Enable Verification
|
||||
|
||||
```typescript
|
||||
async function verifyArgoEnabled(client: Cloudflare, zoneId: string): Promise<boolean> {
|
||||
await new Promise(r => setTimeout(r, 2000)); // Wait for propagation
|
||||
const status = await client.argo.smartRouting.get({ zone_id: zoneId });
|
||||
return status.value === 'on';
|
||||
}
|
||||
```
|
||||
|
||||
## Full Setup Pattern
|
||||
|
||||
```typescript
|
||||
async function setupArgo(client: Cloudflare, zoneId: string) {
|
||||
// 1. Validate
|
||||
const { canEnable, issues } = await validateArgoEligibility(client, zoneId);
|
||||
if (!canEnable) throw new Error(issues.join(', '));
|
||||
|
||||
// 2. Enable both features
|
||||
await Promise.all([
|
||||
client.argo.smartRouting.edit({ zone_id: zoneId, value: 'on' }),
|
||||
client.argo.tieredCaching.edit({ zone_id: zoneId, value: 'on' }),
|
||||
]);
|
||||
|
||||
// 3. Verify
|
||||
const [argo, cache] = await Promise.all([
|
||||
client.argo.smartRouting.get({ zone_id: zoneId }),
|
||||
client.argo.tieredCaching.get({ zone_id: zoneId }),
|
||||
]);
|
||||
|
||||
return { argo: argo.value === 'on', tieredCache: cache.value === 'on' };
|
||||
}
|
||||
```
|
||||
|
||||
**When to combine:** High-traffic sites (>1TB/mo), global users, cacheable content.
|
||||
Reference in New Issue
Block a user