Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion .python-version
Original file line number Diff line number Diff line change
@@ -1 +1 @@
3.12
3.11
121 changes: 121 additions & 0 deletions SERVERLESS_FUNCTION_FIX.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,121 @@
# Serverless Function Fix Summary

## Problem
The Vercel deployment was failing with error:
```
500: INTERNAL_SERVER_ERROR
Code: FUNCTION_INVOCATION_FAILED
ID: sin1::4kx9v-1759707297892-e7b7d2524a9f
```

## Root Cause
The recent deployment changes upgraded the Python version to 3.12, but Vercel's serverless Python runtime does not yet have full support for Python 3.12. This caused the function to fail during invocation.

## Changes Applied

### 1. Added `runtime.txt`
**File**: `runtime.txt` (new file)
**Content**: `python-3.11`

**Why**: Explicitly tells Vercel which Python version to use. Vercel has stable support for Python 3.9 and 3.11, but 3.12 support is still limited.

### 2. Updated `.python-version`
**File**: `.python-version`
**Change**: `3.12` → `3.11`

**Why**: Ensures consistency across development and production environments.

### 3. Updated `pyproject.toml`
**File**: `pyproject.toml`
**Changes**:
- `requires-python = ">=3.12"` → `requires-python = ">=3.11"`
- `target-version = ["py312"]` → `target-version = ["py311"]`

**Why**: Aligns project requirements with supported Python version.

### 4. Enhanced `vercel.json`
**File**: `vercel.json`
**Added**:
```json
{
"functions": {
"api/index.py": {
"runtime": "python3.11",
"maxDuration": 10
}
},
"rewrites": [...]
}
```

**Why**: Explicitly specifies the Python runtime for the serverless function, removing any ambiguity in Vercel's auto-detection.

### 5. Improved Error Handling in `config.py`
**File**: `src/app/core/config.py`
**Change**: Enhanced the `get_settings()` function to gracefully handle missing .env files and provide better error messages.

**Why**: Makes the application more resilient to missing environment variables during cold starts and provides clearer error messages for debugging.

### 6. Updated Documentation
**File**: `VERCEL_DEPLOYMENT.md`
**Changes**:
- Updated Python version references to 3.11
- Enhanced troubleshooting section with specific solutions for FUNCTION_INVOCATION_FAILED errors

## How to Deploy

1. **Ensure all changes are committed**:
```bash
git add .
git commit -m "fix: Downgrade to Python 3.11 for Vercel compatibility"
git push
```

2. **Redeploy to Vercel**:
```bash
vercel --prod
```

3. **Verify the deployment**:
- Check that the function starts successfully
- Visit the `/health` endpoint to verify the app is running
- Check Vercel logs for any errors

## Testing Locally

To verify the changes work locally:

```bash
# Install dependencies with Python 3.11
python3.11 -m venv venv
source venv/bin/activate
pip install -r requirements.txt

# Run the application
uvicorn app.main:app --reload
```

## Expected Outcome

After these changes:
- ✅ The serverless function should start successfully
- ✅ No more FUNCTION_INVOCATION_FAILED errors
- ✅ The application should be accessible at your Vercel URL
- ✅ The `/health` endpoint should return `{"status": "healthy"}`

## Environment Variables

Ensure these are set in your Vercel project:
- `SESSION_SECRET` (minimum 32 characters)
- `SUPABASE_URL` (optional, but recommended)
- `SUPABASE_ANON_KEY` (optional, but recommended)
- `SUPABASE_SERVICE_ROLE_KEY` (optional, but recommended)
- `ENVIRONMENT=production` (optional)

The application will start without Supabase credentials, but some features will be limited.

## References

