[tab] /home/maharajamihir/Projects/coding-extension/INFRA_SETUP.md (markdown)
# AWS Serverless Backend Setup for VS Code Recorder Extension

This guide provides step-by-step instructions to set up the necessary AWS infrastructure for the VS Code Recorder extension's serverless backend. This includes creating an IAM Role for the Lambda function, deploying the Lambda function, and configuring API Gateway to expose the Lambda function as a public endpoint with guardrails.

**Assumptions:**

* You have an AWS account and access to the AWS Management Console.
* You have the AWS CLI configured (optional, but good for local testing/packaging).
* You have Node.js and npm/yarn installed to build the Lambda package.

---

## 1. Prepare the Lambda Deployment Package

Before deploying the Lambda function, you need to package its code and dependencies into a ZIP file.

1.  **Navigate to the `lambda-backend` directory:**
    ```bash
    cd lambda-backend
    ```

2.  **Install dependencies and build the TypeScript code:**
    ```bash
    npm install
    npm run build
    ```

3.  **Create the deployment package (ZIP file):**
    Navigate into the `dist` folder, then zip its contents along with `node_modules` and `package.json`.
    ```bash
    cd dist
    zip -r ../lambda-package.zip . ../node_modules ../package.json
    # Alternatively, for better control, ensure node_modules is directly in the root of the zip
    # From the lambda-backend directory:
    # zip -r lambda-package.zip dist node_modules package.json
    ```
    Ensure the `lambda-package.zip` file is created in the `lambda-backend` directory. The `index.js` (compiled from `index.ts`) should be at the root of the ZIP file when extracted.

---

## 2. Create IAM Role for AWS Lambda

This role will grant your Lambda function the necessary permissions to write to S3 and log to CloudWatch.

1.  **Go to the IAM Console:**
    * Open the AWS Management Console.
    * Search for "IAM" in the search bar and select "IAM".

2.  **Create a new Role:**
    * In the left-hand navigation pane, click on **Roles**.
    * Click the **Create role** button.

3.  **Select trusted entity:**
    * For "Trusted entity type", choose **AWS service**.
    * For "Use case", select **Lambda**.
    * Click **Next**.

4.  **Add permissions:**
    * In the "Add permissions" section, search for and select:
        * `AWSLambdaBasicExecutionRole` (This allows Lambda to write logs to CloudWatch Logs).
    * Click **Next**.

5.  **Name the role and create:**
    * For "Role name", enter `LambdaS3UploadRole` (or a similar descriptive name).
    * (Optional) Add a "Description" like "Role for Lambda to upload recording data to S3."
    * Click **Create role**.

6.  **Attach Custom Inline Policy for S3:**
    * Once the role is created, find and click on the role you just created (`LambdaS3UploadRole`).
    * On the role's summary page, click **Add permissions** -> **Create inline policy**.
    * Choose the **JSON** tab and paste the following policy:

        ```json
        {
            "Version": "2012-10-17",
            "Statement": [
                {
                    "Effect": "Allow",
                    "Action": [
                        "s3:PutObject"
                    ],
                    "Resource": "arn:aws:s3:::crowd-code-bucket/*"
                }
            ]
        }
        ```
    * Click **Next**.
    * For "Policy name", enter `S3PutObjectPolicy` (or a similar name).
    * Click **Create policy**.

    *Note: Ensure the S3 bucket `crowd-code-bucket` exists before the Lambda function attempts to write to it. If it doesn't, create it now in the S3 console.*

---

## 3. Deploy the AWS Lambda Function

Now you will create and deploy your Node.js Lambda function.

1.  **Go to the Lambda Console:**
    * Open the AWS Management Console.
    * Search for "Lambda" and select "Lambda".

2.  **Create a new Function:**
    * Click the **Create function** button.
    * Select **Author from scratch**.

3.  **Configure basic settings:**
    * **Function name:** `VSCodeRecordingUploader`
    * **Runtime:** Choose `Node.js 20.x` (or the latest LTS version available).
    * **Architecture:** `x86_64` (default)
    * **Permissions:**
        * Under "Change default execution role", select **Use an existing role**.
        * Choose the `LambdaS3UploadRole` (or the name you gave it) from the dropdown.
    * Click **Create function**.

4.  **Upload your code:**
    * Once the function is created, you'll be on its configuration page.
    * In the "Code source" section, click **Upload from** -> **.zip file**.
    * Click **Upload**, then select the `lambda-package.zip` file you created earlier.
    * Click **Save**.

5.  **Configure Handler:**
    * Make sure the **Runtime settings** (below "Code source") show the "Handler" as `index.handler`. If it's different (e.g., `app.handler`), click **Edit** and change it to `index.handler`.

---

## 4. Set up API Gateway

This will create a public HTTP endpoint that triggers your Lambda function.

1.  **Go to the API Gateway Console:**
    * Open the AWS Management Console.
    * Search for "API Gateway" and select "API Gateway".

2.  **Create a new REST API:**
    * Under "REST API", click **Build**.
    * Select **New API**.
    * **API name:** `VSCodeRecordingAPI`
    * **Endpoint Type:** `Regional` (default)
    * Click **Create API**.

3.  **Create a Resource:**
    * In the left-hand navigation pane, select **Resources** (under your API name).
    * Click **Actions** -> **Create Resource**.
    * **Resource Name:** `recordings`
    * **Resource Path:** `/recordings`
    * Click **Create Resource**.

4.  **Create a POST Method:**
    * With the `/recordings` resource selected, click **Actions** -> **Create Method**.
    * Select **POST** from the dropdown and click the checkmark.

5.  **Configure POST Method Integration:**
    * **Integration type:** `Lambda Function`
    * **Use Lambda Proxy integration:** Check this box (important for full event forwarding).
    * **Lambda Region:** Select the region where you deployed your Lambda function.
    * **Lambda Function:** Start typing `VSCodeRecordingUploader` and select your Lambda function from the dropdown.
    * **Timeout:** (Optional) Adjust if you expect long-running Lambda executions, but for this, default is usually fine.
    * Click **Save**.
    * When prompted, click **OK** to grant API Gateway permissions to invoke the Lambda function.

6.  **Enable CORS for the POST method:**
    * With the `/recordings` resource selected, click **Actions** -> **Enable CORS**.
    * Keep the default settings (or adjust `Access-Control-Allow-Origin` if you want to restrict specific origins, but for an "Open Endpoint", `*` is fine).
    * Click **Enable CORS and replace existing CORS headers**.
    * Click **Yes, replace existing values** when prompted.

7.  **Configure Throttling (Guardrails):**
    * In the API Gateway console, go to **Stages** (under your API name in the left navigation).
    * If you haven't deployed your API yet, deploy it first (see step 8).
    * Select your stage (e.g., `v1`).
    * Go to the **Throttling** tab.
    * Set the **Rate** (requests per second) and **Burst** (maximum concurrent requests) according to your expected traffic. For example:
        * **Rate:** `10`
        * **Burst:** `5`
    * Click **Save Changes**.

8.  **Deploy the API:**
    * In the left-hand navigation pane, select **Resources**.
    * Click **Actions** -> **Deploy API**.
    * **Deployment stage:**
        * Select `[New Stage]`
        * **Stage name:** `v1` (or another appropriate name like `prod`, `dev`)
    * Click **Deploy**.

---

## 5. Final Steps: Get Invoke URL and Update VS Code Extension

1.  **Retrieve the Invoke URL:**
    * After deploying, you will be taken to the Stage Editor page.
    * The **Invoke URL** for your API will be displayed at the top. It will look something like:
        `https://xxxxxxxxx.execute-api.your-region.amazonaws.com/v1/recordings`
    * **Copy this entire URL.**

2.  **Update the VS Code Extension:**
    * Open your VS Code extension project.
    * Go to `src/recording.ts`.
    * Replace the placeholder `YOUR_API_GATEWAY_ENDPOINT_URL_HERE` with the copied Invoke URL:

        ```typescript
        const API_GATEWAY_URL = '[https://xxxxxxxxx.execute-api.your-region.amazonaws.com/v1/recordings](https://xxxxxxxxx.execute-api.your-region.amazonaws.com/v1/recordings)';
        ```
    * Save the file.

3.  **Re-package and install the VS Code Extension:**
    * You'll need to rebuild and re-package your VS Code extension with the updated API Gateway URL.
    * From your extension's root directory, run:
        ```bash
        npm install
        npm run compile
        vsce package # If you have vsce installed
        ```
    * Then, install the new `.vsix` file into VS Code.

Now your VS Code extension will send recording data to your secure and scalable serverless backend!

---