diff --git a/.python-version b/.python-version index e4fba21..2c07333 100644 --- a/.python-version +++ b/.python-version @@ -1 +1 @@ -3.12 +3.11 diff --git a/SERVERLESS_FUNCTION_FIX.md b/SERVERLESS_FUNCTION_FIX.md new file mode 100644 index 0000000..91726c0 --- /dev/null +++ b/SERVERLESS_FUNCTION_FIX.md @@ -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/) diff --git a/VERCEL_DEPLOYMENT.md b/VERCEL_DEPLOYMENT.md index 90e1730..c08c97a 100644 --- a/VERCEL_DEPLOYMENT.md +++ b/VERCEL_DEPLOYMENT.md @@ -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 @@ -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 diff --git a/pyproject.toml b/pyproject.toml index db98b4c..01e1e0b 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -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", @@ -34,7 +34,7 @@ dev = [ [tool.black] line-length = 88 -target-version = ["py312"] +target-version = ["py311"] [tool.ruff] line-length = 88 diff --git a/runtime.txt b/runtime.txt new file mode 100644 index 0000000..67ebc4e --- /dev/null +++ b/runtime.txt @@ -0,0 +1 @@ +python-3.11 diff --git a/src/app/core/config.py b/src/app/core/config.py index 06a63cf..0687f0a 100644 --- a/src/app/core/config.py +++ b/src/app/core/config.py @@ -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 diff --git a/vercel.json b/vercel.json index 63e743a..61ec9f0 100644 --- a/vercel.json +++ b/vercel.json @@ -1,4 +1,10 @@ { + "functions": { + "api/index.py": { + "runtime": "python3.11", + "maxDuration": 10 + } + }, "rewrites": [ { "source": "/(.*)", "destination": "/api/index" } ]