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 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
# Deployment Guide - Crypto Resource Aggregator

## Quick Deployment to Hugging Face Spaces

### Method 1: Web Interface (Recommended for Beginners)

1. **Create a Hugging Face Account**
   - Go to https://huggingface.co/join
   - Sign up for a free account

2. **Create a New Space**
   - Go to https://huggingface.co/new-space
   - Choose a name (e.g., `crypto-resource-aggregator`)
   - Select SDK: **Docker**
   - Choose visibility: **Public** or **Private**
   - Click "Create Space"

3. **Upload Files**
   Upload the following files to your Space:
   - `app.py` - Main application file
   - `requirements.txt` - Python dependencies
   - `all_apis_merged_2025.json` - Resource configuration
   - `README.md` - Documentation
   - `Dockerfile` - Docker configuration

4. **Wait for Build**
   - The Space will automatically build and deploy
   - This may take 2-5 minutes
   - You'll see the build logs in real-time

5. **Access Your API**
   - Once deployed, your API will be available at:
     `https://[your-username]-[space-name].hf.space`
   - Example: `https://username-crypto-resource-aggregator.hf.space`

### Method 2: Git CLI (Recommended for Advanced Users)

```bash
# Clone your Space repository
git clone https://huggingface.co/spaces/[your-username]/[space-name]
cd [space-name]

# Copy all files to the repository
cp app.py requirements.txt all_apis_merged_2025.json README.md Dockerfile .

# Commit and push
git add .
git commit -m "Initial deployment of Crypto Resource Aggregator"
git push
```

---

## Alternative Deployment Options

### Option 1: Heroku

```bash
# Install Heroku CLI
# https://devcenter.heroku.com/articles/heroku-cli

# Create a new app
heroku create crypto-resource-aggregator

# Create Procfile
echo "web: python app.py" > Procfile

# Deploy
git add .
git commit -m "Deploy to Heroku"
git push heroku main

# Open your app
heroku open
```

### Option 2: Railway

```bash
# Install Railway CLI
npm i -g @railway/cli

# Login
railway login

# Initialize project
railway init

# Deploy
railway up

# Get deployment URL
railway domain
```

### Option 3: Render

1. Go to https://render.com
2. Click "New +" β†’ "Web Service"
3. Connect your GitHub repository
4. Configure:
   - **Build Command**: `pip install -r requirements.txt`
   - **Start Command**: `python app.py`
   - **Environment**: Python 3
5. Click "Create Web Service"

### Option 4: Docker (Self-Hosted)

```bash
# Build the Docker image
docker build -t crypto-aggregator .

# Run the container
docker run -d -p 7860:7860 --name crypto-aggregator crypto-aggregator

# Check logs
docker logs crypto-aggregator

# Stop the container
docker stop crypto-aggregator

# Remove the container
docker rm crypto-aggregator
```

### Option 5: Docker Compose (Self-Hosted)

Create `docker-compose.yml`:

```yaml
version: '3.8'

services:
  aggregator:
    build: .
    ports:
      - "7860:7860"
    restart: unless-stopped
    volumes:
      - ./history.db:/app/history.db
    environment:
      - ENVIRONMENT=production
```

Run:
```bash
docker-compose up -d
```

### Option 6: AWS EC2

```bash
# Connect to your EC2 instance
ssh -i your-key.pem ubuntu@your-instance-ip

# Install Python and dependencies
sudo apt update
sudo apt install python3-pip python3-venv -y

# Create virtual environment
python3 -m venv venv
source venv/bin/activate

# Upload files (from local machine)
scp -i your-key.pem app.py requirements.txt all_apis_merged_2025.json ubuntu@your-instance-ip:~/

# Install dependencies
pip install -r requirements.txt

# Run with nohup
nohup python app.py > output.log 2>&1 &

# Or use systemd service (recommended)
sudo nano /etc/systemd/system/crypto-aggregator.service
```

Create systemd service file:
```ini
[Unit]
Description=Crypto Resource Aggregator
After=network.target

[Service]
User=ubuntu
WorkingDirectory=/home/ubuntu/crypto-aggregator
ExecStart=/home/ubuntu/venv/bin/python app.py
Restart=always

[Install]
WantedBy=multi-user.target
```