- [Vercel Python Runtime Documentation](https://vercel.com/docs/functions/serverless-functions/runtimes/python)
- [Mangum ASGI Adapter](https://mangum.io/)
- [FastAPI Deployment Guide](https://fastapi.tiangolo.com/deployment/)
32 changes: 26 additions & 6 deletions VERCEL_DEPLOYMENT.md
Original file line number Diff line number Diff line change
Expand Up @@ -90,11 +90,31 @@ Check application logs at: `https://your-deployment-url/_logs`

### FUNCTION_INVOCATION_FAILED Error

If you see this error:
1. Check that all required environment variables are set
2. Review logs at `/_logs` endpoint
3. Ensure `SESSION_SECRET` is at least 32 characters
4. Verify Supabase credentials are correct
If you see this error, it typically means the serverless function cannot start. Common causes and solutions:

1. **Python Version Mismatch**:
- Ensure `runtime.txt` specifies `python-3.11`
- Vercel currently has best support for Python 3.9 and 3.11
- Python 3.12+ may not be fully supported yet

2. **Missing Environment Variables**:
- Check that all required environment variables are set in Vercel dashboard
- Use `vercel env ls` to list configured variables
- Ensure `SESSION_SECRET` is at least 32 characters in production

3. **Import Errors**:
- Verify all dependencies in `requirements.txt` are compatible
- Check Vercel build logs for import errors
- Ensure `mangum` is included in dependencies

4. **Configuration Issues**:
- Verify `vercel.json` has proper `functions` and `rewrites` configuration
- Check that `api/index.py` exports a `handler` variable
- Review logs at `/_logs` endpoint (if accessible)

5. **Supabase Credentials**:
- Verify Supabase credentials are correct
- The app will start without Supabase, but some features won't work

### Static Files Not Loading

Expand All @@ -105,7 +125,7 @@ If static files (CSS/JS) are not loading:

### Python Version

The application requires Python 3.12 or later. Vercel automatically detects and uses Python 3.12 based on the `pyproject.toml` configuration.
The application requires Python 3.11 or later. Vercel uses Python 3.11 as specified in the `runtime.txt` file. This ensures compatibility with Vercel's serverless Python runtime.

### Mangum Handler

Expand Down
4 changes: 2 additions & 2 deletions pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ version = "0.1.0"
description = "MVP web application for Sensasiwangi.id"
authors = [{ name = "Sensasiwangi Team" }]
readme = "README.md"
requires-python = ">=3.12"
requires-python = ">=3.11"
dependencies = [
"fastapi>=0.110",
"uvicorn[standard]>=0.27",
Expand All @@ -34,7 +34,7 @@ dev = [

[tool.black]
line-length = 88
target-version = ["py312"]
target-version = ["py311"]

[tool.ruff]
line-length = 88
Expand Down
1 change: 1 addition & 0 deletions runtime.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
python-3.11
20 changes: 17 additions & 3 deletions src/app/core/config.py
Original file line number Diff line number Diff line change
Expand Up @@ -61,6 +61,20 @@ def get_settings() -> Settings:
return settings
except Exception as e:
logger.error(f"Failed to load settings: {e}", exc_info=True)
# Return settings with defaults only
logger.warning("Using default settings without environment variables")
return Settings(_env_file=None)
# Try to create settings without loading .env file
logger.warning("Using default settings without .env file")
try:
# Create a new Settings class with env_file disabled
class SettingsNoEnv(Settings):
model_config = SettingsConfigDict(
env_file=None,
env_file_encoding="utf-8",
extra="ignore"
)
return SettingsNoEnv()
except Exception as e2:
logger.error(f"Failed to create default settings: {e2}", exc_info=True)
raise RuntimeError(
"Unable to initialize application settings. "
"Please ensure required environment variables are set or check the error logs."
) from e
6 changes: 6 additions & 0 deletions vercel.json
Original file line number Diff line number Diff line change
@@ -1,4 +1,10 @@
{
"functions": {
"api/index.py": {
"runtime": "python3.11",
"maxDuration": 10
}
},
"rewrites": [
{ "source": "/(.*)", "destination": "/api/index" }
]
Expand Down