-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsimple_backend.py
More file actions
7182 lines (6001 loc) · 298 KB
/
simple_backend.py
File metadata and controls
7182 lines (6001 loc) · 298 KB
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
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
from fastapi import FastAPI, File, UploadFile, HTTPException, Depends, Header, Request, Form, Body, BackgroundTasks
from fastapi.middleware.cors import CORSMiddleware
from fastapi.responses import StreamingResponse, JSONResponse
from fastapi.security import HTTPBearer, HTTPAuthorizationCredentials
from pydantic import BaseModel
import uvicorn
import json
import uuid
import os
import io
import ssl
import urllib3
import asyncio
import traceback
import time
import threading
from datetime import datetime
from typing import List, Dict, Any, Optional, Callable
from pathlib import Path
import tiktoken
import zipfile
# Import credit configuration
from credit_config import get_new_user_credits
from openai import OpenAI
import boto3
from botocore.config import Config
import html
from html.parser import HTMLParser
import re
import jwt
import hashlib
import hmac
import unicodedata
import requests
import certifi
import traceback
from PyPDF2 import PdfReader
from supabase import create_client, Client
from dotenv import load_dotenv
import stripe
from collections import defaultdict
from datetime import timedelta
from urllib.parse import urlparse
# Import custom modules
from prompts import get_analysis_prompt, get_tree_prompt
from errors import ChunkProcessingError, ContentPolicyError, TokenLimitError, ExtractionError, TreeBuildError
from utils import get_progress_message, log_chunk_analysis, log_source_processing, calculate_progress_percent
# Load environment variables with override to refresh from file
load_dotenv(override=True)
# Import Email Service module
try:
from email_service import (
send_account_creation_email,
send_incomplete_activation_email,
send_processing_complete_email,
log_email_event,
update_user_email_flag,
has_email_been_sent
)
EMAIL_SERVICE_AVAILABLE = True
print("✅ Email service module loaded")
except ImportError as e:
print(f"⚠️ Email service module not available: {e}")
EMAIL_SERVICE_AVAILABLE = False
# Import Memory Tree module (if enabled)
try:
from memory_tree import (
get_scope_for_source,
apply_chunk_to_memory_tree,
export_pack_from_tree
)
MEMORY_TREE_AVAILABLE = True
except ImportError as e:
print(f"⚠️ Memory Tree module not available: {e}")
MEMORY_TREE_AVAILABLE = False
# Configuration from environment variables
OPENAI_API_KEY = os.getenv("OPENAI_API_KEY")
SUPABASE_URL = os.getenv("NEXT_PUBLIC_SUPABASE_URL")
SUPABASE_SERVICE_KEY = os.getenv("SUPABASE_SERVICE_ROLE_KEY")
SUPABASE_JWT_SECRET = os.getenv("SUPABASE_JWT_SECRET") # Get this from Supabase Project Settings -> API
# Stripe configuration
STRIPE_SECRET_KEY = os.getenv("STRIPE_SECRET_KEY")
STRIPE_WEBHOOK_SECRET = os.getenv("STRIPE_WEBHOOK_SECRET")
stripe.api_key = STRIPE_SECRET_KEY
# R2 configuration
R2_ENDPOINT = os.getenv("R2_ENDPOINT")
R2_ACCESS_KEY = os.getenv("R2_ACCESS_KEY")
R2_SECRET_KEY = os.getenv("R2_SECRET_KEY")
R2_BUCKET = os.getenv("R2_BUCKET_NAME")
# Memory Tree feature flag
MEMORY_TREE_ENABLED = os.getenv("MEMORY_TREE_ENABLED", "false").lower() == "true"
# Concurrent processing configuration
MAX_CONCURRENT_CHUNKS = int(os.getenv("OPENAI_MAX_CONCURRENT_REQUESTS", "5"))
if MEMORY_TREE_ENABLED and MEMORY_TREE_AVAILABLE:
print("🌳 Memory Tree ENABLED - will populate knowledge graph during analysis")
elif MEMORY_TREE_ENABLED:
print("⚠️ Memory Tree ENABLED but module not available - check imports")
else:
print("📝 Memory Tree DISABLED - using text-only mode")
print(f"⚡ Concurrent chunk processing: {MAX_CONCURRENT_CHUNKS} chunks at a time")
# Create a properly configured requests session with SSL verification
r2_session = requests.Session()
r2_session.verify = certifi.where() # Use Mozilla's certificate bundle
print(f"🔒 SSL verification enabled using certificates from: {certifi.where()}")
# Initialize Supabase client
if SUPABASE_URL and SUPABASE_SERVICE_KEY:
supabase: Client = create_client(SUPABASE_URL, SUPABASE_SERVICE_KEY)
print(f"✅ Supabase client initialized with service role key (length: {len(SUPABASE_SERVICE_KEY)})")
print(f" Service key starts with: {SUPABASE_SERVICE_KEY[:20]}...")
else:
print("Warning: Supabase credentials not found. Running in legacy mode.")
supabase = None
from contextlib import asynccontextmanager
import asyncio
from concurrent.futures import ThreadPoolExecutor
@asynccontextmanager
async def lifespan(app: FastAPI):
# Increase the default thread pool size to prevent starvation
# during concurrent OpenAI calls and heavy chunking
loop = asyncio.get_running_loop()
executor = ThreadPoolExecutor(max_workers=50)
loop.set_default_executor(executor)
print("🚀 Configured asyncio default executor with 50 workers")
yield
executor.shutdown(wait=False)
app = FastAPI(title="Simple UCP Backend", version="1.0.0", lifespan=lifespan)
# CORS middleware - Configure allowed origins from environment
allowed_origins = os.getenv("ALLOWED_ORIGINS", "https://www.context-pack.com").split(",")
# Add additional domains that might be accessing the API
additional_origins = [
"https://www.context-pack.com",
"https://context-pack.com",
"https://universal-context-pack.vercel.app",
"https://universalcontextpack.vercel.app",
"http://localhost:3000",
"http://localhost:3001",
"*" # Allow all origins temporarily to debug CORS issue
]
app.add_middleware(
CORSMiddleware,
allow_origins=["*"], # Allow all origins temporarily
allow_credentials=True,
allow_methods=["GET", "POST", "PUT", "PATCH", "DELETE", "OPTIONS"],
allow_headers=["*"],
)
# Authentication
security = HTTPBearer()
# Rate limiting storage (in production, use Redis)
payment_attempts = defaultdict(list)
analysis_attempts = defaultdict(list)
def check_rate_limit(user_id: str, limit_type: str = "payment", max_attempts: int = 5, window_hours: int = 1):
"""Check if user has exceeded rate limit"""
now = datetime.utcnow()
window_start = now - timedelta(hours=window_hours)
# Choose the right storage
attempts_storage = payment_attempts if limit_type == "payment" else analysis_attempts
# Clean old attempts
user_attempts = [attempt for attempt in attempts_storage[user_id] if attempt > window_start]
attempts_storage[user_id] = user_attempts
# Check if limit exceeded
if len(user_attempts) >= max_attempts:
return False, len(user_attempts)
# Add current attempt
attempts_storage[user_id].append(now)
return True, len(user_attempts) + 1
# Email notification service
async def send_email_notification(user_email: str, job_id: str, chunks_processed: int, total_chunks: int, pack_id: str = None, success: bool = True):
"""Send email notification when a large job completes"""
try:
# Get email configuration from environment
EMAIL_HOST = os.getenv("EMAIL_HOST") # e.g., smtp.gmail.com
EMAIL_PORT = int(os.getenv("EMAIL_PORT", "587"))
EMAIL_USER = os.getenv("EMAIL_USER") # Your email address
EMAIL_PASSWORD = os.getenv("EMAIL_PASSWORD") # App password or email password
EMAIL_FROM = os.getenv("EMAIL_FROM", EMAIL_USER) # From email address
if success:
subject = "🎉 Your Universal Context Pack is Ready!"
message = f"""
Hello!
Your Universal Context Pack has been completed successfully and is now available for download.
Job Details:
- Job ID: {job_id}
- Chunks Processed: {chunks_processed}/{total_chunks}
- Status: Successfully Completed
Open your pack here:
{os.getenv('FRONTEND_URL', 'https://www.context-pack.com')}/process-v3?pack={pack_id}
Thank you for using Universal Context Pack!
Best regards,
The UCP Team
"""
else:
subject = "❌ Your Universal Context Pack Analysis Failed"
message = f"""
Hello!
Unfortunately, your Universal Context Pack analysis encountered an error and could not be completed.
Job Details:
- Job ID: {job_id}
- Chunks Processed: {chunks_processed}/{total_chunks}
- Status: Failed
Please try again or contact our support team if the issue persists.
Best regards,
The UCP Team
"""
# For now, just log the email (replace with actual email service)
print(f"📧 EMAIL NOTIFICATION for {user_email}:")
print(f"Subject: {subject}")
print(f"Message: {message}")
# Try webhook-based email service as primary option (more reliable on Railway)
WEBHOOK_EMAIL_URL = os.getenv("WEBHOOK_EMAIL_URL") # Optional webhook email service
RESEND_API_KEY = os.getenv("RESEND_API_KEY") # Resend.com API key
if RESEND_API_KEY:
try:
import requests
print(f"📧 Attempting to send email via Resend API...")
# Use verified domain for from address
from_email = "noreply@context-pack.com" # Use your verified domain
response = requests.post(
"https://api.resend.com/emails",
headers={
"Authorization": f"Bearer {RESEND_API_KEY}",
"Content-Type": "application/json"
},
json={
"from": f"Universal Context Pack <{from_email}>",
"to": [user_email],
"subject": subject,
"text": message
},
timeout=30
)
if response.status_code == 200:
print(f"✅ Email sent successfully via Resend to {user_email}")
return True
else:
print(f"❌ Resend API failed: {response.status_code} - {response.text}")
except Exception as resend_error:
print(f"❌ Resend email service failed: {resend_error}")
elif WEBHOOK_EMAIL_URL:
try:
import requests
print(f"📧 Attempting to send email via webhook: {WEBHOOK_EMAIL_URL}")
response = requests.post(
WEBHOOK_EMAIL_URL,
json={
"to": user_email,
"subject": subject,
"message": message,
"from": EMAIL_FROM
},
timeout=30
)
if response.status_code == 200:
print(f"✅ Email sent successfully via webhook to {user_email}")
return True
else:
print(f"❌ Webhook email failed: {response.status_code} - {response.text}")
except Exception as webhook_error:
print(f"❌ Webhook email service failed: {webhook_error}")
# Try to send actual email if SMTP is configured
if EMAIL_HOST and EMAIL_USER and EMAIL_PASSWORD:
try:
import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
import socket
print(f"🌐 Attempting SMTP connection to {EMAIL_HOST}:{EMAIL_PORT}")
# Test network connectivity first
try:
socket.create_connection((EMAIL_HOST, EMAIL_PORT), timeout=10)
print(f"✅ Network connection to {EMAIL_HOST}:{EMAIL_PORT} successful")
except socket.error as e:
print(f"❌ Network connection failed: {e}")
print("🔧 Trying alternative SMTP approaches...")
# Try port 465 (SSL) as fallback
try:
socket.create_connection((EMAIL_HOST, 465), timeout=10)
print(f"✅ Alternative SSL connection to {EMAIL_HOST}:465 successful")
EMAIL_PORT = 465
use_ssl = True
except socket.error:
print(f"❌ All SMTP connection attempts failed")
raise e
else:
use_ssl = False
# Create message
msg = MIMEMultipart()
msg['From'] = EMAIL_FROM
msg['To'] = user_email
msg['Subject'] = subject
# Add body to email
msg.attach(MIMEText(message, 'plain'))
# Create SMTP session with appropriate method
if use_ssl:
print(f"🔐 Using SSL connection on port 465")
server = smtplib.SMTP_SSL(EMAIL_HOST, 465, timeout=30)
else:
print(f"🔐 Using STARTTLS connection on port {EMAIL_PORT}")
server = smtplib.SMTP(EMAIL_HOST, EMAIL_PORT, timeout=30)
server.starttls() # Enable security
# Enable debug output
server.set_debuglevel(1)
print(f"🔑 Logging in with user: {EMAIL_USER}")
server.login(EMAIL_USER, EMAIL_PASSWORD)
# Send email
print(f"📤 Sending email to {user_email}")
text = msg.as_string()
server.sendmail(EMAIL_FROM, user_email, text)
server.quit()
print(f"✅ Email sent successfully to {user_email}")
return True
except Exception as email_error:
print(f"❌ Failed to send email via SMTP: {email_error}")
print(f"📊 Error type: {type(email_error).__name__}")
# Try one more fallback approach - direct port 25
try:
print(f"🔄 Attempting fallback SMTP on port 25...")
import smtplib
server = smtplib.SMTP(EMAIL_HOST, 25, timeout=30)
server.starttls()
server.login(EMAIL_USER, EMAIL_PASSWORD)
msg = MIMEMultipart()
msg['From'] = EMAIL_FROM
msg['To'] = user_email
msg['Subject'] = subject
msg.attach(MIMEText(message, 'plain'))
server.sendmail(EMAIL_FROM, user_email, msg.as_string())
server.quit()
print(f"✅ Email sent successfully via port 25 to {user_email}")
return True
except Exception as fallback_error:
print(f"❌ Fallback SMTP also failed: {fallback_error}")
# Fall back to console logging
print("📧 Email content (SMTP failed):")
print(f"To: {user_email}")
print(f"Subject: {subject}")
print(f"Body: {message}")
return False
else:
print("📧 SMTP not configured, email logged to console only")
print("To enable email sending, set EMAIL_HOST, EMAIL_USER, and EMAIL_PASSWORD environment variables")
return True # Consider logging as success for now
except Exception as e:
print(f"❌ Failed to send email notification to {user_email}: {e}")
return False
# Request models
class AnalyzeRequest(BaseModel):
selected_chunks: List[int] = [] # List of chunk indices to analyze
max_chunks: Optional[int] = None # Maximum number of chunks to analyze (limits the selection)
upload_method: Optional[str] = None # 'files' for Upload Export tab, 'url' for URL tab
class ChunkRequest(BaseModel):
chunk_size: Optional[int] = 600000 # Default to 600k characters (~150k tokens) - safe margin below GPT's limit
overlap: Optional[int] = 6000 # Proportional overlap
class CreditPurchaseRequest(BaseModel):
credits: int
amount: float
package_id: str = None
class StripePaymentIntentRequest(BaseModel):
credits: int
amount: float
unlimited: Optional[bool] = False
package_id: str = None
DEFAULT_PACK_NAME = "Untitled Pack"
def resolve_pack_name(pack_name: Optional[str]) -> str:
"""Normalize pack names and ensure newly created packs always have a non-empty name."""
if isinstance(pack_name, str):
normalized = pack_name.strip()
if normalized:
return normalized
return DEFAULT_PACK_NAME
class CreatePackRequest(BaseModel):
pack_name: str
description: Optional[str] = None
custom_system_prompt: Optional[str] = None
class AddSourceRequest(BaseModel):
source_name: str
source_type: str = "chat_export" # chat_export, document, url, text
class AddMemoryRequest(BaseModel):
text: str
source: str = "MCP Tool"
class PackReviewRequest(BaseModel):
rating: int # 1-5
feedback_text: Optional[str] = None
class LoginRequest(BaseModel):
email: str
password: str
class ChatGPTConversationRequest(BaseModel):
pack_id: str
conversation: Dict[str, Any] # Contains title and messages array
# User model for authentication
class AuthenticatedUser:
def __init__(self, user_id: str, email: str, r2_directory: str):
self.user_id = user_id
self.email = email
self.r2_directory = r2_directory
# Job logging helper
# In-memory progress tracking for real-time updates
job_progress = {}
job_progress_history = {} # Track all progress messages
active_streams = {} # Track active progress streams
# Real-time streaming generator
async def progress_stream_generator(job_id: str):
"""Generate progress updates in real-time for a specific job"""
# Initialize if not exists
if job_id not in job_progress_history:
job_progress_history[job_id] = []
last_sent_count = 0
while True:
try:
# Check if we have new progress updates
current_history = job_progress_history.get(job_id, [])
# Send any new progress updates immediately
if len(current_history) > last_sent_count:
for i in range(last_sent_count, len(current_history)):
progress_data = current_history[i]
yield f"data: {json.dumps(progress_data)}\n\n"
last_sent_count = len(current_history)
# Check if job is complete
job_status = job_progress.get(job_id, {})
if job_status.get('status') == 'completed' or job_status.get('status') == 'error':
yield f"data: {json.dumps({'type': 'complete', 'status': job_status.get('status')})}\n\n"
break
# Very short delay for responsiveness
await asyncio.sleep(0.05)
except Exception as e:
yield f"data: {json.dumps({'type': 'error', 'message': str(e)})}\n\n"
break
def update_job_progress(job_id: str, step: str, progress: int, message: str, current_chunk: int = None, total_chunks: int = None):
"""Update job progress with real-time information"""
timestamp = datetime.utcnow().isoformat()
progress_entry = {
"step": step,
"progress": progress,
"message": message,
"current_chunk": current_chunk,
"total_chunks": total_chunks,
"timestamp": timestamp,
"last_updated": datetime.utcnow().timestamp()
}
job_progress[job_id] = progress_entry
# Also add to history for real-time streaming
if job_id not in job_progress_history:
job_progress_history[job_id] = []
job_progress_history[job_id].append(progress_entry)
# Keep only last 50 progress entries to prevent memory bloat
if len(job_progress_history[job_id]) > 50:
job_progress_history[job_id] = job_progress_history[job_id][-50:]
def get_job_progress(job_id: str):
"""Get current job progress"""
return job_progress.get(job_id, {
"step": "unknown",
"progress": 0,
"message": "No progress available",
"current_chunk": None,
"total_chunks": None,
"timestamp": datetime.utcnow().isoformat(),
"last_updated": datetime.utcnow().timestamp()
})
async def get_user_payment_status(user_id: str) -> dict:
"""Get user's payment status and chunk limits"""
if not supabase:
# Legacy mode - allow unlimited for now
return {"plan": "legacy", "chunks_used": 0, "chunks_allowed": 999, "can_process": True}
try:
# Get user payment status using database function
result = supabase.rpc("get_user_payment_status", {"user_uuid": user_id}).execute()
if result.data:
return result.data
else:
# Fallback to manual calculation
profile_result = supabase.rpc("get_user_profile_for_backend", {"user_uuid": user_id}).execute()
if not profile_result.data:
# Create profile if it doesn't exist
create_result = supabase.rpc("create_user_profile_for_backend", {
"user_uuid": user_id,
"user_email": "unknown@example.com", # We don't have email here
"r2_dir": f"user_{user_id}"
}).execute()
# Get profile data directly
profile = supabase.table('user_profiles').select('*').eq('id', user_id).execute()
if profile.data and len(profile.data) > 0:
user_data = profile.data[0]
return {
"plan": user_data.get('payment_plan', 'free'),
"chunks_used": 0,
"chunks_allowed": user_data.get('credits_balance', get_new_user_credits()),
"credits_balance": user_data.get('credits_balance', get_new_user_credits()),
"subscription_status": user_data.get('subscription_status'),
"subscription_tier": user_data.get('subscription_tier'),
"can_process": True
}
return {"plan": "free", "chunks_used": 0, "chunks_allowed": get_new_user_credits(), "can_process": True}
except Exception as e:
print(f"Error getting payment status: {e}")
# Default to free plan
return {"plan": "free", "chunks_used": 0, "chunks_allowed": get_new_user_credits(), "can_process": True}
async def ensure_user_profile_exists(user_id: str, email: str) -> str:
"""
Ensure user profile exists in database (non-blocking).
Returns r2_directory path.
This is called asynchronously after auth to avoid blocking critical paths.
"""
if not supabase:
return f"user_{user_id}"
try:
# Quick check if profile exists
import asyncio
result = await asyncio.to_thread(
lambda: supabase.rpc("get_user_profile_for_backend", {"user_uuid": user_id}).execute()
)
if result.data:
return result.data.get("r2_user_directory", f"user_{user_id}")
# Profile doesn't exist, create it
r2_directory = f"user_{user_id}"
result = await asyncio.to_thread(
lambda: supabase.rpc("create_user_profile_for_backend", {
"user_uuid": user_id,
"user_email": email,
"r2_dir": r2_directory
}).execute()
)
if result.data:
return result.data.get("r2_user_directory", r2_directory)
return r2_directory
except Exception as e:
print(f"[ensure_user_profile_exists] Error: {e}")
return f"user_{user_id}"
async def get_current_user(credentials: HTTPAuthorizationCredentials = Depends(security)) -> AuthenticatedUser:
"""Validate JWT token and return authenticated user"""
try:
# Extract token
token = credentials.credentials
# Production: Always verify JWT signatures
if not SUPABASE_JWT_SECRET:
raise HTTPException(status_code=500, detail="JWT secret not configured")
try:
# First try with full verification
payload = jwt.decode(
token,
SUPABASE_JWT_SECRET,
algorithms=["HS256"],
audience="authenticated",
options={"verify_aud": True, "verify_signature": True}
)
except jwt.InvalidAudienceError:
# Try without audience verification but keep signature verification
payload = jwt.decode(
token,
SUPABASE_JWT_SECRET,
algorithms=["HS256"],
options={"verify_aud": False, "verify_signature": True}
)
user_id = payload.get("sub")
email = payload.get("email")
if not user_id:
raise HTTPException(status_code=401, detail="Invalid token: missing user ID")
# Email is optional, use user_id as fallback
if not email:
email = f"user_{user_id}@example.com"
# OPTIMIZED: Use default r2_directory without blocking database call
# Profile will be created asynchronously on first use if needed
r2_directory = f"user_{user_id}"
# Return immediately without blocking on profile creation
return AuthenticatedUser(user_id, email, r2_directory)
except jwt.ExpiredSignatureError as e:
raise HTTPException(status_code=401, detail="Token has expired")
except jwt.InvalidTokenError as e:
raise HTTPException(status_code=401, detail=f"Invalid token: {str(e)}")
except HTTPException:
# Re-raise HTTP exceptions as-is
raise
except Exception as e:
raise HTTPException(status_code=401, detail=f"Authentication failed: {str(e)}")
async def update_job_status_in_db(user: AuthenticatedUser, job_id: str, status: str, progress: int = None, error_message: str = None, metadata: dict = None):
"""Update job status in Supabase with enhanced cost tracking"""
if not supabase:
return None
try:
# First, let's check if the job exists using our backend function
job_check_result = supabase.rpc("check_job_exists_for_backend", {
"user_uuid": user.user_id,
"target_job_id": job_id
}).execute()
if not job_check_result.data or not job_check_result.data[0]["job_exists"]:
return None
else:
current_status = job_check_result.data[0]["current_status"]
# Extract data from metadata if provided
processed_chunks = None
total_chunks = None
total_input_tokens = None
total_output_tokens = None
total_cost = None
if metadata:
processed_chunks = metadata.get("processed_chunks")
total_chunks = metadata.get("total_chunks")
total_input_tokens = metadata.get("total_input_tokens")
total_output_tokens = metadata.get("total_output_tokens")
total_cost = metadata.get("total_cost")
# Use enhanced backend function to update job status with costs
result = supabase.rpc("update_job_status_with_costs_for_backend", {
"user_uuid": user.user_id,
"target_job_id": job_id,
"status_param": status,
"progress_param": progress,
"error_message_param": error_message,
"processed_chunks_param": processed_chunks,
"total_chunks_param": total_chunks,
"total_input_tokens_param": total_input_tokens,
"total_output_tokens_param": total_output_tokens,
"total_cost_param": total_cost
}).execute()
if result.data and len(result.data) > 0:
return result.data[0]
else:
return None
except Exception as e:
print(f"❌ Error updating job status in DB: {e}")
return None
# Initialize clients
# Default OpenAI client (fallback)
default_openai_client = OpenAI(api_key=OPENAI_API_KEY) if OPENAI_API_KEY else None
encoder = tiktoken.get_encoding("cl100k_base")
def get_openai_client(api_key: str = None) -> OpenAI:
"""
Get OpenAI client - always uses server's API key now
"""
# Always reload the current API key from environment
current_api_key = os.getenv("OPENAI_API_KEY")
if not current_api_key:
print("❌ No OpenAI API key found in environment variables")
raise HTTPException(status_code=500, detail="Server OpenAI API key not configured")
try:
return OpenAI(api_key=current_api_key)
except Exception as e:
print(f"❌ Error creating OpenAI client: {e}")
raise HTTPException(status_code=500, detail="Failed to initialize OpenAI client")
async def openai_call_with_retry(openai_client, max_retries=3, job_id=None, **kwargs):
"""
Make OpenAI API calls with retry logic for connection issues and quota handling
Supports cancellation checking if job_id is provided
"""
import time
import asyncio
from openai import OpenAI
# Check for cancellation before starting
if job_id and job_id in cancelled_jobs:
print(f"🚫 OpenAI call cancelled before starting for job {job_id}")
raise Exception(f"Job {job_id} was cancelled")
for attempt in range(max_retries):
try:
# Check for cancellation before each attempt
if job_id and job_id in cancelled_jobs:
print(f"🚫 OpenAI call cancelled during retry attempt {attempt + 1} for job {job_id}")
raise Exception(f"Job {job_id} was cancelled")
# Run the blocking OpenAI call in a thread pool to avoid blocking the event loop
response = await asyncio.to_thread(openai_client.chat.completions.create, **kwargs)
# Check for cancellation after call completes
if job_id and job_id in cancelled_jobs:
print(f"🚫 OpenAI call cancelled after completion for job {job_id}")
raise Exception(f"Job {job_id} was cancelled")
print(f"✅ OpenAI API call successful on attempt {attempt + 1}")
return response
except Exception as e:
# If it's a cancellation exception, don't retry
if job_id and job_id in cancelled_jobs:
print(f"🚫 Job {job_id} cancelled - aborting OpenAI call")
raise e
error_str = str(e).lower()
if attempt == 0: # Only log on first attempt to reduce noise
print(f"❌ OpenAI API error on attempt {attempt + 1}: {e}")
print(f"🔍 Error type: {type(e).__name__}")
# Don't retry quota/billing errors - fail immediately
if any(term in error_str for term in ['quota', 'insufficient_quota', 'billing', 'plan']):
print(f"💳 Quota/billing error detected - not retrying")
raise e
# Don't retry content policy errors - fail immediately
if any(term in error_str for term in ['content_policy', 'policy', 'safety']):
print(f"🚫 Content policy error detected - not retrying")
raise e
# Don't retry context length errors - fail immediately
if any(term in error_str for term in ['context_length', 'token limit', 'too long']):
print(f"📏 Context length error detected - not retrying")
raise e
# Retry connection/network errors
if attempt < max_retries - 1 and any(term in error_str for term in [
'connection', 'timeout', 'network', 'ssl', 'socket', 'read timed out'
]):
wait_time = (attempt + 1) * 2 # Exponential backoff: 2, 4, 6 seconds
print(f"🔄 Retrying in {wait_time} seconds due to connection error...")
# Check for cancellation during wait
for i in range(wait_time):
if job_id and job_id in cancelled_jobs:
print(f"🚫 Job {job_id} cancelled during retry wait")
raise Exception(f"Job {job_id} was cancelled")
await asyncio.sleep(1) # Sleep 1 second at a time to check cancellation
continue
else:
# Re-raise the exception if it's not a connection issue or we've exceeded retries
print(f"❌ Not retrying - either not a connection error or max retries exceeded")
raise e
raise Exception(f"OpenAI API failed after {max_retries} attempts")
# R2 client configuration - let's try with requests directly to avoid boto3 SSL issues
# Import for AWS signature v4
import hashlib
import hmac
from datetime import datetime
def sign_aws_request(method, url, headers, payload, access_key, secret_key, region='auto'):
"""Create AWS Signature Version 4 for R2"""
# Parse URL
parsed_url = urlparse(url)
host = parsed_url.netloc
path = parsed_url.path or '/'
# Create timestamp
t = datetime.utcnow()
datestamp = t.strftime('%Y%m%d')
timestamp = t.strftime('%Y%m%dT%H%M%SZ')
# Step 1: Create canonical request
canonical_headers = f"host:{host}\nx-amz-content-sha256:{hashlib.sha256(payload.encode()).hexdigest()}\nx-amz-date:{timestamp}\n"
signed_headers = "host;x-amz-content-sha256;x-amz-date"
canonical_request = f"{method}\n{path}\n\n{canonical_headers}\n{signed_headers}\n{hashlib.sha256(payload.encode()).hexdigest()}"
# Step 2: Create string to sign
algorithm = "AWS4-HMAC-SHA256"
credential_scope = f"{datestamp}/{region}/s3/aws4_request"
string_to_sign = f"{algorithm}\n{timestamp}\n{credential_scope}\n{hashlib.sha256(canonical_request.encode()).hexdigest()}"
# Step 3: Calculate signature
def sign(key, msg):
return hmac.new(key, msg.encode(), hashlib.sha256).digest()
signing_key = sign(f"AWS4{secret_key}".encode(), datestamp)
signing_key = sign(signing_key, region)
signing_key = sign(signing_key, "s3")
signing_key = sign(signing_key, "aws4_request")
signature = hmac.new(signing_key, string_to_sign.encode(), hashlib.sha256).hexdigest()
# Step 4: Add signing info to headers
authorization = f"{algorithm} Credential={access_key}/{credential_scope}, SignedHeaders={signed_headers}, Signature={signature}"
headers.update({
'Authorization': authorization,
'x-amz-date': timestamp,
'x-amz-content-sha256': hashlib.sha256(payload.encode()).hexdigest()
})
return headers
def calculate_upload_timeout(content_size_bytes: int) -> int:
"""Calculate dynamic timeout based on content size"""
base_timeout = 60 # Base 60 seconds for small files
mb_size = content_size_bytes / (1024 * 1024)
dynamic_timeout = int(base_timeout + (mb_size * 10)) # +10 seconds per MB
max_timeout = 300 # Cap at 5 minutes
return min(dynamic_timeout, max_timeout)
def upload_to_r2_direct(key: str, content: str, max_retries: int = 3):
"""Upload directly to R2 using requests with proper SSL verification, dynamic timeouts, and retry logic"""
import time
# Calculate content size and dynamic timeout
content_bytes = content.encode('utf-8', errors='ignore')
content_size = len(content_bytes)
timeout = calculate_upload_timeout(content_size)
print(f"📤 Uploading {key}: {content_size / (1024 * 1024):.2f} MB, timeout: {timeout}s")
# Retry loop with exponential backoff
for attempt in range(max_retries):
try:
# Construct the URL
url = f"{R2_ENDPOINT}/{R2_BUCKET}/{key}"
# Prepare headers
headers = {
'Content-Type': 'text/plain; charset=utf-8',
'Host': urlparse(R2_ENDPOINT).netloc
}
# Sign the request
headers = sign_aws_request('PUT', url, headers, content, R2_ACCESS_KEY, R2_SECRET_KEY)
# Make the request with proper SSL verification and better Unicode handling
try:
# Clean the content of any surrogate characters before encoding
clean_content = content_bytes.decode('utf-8')
response = r2_session.put(url, data=content_bytes, headers=headers, timeout=timeout)
except requests.exceptions.SSLError as ssl_error:
print(f"❌ SSL verification failed for R2 upload: {ssl_error}")
print(f"❌ Cannot upload to R2 due to SSL issues")
return False
except UnicodeEncodeError as ue:
print(f"Unicode encoding error: {ue}")
# More aggressive cleaning for surrogate pairs
import unicodedata
clean_content = ''.join(char for char in content if unicodedata.category(char) != 'Cs')
content_bytes = clean_content.encode('utf-8')
try:
response = r2_session.put(url, data=content_bytes, headers=headers, timeout=timeout)
except requests.exceptions.SSLError as ssl_error:
print(f"❌ SSL verification failed on retry: {ssl_error}")
print(f"❌ Cannot upload to R2 due to SSL issues")
return False
# Success - upload completed
if response.status_code in [200, 201]:
print(f"✅ R2 upload successful: {key} (attempt {attempt + 1}/{max_retries})")
return True
else:
print(f"❌ R2 upload failed: {response.status_code} - {response.text}")
print(f"❌ Failed to upload {key} to R2 bucket {R2_BUCKET}")
print(f"❌ Please verify your R2 bucket exists and credentials are correct")
return False
except (requests.exceptions.Timeout, TimeoutError) as timeout_error:
# Timeout error - retry with exponential backoff
if attempt < max_retries - 1:
wait_time = (2 ** attempt) * 2 # 2s, 4s, 8s
print(f"⏱️ Upload timeout on attempt {attempt + 1}/{max_retries}: {timeout_error}")
print(f"🔄 Retrying in {wait_time} seconds...")
time.sleep(wait_time)
continue
else:
print(f"❌ Upload timed out after {max_retries} attempts: {timeout_error}")
print(f"❌ Failed to upload {key} to R2 - file size: {content_size / (1024 * 1024):.2f} MB")
return False
except requests.exceptions.ConnectionError as conn_error:
# Connection error - retry with exponential backoff
if attempt < max_retries - 1: