Skip to content

Conversation

@ken-zlai
Copy link
Contributor

@ken-zlai ken-zlai commented Dec 18, 2024

Summary

I've made some updates to the environment variable configuration. Everything seems to work locally at http://localhost:5173/ and http://localhost:3000/, but I'm not sure if it will function correctly in the deployed environment.

The goal is to ensure the app calls the correct APIs both locally (using the URLs above) and in production current version. Currently, the issue is that client-side API calls don't have a public-facing endpoint to connect to.

@sean-zlai, could you take a look? Configuring environment variables in Svelte is still new to me. From what I understand, the variables should be exposed from this configuration once prefixed with PUBLIC_. Also linking Chewy's PR, which should add the load balancer and public-facing API URL for the client.

Checklist

  • Added Unit Tests
  • Covered by existing CI
  • Integration tested
  • Documentation update

Summary by CodeRabbit

  • New Features

    • Introduced a new configuration for API endpoints, supporting both development and production environments.
    • Added a function to dynamically determine the API base URL based on the deployment context.
  • Bug Fixes

    • Simplified the configuration for the frontend service by removing the API_BASE_URL variable.
  • Chores

    • Minor formatting adjustment in the networks section of the configuration file.

@coderabbitai
Copy link
Contributor

coderabbitai bot commented Dec 18, 2024

Walkthrough

The pull request introduces changes to the frontend API configuration by modifying how the base API URL is determined. The docker-init/compose.yaml file has had the API_BASE_URL environment variable removed from the frontend service. A new api-config.ts file has been created to handle API URL configuration dynamically, with a getApiBaseUrl() function that determines the appropriate URL based on the deployment environment (development or production). The api.ts file now uses this new configuration method to set the base API URL.

Changes

File Change Summary
docker-init/compose.yaml Removed API_BASE_URL environment variable from frontend service
frontend/src/lib/api/api-config.ts New file added with API_CONFIGS and getApiBaseUrl() function to manage API URLs for different environments
frontend/src/lib/api/api.ts Updated to use getApiBaseUrl() for determining the base API URL

Sequence Diagram

sequenceDiagram
    participant App as Frontend Application
    participant Config as API Config Module
    participant API as API Module

    App->>Config: Determine environment
    Config-->>App: Return appropriate API URL
    App->>API: Initialize with base URL
    API->>Server: Make API requests
Loading

Possibly Related PRs

Suggested Reviewers

  • piyush-zlai

Poem

🐰 A Rabbit's Ode to API Configuration 🌐

Localhost, production, dev or test,
Our API config now passes every quest!
No more hardcoded URLs to bind,
Flexibility and logic intertwined.
A dynamic path, both smooth and light,
Our frontend dances with delight! 🚀


🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Generate unit testing code for this file.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

