# Deploying to Google Cloud Run (Continuous Deployment via GitHub)

This guide describes how to configure Google Cloud Run to deploy the Fintra LVaR FastAPI service directly from your GitHub repository using Google Cloud Buildpacks (source-based deployment).

---

## 📋 Prerequisites

1. **Google Cloud Platform (GCP)** Account.
2. A **GitHub Repository** with the project files pushed.
3. Enabled APIs in your GCP Project:
   - **Cloud Run API**
   - **Artifact Registry API**
   - **Cloud Build API**

---

## 🚀 Deployment Instructions

### Step 1: Push Project Files to GitHub
Ensure you have committed and pushed the latest codebase (including the `Procfile` and `.gcloudignore` files) to your primary branch (e.g., `main`):
```bash
git add .
git commit -m "Configure Google Cloud Run Buildpacks deployment"
git push origin main
```

### Step 2: Configure Cloud Run to Deploy from GitHub
1. Open the [Google Cloud Console](https://console.cloud.google.com/).
2. Navigate to **Cloud Run** and click **Create Service** (or edit an existing one).
3. Under **Deployment platform**, choose **"Deploy continuously from a git repository"**.
4. Click **Set up with Cloud Build**:
   - **Repository Provider**: GitHub.
   - **Repository**: Choose your `lver-fastapi` repository.
   - Click **Next**.
   - **Branch**: Set to `main` (or the branch you want to deploy from).
   - **Build Type**: Select **Google Cloud Buildpacks**.
   - Click **Save**.
5. Set your **Service Name** (e.g., `fintra-lvar-fastapi`) and **Region** (e.g., `us-central1`).
6. Under **Ingress**, select **"Allow all traffic"** (or limit it based on your network architecture).
7. Under **Authentication**, prefer **"Require authentication"** (IAM) or put the service behind a gateway. "Allow unauthenticated invocations" is optional and should only be used **together with `API_KEY`** (see Step 3), which makes the app itself reject requests without a valid `X-API-Key: <API_KEY>` header (except `GET /` and the public `GET /ocr/health`, which you can use as the Cloud Run health probe).

### Step 3: Configure Environment Variables
Under the **Container(s), Volumes, Connections, Security** section:
* **Port**: Ensure the container port matches `8080` (Buildpacks automatically bind to `$PORT` which defaults to `8080` in Cloud Run).
* **Variables** (store secrets in Secret Manager, not in the repo):

| Variable | Purpose | Default / behavior when unset |
|---|---|---|
| `API_KEY` | Shared secret. When set, every endpoint except `GET /` and `GET /ocr/health` requires the header `X-API-Key: <value>` (no other auth form is accepted). Locally it can be set in a `.env` file (see `.env.example`). Set `ENV=production` as well, otherwise `/docs`, `/redoc` and `/openapi.json` stay publicly reachable. `sync.py` sends it automatically if `API_KEY` is set in its environment. | Unset = no authentication (a warning is logged at startup). **Set this in production.** |
| `PROJECT_ADMIN_NAME` / `PROJECT_ADMIN_PASSWORD` | Credentials accepted by `POST /lvar/project_init/{name}/{password}` and `/lvar/project_delete/...`. | Unset = these endpoints refuse every request ("Project not found or invalid credentials"). |
| `ALLOW_PROJECT_DELETE` | Set to `true` to let `/lvar/project_delete` actually drop tables and delete the DB file. | Off: delete requests are refused. |
| `ENV` | Set to `production` to disable `/docs`, `/redoc` and `/openapi.json`. | Docs enabled. |
| `MAX_REQUEST_LIST_ITEMS` | Maximum length of each list in request bodies. | `50000` (sync.py sends 20000 per batch). |
| `DATABASE_PATH` | LVaR SQLite file location (e.g. a mounted volume). | `app/lvar/storage/finStock.db` |
| `OCR_DATABASE_PATH` / `OCR_STORAGE_DIR` | OCR SQLite file and file storage (uploads, page images, markdown); point at a mounted volume. | `app/ocr/data/financial_ocr.db` / `app/ocr/storage` |
| `OCR_API_KEY` / `EXTRACT_API_KEY` / `MERGE_API_KEY` | Gemini key of each OCR-module step: OCR, extraction, merge (store in Secret Manager). Each step has its own rate limiter, so each key's per-minute and daily quota is used separately. | That step fails; `/ocr/health` reports `warn`. |
| `JOB_TTL_SEC` | How long finished `/ocr/jobs` results are kept in memory. | `3600` |
| `OCR_PAGE_PARALLELISM` | Pages of one OCR / extraction request processed at once; the shared rate limiter (`RATE_LIMIT_RPM`) still caps calls per minute. | `10` |
| `MERGE_MAX_GAP_REPORTS` | Merge: how many reports a line may skip and still be linked; 2+ skipped are flagged `LONG_GAP` for review. | `3` |
| `CORS_ORIGINS` | Comma-separated origins of browser front-ends. | `http://localhost:3030,http://127.0.0.1:3030` |
| `MAX_UPLOAD_MB` | Max size of one uploaded PDF / page image. | `50` |
| `SQLITE_TIMEOUT_SEC` | SQLite busy timeout. | `60` |

**Request timeout:** OCR and extraction call Gemini page by page, so a synchronous `/ocr/pipeline/ocr*` or `/ocr/pipeline/extract` request (and the merge stream) can run for minutes. Set the Cloud Run request timeout, and any proxy in front of it, to at least 300 s, or have the frontend use the `/ocr/jobs/*` endpoints, which return immediately and are polled.

**Single instance:** merge locks and background jobs are kept in memory, so run one instance (`--max-instances=1`) with the single uvicorn process from `Procfile`.

Note: Cloud Run's filesystem is ephemeral; SQLite data and OCR files are lost on instance restarts unless `DATABASE_PATH`, `OCR_DATABASE_PATH` and `OCR_STORAGE_DIR` point to a mounted volume.

### Step 4: Click Create
Cloud Run will trigger Cloud Build to compile your source code via Buildpacks, package it into a container image, push it to Artifact Registry, and deploy the service.

Once the deployment completes, Cloud Run will provide a secure **public URL** for your service (e.g., `https://fintra-lvar-fastapi-xxxx-uc.a.run.app`).

---

## 🛠️ Diagnostics & Logs

- **Deployment Logs**: If the build fails, check the logs under **Cloud Build** in the GCP Console.
- **Runtime Logs**: Runtime outputs can be viewed under the **Logs** tab of your service in the **Cloud Run** console.


deploy in local server
1. python -m venv .venv
2. .venv\Scripts\activate
3. pip install -r requirements.txt
4. uvicorn app.main:app --reload --host 0.0.0.0 --port 8000