Enable and start:
```bash
sudo systemctl enable crypto-aggregator
sudo systemctl start crypto-aggregator
sudo systemctl status crypto-aggregator
```

### Option 7: Google Cloud Run

```bash
# Install gcloud CLI
# https://cloud.google.com/sdk/docs/install

# Authenticate
gcloud auth login

# Set project
gcloud config set project YOUR_PROJECT_ID

# Build and deploy
gcloud run deploy crypto-aggregator \
  --source . \
  --platform managed \
  --region us-central1 \
  --allow-unauthenticated

# Get URL
gcloud run services describe crypto-aggregator --region us-central1 --format 'value(status.url)'
```

### Option 8: DigitalOcean App Platform

1. Go to https://cloud.digitalocean.com/apps
2. Click "Create App"
3. Connect your GitHub repository
4. Configure:
   - **Run Command**: `python app.py`
   - **Environment**: Python 3.11
   - **HTTP Port**: 7860
5. Click "Deploy"

---

## Environment Variables (Optional)

You can configure the following environment variables:

```bash
# Port (default: 7860)
export PORT=8000

# Log level (default: INFO)
export LOG_LEVEL=DEBUG

# Database path (default: history.db)
export DATABASE_PATH=/path/to/history.db
```

---

## Post-Deployment Testing

### 1. Test Health Endpoint

```bash
curl https://your-deployment-url.com/health
```

Expected response:
```json
{
  "status": "healthy",
  "timestamp": "2025-11-10T...",
  "resources_loaded": true,
  "database_connected": true
}
```

### 2. Test Resource Listing

```bash
curl https://your-deployment-url.com/resources
```

### 3. Test Query Endpoint

```bash
curl -X POST https://your-deployment-url.com/query \
  -H "Content-Type: application/json" \
  -d '{
    "resource_type": "market_data",
    "resource_name": "coingecko",
    "endpoint": "/simple/price",
    "params": {
      "ids": "bitcoin",
      "vs_currencies": "usd"
    }
  }'
```

### 4. Test Status Monitoring

```bash
curl https://your-deployment-url.com/status
```

### 5. Run Full Test Suite

From your local machine:

```bash
# Update BASE_URL in test_aggregator.py
# Change: BASE_URL = "http://localhost:7860"
# To: BASE_URL = "https://your-deployment-url.com"

# Run tests
python test_aggregator.py
```

---

## Performance Optimization

### 1. Enable Caching

Add Redis for caching (optional):

```python
import redis
import json

# Connect to Redis
redis_client = redis.Redis(host='localhost', port=6379, decode_responses=True)

# Cache resource data
def get_cached_data(key, ttl=300):
    cached = redis_client.get(key)
    if cached:
        return json.loads(cached)
    return None

def set_cached_data(key, data, ttl=300):
    redis_client.setex(key, ttl, json.dumps(data))
```

### 2. Use Connection Pooling

Already implemented with `aiohttp.ClientSession`

### 3. Add Rate Limiting

Install:
```bash
pip install slowapi
```

Add to `app.py`:
```python
from slowapi import Limiter, _rate_limit_exceeded_handler
from slowapi.util import get_remote_address
from slowapi.errors import RateLimitExceeded

limiter = Limiter(key_func=get_remote_address)
app.state.limiter = limiter
app.add_exception_handler(RateLimitExceeded, _rate_limit_exceeded_handler)

@app.post("/query")
@limiter.limit("60/minute")
async def query_resource(request: Request, query: ResourceQuery):
    # ... existing code
```

### 4. Add Monitoring

Use Sentry for error tracking:

```bash
pip install sentry-sdk
```

```python
import sentry_sdk
from sentry_sdk.integrations.fastapi import FastApiIntegration

sentry_sdk.init(
    dsn="your-sentry-dsn",
    integrations=[FastApiIntegration()],
    traces_sample_rate=1.0,
)
```

---

## Security Best Practices

### 1. API Key Management

Store API keys in environment variables:

```python
import os

API_KEYS = {
    'etherscan': os.getenv('ETHERSCAN_API_KEY', 'default-key'),
    'coinmarketcap': os.getenv('CMC_API_KEY', 'default-key'),
}
```

### 2. Enable HTTPS

Most platforms (Hugging Face, Heroku, etc.) provide HTTPS by default.

For self-hosted, use Let's Encrypt:

```bash
# Install Certbot
sudo apt install certbot python3-certbot-nginx

# Get certificate
sudo certbot --nginx -d your-domain.com
```

### 3. Add Authentication (Optional)

```bash
pip install python-jose[cryptography] passlib[bcrypt]
```

```python
from fastapi.security import HTTPBearer, HTTPAuthorizationCredentials
from fastapi import Security

security = HTTPBearer()

@app.post("/query")
async def query_resource(
    query: ResourceQuery,
    credentials: HTTPAuthorizationCredentials = Security(security)
):
    # Verify token
    if credentials.credentials != "your-secret-token":
        raise HTTPException(status_code=401, detail="Invalid token")
    # ... existing code
```

---

## Monitoring & Maintenance

### 1. Monitor Logs

Hugging Face Spaces:
- View logs in the Space settings β†’ "Logs" tab

Docker:
```bash
docker logs -f crypto-aggregator
```

Systemd:
```bash
journalctl -u crypto-aggregator -f
```

### 2. Database Maintenance

Backup database regularly:

```bash
# Local backup
cp history.db history_backup_$(date +%Y%m%d).db

# Remote backup
scp user@server:/path/to/history.db ./backups/
```

Clean old records:

```sql
-- Remove records older than 30 days
DELETE FROM query_history WHERE timestamp < datetime('now', '-30 days');
DELETE FROM resource_status WHERE last_check < datetime('now', '-30 days');
```

### 3. Update Resources

To add new resources, update `all_apis_merged_2025.json` and redeploy.

### 4. Health Checks

Set up automated health checks:

```bash
# Cron job (every 5 minutes)
*/5 * * * * curl https://your-deployment-url.com/health || echo "API is down!"
```

Use UptimeRobot or similar service for monitoring.

---

## Troubleshooting

### Issue: Server won't start

**Solution:**
```bash
# Check if port 7860 is in use
lsof -i :7860

# Kill existing process
kill -9 $(lsof -t -i:7860)

# Or use a different port
PORT=8000 python app.py
```

### Issue: Database locked

**Solution:**
```bash
# Stop all instances
pkill -f app.py

# Remove lock (if exists)
rm history.db-journal

# Restart
python app.py
```

### Issue: High memory usage

**Solution:**
- Add connection limits
- Implement request queuing
- Scale horizontally with multiple instances

### Issue: API rate limits

**Solution:**
- Implement caching
- Add multiple API keys for rotation
- Use fallback resources

---

## Scaling

### Horizontal Scaling

Use a load balancer with multiple instances:

```yaml
# docker-compose-scaled.yml
version: '3.8'

services:
  aggregator:
    build: .
    deploy:
      replicas: 3
    environment:
      - WORKER_ID=${HOSTNAME}

  nginx:
    image: nginx:alpine
    ports:
      - "80:80"
    volumes:
      - ./nginx.conf:/etc/nginx/nginx.conf
    depends_on:
      - aggregator
```

### Vertical Scaling

Increase resources on your hosting platform:
- Hugging Face: Upgrade to paid tier
- AWS: Use larger EC2 instance
- Docker: Adjust container resources

---

## Support

For issues or questions:
1. Check `/health` endpoint
2. Review application logs
3. Test individual resources with `/status`
4. Verify database with SQLite browser

---

## Next Steps

After deployment:

1. **Integrate with your main app** using the provided client examples
2. **Set up monitoring** with health checks and alerts
3. **Configure backups** for the history database
4. **Add custom resources** by updating the JSON file
5. **Implement caching** for frequently accessed data
6. **Enable authentication** if needed for security

---

**Congratulations! Your Crypto Resource Aggregator is now deployed and ready to use!** πŸš€