@ken-zlai ken-zlai changed the title [wipconfigure frontend enviornment variables [wip] configure frontend enviornment variables Dec 18, 2024
Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 2

🔭 Outside diff range comments (2)
frontend/src/lib/api/api.ts (1)

Line range hint 13-23: Enhance error handling in send function

The current error handling doesn't provide enough context about API failures.

Consider this enhancement:

 async function send({ method, path }: { method: string; path: string }) {
   const opts = { method, headers: {} };
+  try {
+    const res = await fetch(`${base}/${path}`, opts);
+    if (res.ok) {
+      const text = await res.text();
+      return text ? JSON.parse(text) : {};
+    }
-    error(res.status);
+    const errorText = await res.text();
+    error(res.status, {
+      message: `API request failed: ${errorText}`,
+      code: res.status
+    });
+  } catch (e) {
+    error(500, {
+      message: `Network error: ${e.message}`,
+      code: 500
+    });
+  }
 }
docker-init/compose.yaml (1)

Line range hint 89-106: Add required environment variables for frontend service

The frontend service is missing the necessary environment variables for API configuration.

Add the following to the frontend service configuration:

   frontend:
     build:
       context: ..
       dockerfile: docker-init/frontend/Dockerfile
     depends_on:
       - app
+    environment:
+      - PUBLIC_API_EXTERNAL_URL=http://localhost:9000
+      - PUBLIC_API_BASE_URL=http://app:9000
     ports:
       - "3000:3000"
     healthcheck:
       test: ["CMD", "curl", "-f", "http://localhost:3000"]
       interval: 30s
       timeout: 10s
       retries: 3
       start_period: 40s
🧹 Nitpick comments (1)
frontend/src/lib/api/api.ts (1)

10-10: Consider making apiBaseUrl more dynamic

Setting the base URL as a module-level constant prevents it from updating if environment variables change during runtime.

Consider this approach:

-const apiBaseUrl = getApiBaseUrl();
-
-const base = `${apiBaseUrl}/api/v1`;

 async function send({ method, path }: { method: string; path: string }) {
+  const base = `${getApiBaseUrl()}/api/v1`;
   const opts = { method, headers: {} };
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro (Legacy)

📥 Commits

Reviewing files that changed from the base of the PR and between e127fb7 and f750e50.

📒 Files selected for processing (3)
  • docker-init/compose.yaml (1 hunks)
  • frontend/src/lib/api/api-config.ts (1 hunks)
  • frontend/src/lib/api/api.ts (1 hunks)
🔇 Additional comments (1)
docker-init/compose.yaml (1)

Line range hint 89-106: Verify frontend healthcheck endpoint

The healthcheck is testing the root endpoint, but we should verify if a more specific health endpoint exists.

✅ Verification successful

Let me check the content of these files to see if there are any specific health endpoints defined.


Let me check the actual frontend routes and components to see if there's any health-related endpoint implementation.


Let me check the root directory for any health check configurations in the frontend service.


Let me check the actual healthcheck configuration in the docker-compose file to understand what's currently being used.


Frontend healthcheck is using a basic endpoint test which is sufficient

The current healthcheck configuration for the frontend service is testing the root endpoint (http://localhost:3000) which is appropriate for this use case because:

  • It verifies that the HTTP server is up and responding
  • It's a lightweight check that doesn't put unnecessary load on the service
  • It follows common Docker healthcheck practices for frontend services

No changes are needed to the current healthcheck configuration.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Search for health-related endpoints in the frontend codebase
rg -l 'health|ping|status' frontend/src/

Length of output: 223


Script:

#!/bin/bash
# Check the content of api files for health-related endpoints
rg -A 5 'health|ping|status' frontend/src/lib/api/api.ts

Length of output: 158


Script:

#!/bin/bash
# Search for route definitions and health-related components
rg -A 5 "route|Route" frontend/src/

Length of output: 1694


Script:

#!/bin/bash
# Look for frontend service configuration files
fd -t f "frontend|health" . --exec grep -l "health\|healthcheck\|ping"

Length of output: 72


Script:

#!/bin/bash
# Check the healthcheck configuration in the docker-compose file
rg -A 5 "healthcheck" docker-init/compose.yaml

Length of output: 567

Comment on lines +4 to +13
const API_CONFIGS = {
dev: {
client: 'http://localhost:9000',
server: 'http://localhost:9000'
},
prod: {
client: env.PUBLIC_API_EXTERNAL_URL ?? 'http://localhost:9000',
server: env.PUBLIC_API_BASE_URL ?? 'http://app:9000'
}
};
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue

Review environment variable configuration and default values

The configuration structure has several concerns:

  1. Default URLs should not point to localhost in production
  2. The server URL in production points to 'http://' which isn't secure for production use

Consider these changes:

 const API_CONFIGS = {
 	dev: {
 		client: 'http://localhost:9000',
 		server: 'http://localhost:9000'
 	},
 	prod: {
-		client: env.PUBLIC_API_EXTERNAL_URL ?? 'http://localhost:9000',
-		server: env.PUBLIC_API_BASE_URL ?? 'http://app:9000'
+		client: env.PUBLIC_API_EXTERNAL_URL ?? '/api',
+		server: env.PUBLIC_API_BASE_URL ?? 'https://api.chronon.ai'
 	}
 };

Committable suggestion skipped: line range outside the PR's diff.

Comment on lines +15 to +18
export function getApiBaseUrl() {
const deployEnv = import.meta.env.PROD ? 'prod' : 'dev';
return browser ? API_CONFIGS[deployEnv].client : API_CONFIGS[deployEnv].server;
}
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🛠️ Refactor suggestion

Add error handling for missing environment variables in production

The current implementation silently falls back to default values in production, which could lead to unexpected behavior.

Consider adding validation:

 export function getApiBaseUrl() {
 	const deployEnv = import.meta.env.PROD ? 'prod' : 'dev';
+	if (deployEnv === 'prod') {
+		if (!env.PUBLIC_API_EXTERNAL_URL || !env.PUBLIC_API_BASE_URL) {
+			console.warn('Missing API configuration environment variables in production');
+		}
+	}
 	return browser ? API_CONFIGS[deployEnv].client : API_CONFIGS[deployEnv].server;
 }

Committable suggestion skipped: line range outside the PR's diff.

Comment on lines +10 to +11
client: env.PUBLIC_API_EXTERNAL_URL ?? 'http://localhost:9000',
server: env.PUBLIC_API_BASE_URL ?? 'http://app:9000'
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Just to make sure I understand,

  • PUBLIC_API_EXTERNAL_URL will point to the public DNS (ex. http://app.zipline.ai:9000, or AWS EC2 host/etc)
  • PUBLIC_API_BASE_URL will point to the internal DNS (ex. http://app:9000) based on docker compose.yml)

but they are both pointing at the same API/backend?

I wonder if we could either:

  • Only have a single URL per environment (dev/prod), but always fully qualifying it (always use app.zipline.ai, {instance}.us-west-1.elb.amazonaws.com, etc) instead of using the internal app:9000 for the server
  • Proxy requests through the frontend node server, so /apigoes tolocalhost:9000orapp:9000based on environment, but to the client it's always/api` (removes browser CORS issues as well)

Copy link
Contributor

@sean-zlai sean-zlai Dec 19, 2024

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Basically following the last note on the SvelteKit FAQ.

Something like:

src/routes/api/[...path]/+server.js

import { env } from '$env/dynamic/private'; // can be private (not `PUBLIC_` prefixed) since no longer needed client-side
import type { RequestHandler } from './$types';

export const GET: RequestHandler = ({ params, url }) => {
	return fetch(`https://${env.API_BASE_URL}/${params.path + url.search}`);
};

export const POST: RequestHandler = ({ params, url }) => {
	return fetch(`https://${env.API_BASE_URL}/${params.path + url.search}`);
};

// ... other methods as needed

@ken-zlai
Copy link
Contributor Author

We chose to use #143 as a solution instead

@ken-zlai ken-zlai closed this Dec 23, 2024
@sean-zlai sean-zlai deleted the ken/client-side-api-support branch May 12, 2025 19:04
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants