Overview
Cloud Functions for Firebase lets you run backend code in response to events triggered by Firebase features and HTTPS requests. This page documents all Cloud Functions deployed in the Luis IT Repair application.Configuration
Cloud Functions are configured infirebase.json:
Global Settings
The functions use the following global configuration:The
maxInstances limit helps control costs by preventing runaway scaling during traffic spikes. Individual functions can override this with their own maxInstances option.Functions
mlSearch
Type: HTTP FunctionRegion:
southamerica-east1Access: Public (no authentication required)
Endpoint:
/api/ml/search
Purpose
Searches MercadoLibre (Mexico) for products and returns structured results. This function enables the application to display marketplace prices for repair parts and accessories.Function Definition
Request Parameters
| Parameter | Type | Required | Description |
|---|---|---|---|
q | string | Yes | Search query |
limit | string | No | Max results (default: 12) |
debug | string | No | Enable debug mode (“1” for true) |
Example Request
Response Format
Search Strategy
The function uses a multi-layered search strategy:- API Search: Attempts official MercadoLibre API
- Token Refresh: Auto-refreshes OAuth token if expired
- HTML Fallback: Falls back to HTML scraping if API fails
- Query Variants: Tries multiple query variations
Query Variants
The function generates multiple search variants from the input:Environment Variables
The function uses optional environment variables for MercadoLibre API authentication:| Variable | Description | Required |
|---|---|---|
MELI_ACCESS_TOKEN | MercadoLibre access token | No |
MELI_CLIENT_ID | OAuth client ID | No* |
MELI_CLIENT_SECRET | OAuth client secret | No* |
MELI_REFRESH_TOKEN | OAuth refresh token | No* |
Setting Environment Variables
CORS Configuration
The function enables CORS for all origins:Error Handling
The function handles various error scenarios:| Error | Status Code | Response |
|---|---|---|
Missing q parameter | 400 | {error: "Parametro q requerido."} |
| Network/API error | 502 | {error: "No se pudo consultar..."} |
| No results found | 200 | {results: [], detail: "Sin resultados..."} |
Debug Mode
Enable debug mode to see diagnostic information:- API request attempts and status codes
- HTML scraping attempts and results
- Token refresh attempts
- Anti-bot detection hints
Helper Functions
The function includes several helper utilities:decodeHtmlEntities
Decodes HTML entities in text:stripHtml
Removes HTML tags from text:buildQueryVariants
Generates search query variations:parseMlSearchHtml
Extracts product data from MercadoLibre HTML:fetchMlApi
Calls the official MercadoLibre API:refreshMlAccessToken
Refreshes expired OAuth tokens:fetchMlHtml
Fetches and parses MercadoLibre HTML as a fallback:Hosting Integration
The function is integrated with Firebase Hosting via rewrites infirebase.json:
Deployment
Build and Deploy
View Logs
Cost Optimization
Instance Limits
The globalmaxInstances: 10 setting prevents runaway costs:
With 10 max instances, if traffic exceeds capacity, additional requests will queue or receive 429 errors instead of spawning more instances.
Region Selection
southamerica-east1 is selected for:
- Lower latency for Mexican users
- MercadoLibre API is region-specific (MLM = Mexico)
- Reduced cross-region data transfer costs
Function Optimization Tips
- Minimize cold starts: Keep functions warm with scheduled pings
- Reuse connections: Use global variables for HTTP clients
- Set timeouts: Prevent long-running functions
- Use caching: Cache frequently requested data
Local Development
Firebase Emulator
Run functions locally:Environment Variables for Emulator
Create.runtimeconfig.json in the functions/ directory:
Monitoring
Firebase Console
- Go to Firebase Console > Functions
- View metrics:
- Invocations per minute
- Execution time
- Error rate
- Memory usage
Cloud Logging
The function uses structured logging:Alerts
Set up alerts in Firebase Console:- Error rate threshold
- Execution time threshold
- Instance count threshold
Troubleshooting
Function Not Responding
- Check deployment status:
firebase functions:list - Check logs:
firebase functions:log --only mlSearch - Verify region matches hosting rewrite configuration
API Rate Limits
MercadoLibre may rate limit requests:- Use authenticated API calls when possible
- Implement client-side caching
- Consider adding Redis cache layer
HTML Scraping Failures
MercadoLibre may detect automated requests:- Rotate user agents
- Use authenticated API primarily
- Add delays between requests
- Check
antiBotHintin debug diagnostics
Security Considerations
- Public Access: The function is public, so implement rate limiting
- Input Validation: Always validate and sanitize query parameters
- Secrets Management: Use Firebase Functions config for secrets
- CORS: Currently allows all origins; restrict if needed
Future Enhancements
Potential improvements:- Add Redis caching for popular searches
- Implement request rate limiting
- Add support for other marketplaces
- Implement webhook for real-time price updates
- Add authentication for admin features
