Skip to content

armgit / kaneo

Public Imported from GitHub
0

⚡ Project management that doesn't become the project. Boards, Gantt charts, and GitHub integration. Self-host it or use Kaneo Cloud.

fix(api): resolve issue #1231 (#1257)

(justin)randoneering94072eec4c81
diff --git a/.env.sample b/.env.sample
index fa26e4031..229ae4c15 100644
--- a/.env.sample
+++ b/.env.sample
@@ -3,10 +3,14 @@
# KANEO_API_URL=http://localhost:1337 # optional — defaults to KANEO_CLIENT_URL/api
# Database
-# DATABASE_URL= # optional — derived from POSTGRES_* vars if unset
+# DATABASE_URL= # optional — use this for host-native or external DB access
POSTGRES_DB=kaneo
POSTGRES_USER=kaneo
POSTGRES_PASSWORD=
+# POSTGRES_HOST=postgres # Compose container default; use localhost for host-native API startup
+# POSTGRES_PORT=5432
+# Note: POSTGRES_DB and POSTGRES_USER alone do not enable derived connection mode.
+# Derived DATABASE_URL is only used when POSTGRES_PASSWORD or an explicit host/port is set.
# Redis Pub/Sub for WebSockets (Optional) -> auto fallback to in memory
# Only one mode should be configured. Priority: Cluster > Sentinel > Standalone.
diff --git a/.gitignore b/.gitignore
index d39b8d884..256b387f3 100644
--- a/.gitignore
+++ b/.gitignore
@@ -43,6 +43,9 @@ yarn-error.log*
# Cache
.cache/
+# Local worktrees
+.worktrees/
+
# Overrides
compose.override.yml
diff --git a/Dockerfile.kaneo b/Dockerfile.kaneo
index c58e6fcb1..e149d0617 100644
--- a/Dockerfile.kaneo
+++ b/Dockerfile.kaneo
@@ -56,20 +56,19 @@ COPY pnpm-workspace.yaml pnpm-lock.yaml package.json ./
COPY apps/web/package.json ./apps/web/
COPY packages/typescript-config/package.json ./packages/typescript-config/
COPY packages/libs/package.json ./packages/libs/
-
-RUN pnpm install --frozen-lockfile
-
COPY packages/typescript-config ./packages/typescript-config
COPY packages/libs ./packages/libs
COPY i18n ./i18n
COPY apps/web ./apps/web
+RUN pnpm install --frozen-lockfile
+
WORKDIR /app/apps/web
RUN pnpm run build
FROM node:20.20.2-alpine AS runtime
-RUN apk add --no-cache nginx=1.28.3-r0 && \
+RUN apk add --no-cache nginx=1.28.3-r1 && \
addgroup -g 1001 appuser && \
adduser -u 1001 -G appuser -D appuser && \
mkdir -p /app /app/apps/api/data /var/cache/nginx /var/run/nginx /var/log/nginx /var/lib/nginx/logs /var/lib/nginx/tmp /usr/share/nginx/html /docker-entrypoint.d && \
diff --git a/ENVIRONMENT_SETUP.md b/ENVIRONMENT_SETUP.md
index 389af72e1..c844b1c8b 100644
--- a/ENVIRONMENT_SETUP.md
+++ b/ENVIRONMENT_SETUP.md
@@ -136,6 +136,16 @@ For a complete list of all environment variables, their descriptions, and config
- Ensure the connection string format is correct
- Check username, password, host, port, and database name
+3. **Match the hostname to where the API runs:**
+ - Use `postgres` only when the API container is on the same Docker Compose network as the Postgres service
+ - Use `localhost` when the API runs directly on your host machine
+ - If you see `getaddrinfo EAI_AGAIN postgres`, the API is trying to resolve the Compose hostname from the wrong network context
+
+4. **Use the right configuration mode:**
+ - For host-native development, prefer an explicit `DATABASE_URL`
+ - If you derive from `POSTGRES_*`, set `POSTGRES_HOST=localhost` when running the API on your host
+ - `POSTGRES_DB` and `POSTGRES_USER` by themselves do not switch Kaneo into derived connection mode
+
### Authentication Issues
**Symptoms:**
diff --git a/README.md b/README.md
index 9e5e6e694..2386338b0 100644
--- a/README.md
+++ b/README.md
@@ -103,6 +103,9 @@ volumes:
Save this as `compose.yml`, create a `.env` file with `KANEO_CLIENT_URL=http://localhost:5173`, `POSTGRES_PASSWORD=<password>`, and `AUTH_SECRET=<output of openssl rand -hex 32>`, run `docker compose up -d`, and open [http://localhost:5173](http://localhost:5173).
+In Docker Compose, the bundled Kaneo container reaches PostgreSQL at the service hostname `postgres`.
+If you run the API on your host instead of inside Compose, use `localhost` or set `DATABASE_URL` explicitly.
+
> **Important:** See our [full documentation](https://kaneo.app/docs/core) for detailed setup instructions, environment variable configuration, and troubleshooting guides.
### Development Setup
diff --git a/apps/api/drizzle.config.ts b/apps/api/drizzle.config.ts
index 9e41ad886..dc670022b 100644
--- a/apps/api/drizzle.config.ts
+++ b/apps/api/drizzle.config.ts
@@ -1,5 +1,6 @@
import { config } from "dotenv-mono";
import { type Config, defineConfig } from "drizzle-kit";
+import { resolveDatabaseConnectionString } from "./src/database/resolve-database-url";
config();
@@ -8,8 +9,6 @@ export default defineConfig({
schema: "./src/database/schema.ts",
dialect: "postgresql",
dbCredentials: {
- url:
- process.env.DATABASE_URL ||
- "postgresql://kaneo_user:kaneo_password@localhost:5432/kaneo",
+ url: resolveDatabaseConnectionString(),
},
}) satisfies Config;
diff --git a/apps/api/src/database/index.ts b/apps/api/src/database/index.ts
index f25729beb..51685ff7d 100644
--- a/apps/api/src/database/index.ts
+++ b/apps/api/src/database/index.ts
@@ -30,6 +30,7 @@ import {
workspaceTableRelations,
workspaceUserTableRelations,
} from "./relations";
+import { resolveDatabaseConnectionString } from "./resolve-database-url";
import {
accountTable,
activityTable,
@@ -63,12 +64,6 @@ import {
config();
-export const pool = new Pool({
- connectionString:
- process.env.DATABASE_URL ||
- "postgresql://kaneo_user:kaneo_password@localhost:5432/kaneo",
-});
-
export const schema = {
accountTable,
assetTable,
@@ -127,8 +122,41 @@ export const schema = {
workspaceUserTableRelations,
};
-const db = drizzle(pool, {
- schema: schema,
+type DatabaseInstance = ReturnType<typeof drizzle<typeof schema>>;
+
+let pool: Pool | undefined;
+let dbInstance: DatabaseInstance | undefined;
+
+export function getDatabasePool(): Pool {
+ if (!pool) {
+ pool = new Pool({
+ connectionString: resolveDatabaseConnectionString(),
+ });
+ }
+
+ return pool;
+}
+
+export function getDatabase(): DatabaseInstance {
+ if (!dbInstance) {
+ dbInstance = drizzle(getDatabasePool(), {
+ schema,
+ });
+ }
+
+ return dbInstance;
+}
+
+const db = new Proxy({} as DatabaseInstance, {
+ get(_target, property, receiver) {
+ const value = Reflect.get(getDatabase(), property, receiver);
+
+ if (typeof value === "function") {
+ return value.bind(getDatabase());
+ }
+
+ return value;
+ },
});
export default db;
diff --git a/apps/api/src/database/prepare-database-startup.ts b/apps/api/src/database/prepare-database-startup.ts
new file mode 100644
index 000000000..170b0e2fb
--- /dev/null
+++ b/apps/api/src/database/prepare-database-startup.ts
@@ -0,0 +1,54 @@
+import type { ResolvedDatabaseConfig } from "./resolve-database-url";
+import { resolveDatabaseConfig } from "./resolve-database-url";
+
+type PrepareDatabaseStartupOptions = {
+ resolveConfig?: () => ResolvedDatabaseConfig;
+ waitForDatabase: () => Promise<void>;
+ runStartupMigrations: () => Promise<void>;
+ logInfo?: (message: string, ...args: unknown[]) => void;
+ logError?: (message: string, ...args: unknown[]) => void;
+};
+
+export async function prepareDatabaseStartup({
+ resolveConfig = resolveDatabaseConfig,
+ waitForDatabase,
+ runStartupMigrations,
+ logInfo = console.log,
+ logError = console.error,
+}: PrepareDatabaseStartupOptions): Promise<void> {
+ let config: ResolvedDatabaseConfig;
+
+ try {
+ config = resolveConfig();
+ } catch (error) {
+ logError("❌ Database configuration failed", error);
+
+ throw new Error("Database configuration failed during startup.", {
+ cause: error,
+ });
+ }
+
+ logInfo("🔄 Preparing database startup", config.logConfig);
+
+ try {
+ await waitForDatabase();
+ } catch (error) {
+ logError("❌ Database readiness check failed", config.logConfig, error);
+
+ throw new Error(
+ `Database startup failed for ${config.host}:${config.port}/${config.database} (source: ${config.source}). If you are running outside Docker Compose, use localhost or set DATABASE_URL explicitly.`,
+ { cause: error },
+ );
+ }
+
+ try {
+ await runStartupMigrations();
+ } catch (error) {
+ logError("❌ Database migrations failed", config.logConfig, error);
+
+ throw new Error(
+ `Database migrations failed for ${config.host}:${config.port}/${config.database} (source: ${config.source}).`,
+ { cause: error },
+ );
+ }
+}
diff --git a/apps/api/src/database/resolve-database-url.ts b/apps/api/src/database/resolve-database-url.ts
new file mode 100644
index 000000000..86c69c264
--- /dev/null
+++ b/apps/api/src/database/resolve-database-url.ts
@@ -0,0 +1,79 @@
+const LOCAL_FALLBACK_CONNECTION_STRING = "postgresql://localhost:5432/kaneo";
+
+type DatabaseConfigSource = "DATABASE_URL" | "POSTGRES_ENV" | "LOCAL_FALLBACK";
+
+export type ResolvedDatabaseConfig = {
+ connectionString: string;
+ source: DatabaseConfigSource;
+ host: string;
+ port: number;
+ database: string;
+ username: string;
+ logConfig: {
+ source: DatabaseConfigSource;
+ host: string;
+ port: number;
+ database: string;
+ username: string;
+ };
+};
+
+function getDerivationSignal(): boolean {
+ return Boolean(
+ process.env.POSTGRES_PASSWORD ||
+ process.env.POSTGRES_HOST ||
+ process.env.POSTGRES_PORT,
+ );
+}
+
+function toResolvedConfig(
+ connectionString: string,
+ source: DatabaseConfigSource,
+): ResolvedDatabaseConfig {
+ const url = new URL(connectionString);
+
+ const logConfig = {
+ source,
+ host: url.hostname,
+ port: Number(url.port || 5432),
+ database: url.pathname.replace(/^\//, ""),
+ username: decodeURIComponent(url.username),
+ };
+
+ return {
+ connectionString,
+ ...logConfig,
+ logConfig,
+ };
+}
+
+export function resolveDatabaseConfig(): ResolvedDatabaseConfig {
+ if (process.env.DATABASE_URL) {
+ return toResolvedConfig(process.env.DATABASE_URL, "DATABASE_URL");
+ }
+
+ if (getDerivationSignal()) {
+ if (!process.env.POSTGRES_PASSWORD) {
+ throw new Error(
+ "POSTGRES_PASSWORD must be set when deriving DATABASE_URL from POSTGRES_* variables",
+ );
+ }
+
+ const username = process.env.POSTGRES_USER || "kaneo";
+ const password = encodeURIComponent(process.env.POSTGRES_PASSWORD);
+ const host = process.env.POSTGRES_HOST || "postgres";
+ const port = process.env.POSTGRES_PORT || "5432";
+ const database = process.env.POSTGRES_DB || "kaneo";
+
+ return toResolvedConfig(
+ `postgresql://${encodeURIComponent(username)}:${password}@${host}:${port}/${database}`,
+ "POSTGRES_ENV",
+ );
+ }
+
+ return toResolvedConfig(LOCAL_FALLBACK_CONNECTION_STRING, "LOCAL_FALLBACK");
+}
+
+export function resolveDatabaseConnectionString(): string {
+ return resolveDatabaseConfig().connectionString;
+}
diff --git a/apps/api/src/database/wait-for-database.ts b/apps/api/src/database/wait-for-database.ts
new file mode 100644
index 000000000..836ba2c22
--- /dev/null
+++ b/apps/api/src/database/wait-for-database.ts
@@ -0,0 +1,46 @@
+type WaitForDatabaseOptions = {
+ query: () => Promise<unknown>;
+ sleep?: (delayMs: number) => Promise<void>;
+ maxAttempts?: number;
+ retryDelayMs?: number;
+};
+
+function defaultSleep(delayMs: number): Promise<void> {
+ return new Promise((resolve) => {
+ setTimeout(resolve, delayMs);
+ });
+}
+
+export async function waitForDatabase({
+ query,
+ sleep = defaultSleep,
+ maxAttempts = 30,
+ retryDelayMs = 1_000,
+}: WaitForDatabaseOptions): Promise<void> {
+ if (maxAttempts < 1) {
+ throw new RangeError(`maxAttempts must be at least 1, got ${maxAttempts}`);
+ }
+
+ if (retryDelayMs < 0) {
+ throw new RangeError(
+ `retryDelayMs must be non-negative, got ${retryDelayMs}`,
+ );
+ }
+
+ let lastError: unknown;
+
+ for (let attempt = 1; attempt <= maxAttempts; attempt += 1) {
+ try {
+ await query();
+ return;
+ } catch (error) {
+ lastError = error;
+
+ if (attempt === maxAttempts) {
+ throw lastError;
+ }
+
+ await sleep(retryDelayMs);
+ }
+ }
+}
diff --git a/apps/api/src/index.ts b/apps/api/src/index.ts
index 989969185..b17907ee4 100644
--- a/apps/api/src/index.ts
+++ b/apps/api/src/index.ts
@@ -3,7 +3,7 @@ import { fileURLToPath, pathToFileURL } from "node:url";
import { serve } from "@hono/node-server";
import { createNodeWebSocket } from "@hono/node-ws";
import type { Session, User } from "better-auth/types";
-import { eq } from "drizzle-orm";
+import { eq, sql } from "drizzle-orm";
import { migrate } from "drizzle-orm/node-postgres/migrator";
import { Hono } from "hono";
import { cors } from "hono/cors";
@@ -20,7 +20,9 @@ import { auth } from "./auth";
import column from "./column";
import comment from "./comment";
import config from "./config";
-import db, { schema } from "./database";
+import db, { getDatabase, schema } from "./database";
+import { prepareDatabaseStartup } from "./database/prepare-database-startup";
+import { waitForDatabase } from "./database/wait-for-database";
import discordIntegration from "./discord-integration";
import { eventContext } from "./events";
import externalLink from "./external-link";
@@ -598,14 +600,25 @@ export function createApp() {
export async function runStartupTasks() {
const currentDir = dirname(fileURLToPath(import.meta.url));
- await migrateWorkspaceUserEmail();
- await migrateSessionColumn();
+ await prepareDatabaseStartup({
+ waitForDatabase: async () => {
+ await waitForDatabase({
+ query: async () => {
+ await getDatabase().execute(sql`SELECT 1`);
+ },
+ });
+ },
+ runStartupMigrations: async () => {
+ await migrateWorkspaceUserEmail();
+ await migrateSessionColumn();
- console.log("🔄 Migrating database...");
- await migrate(db, {
- migrationsFolder: `${currentDir}/../drizzle`,
+ console.log("🔄 Migrating database...");
+ await migrate(getDatabase(), {
+ migrationsFolder: `${currentDir}/../drizzle`,
+ });
+ console.log("✅ Database migrated successfully!");
+ },
});
- console.log("✅ Database migrated successfully!");
// After Drizzle migrations: apikey table must exist so we can align columns
// with Better Auth (reference_id + nullable user_id).
diff --git a/apps/docs/core/installation/docker-compose.mdx b/apps/docs/core/installation/docker-compose.mdx
index 2d34bec9c..d819d906e 100644
--- a/apps/docs/core/installation/docker-compose.mdx
+++ b/apps/docs/core/installation/docker-compose.mdx
@@ -70,6 +70,9 @@ Set `KANEO_API_URL` explicitly only if you need to override the default (e.g. a
This keeps the browser on one origin while the container proxies `/api` requests to the internal API process.
+For this Compose setup, the bundled Kaneo container reaches PostgreSQL at the service hostname `postgres`.
+If you run the API directly on your host instead, use `localhost` or set `DATABASE_URL` explicitly.
+
## Notes on object storage
Kaneo uses S3-compatible object storage for private uploads in task descriptions and comments.
diff --git a/apps/docs/core/installation/migration.mdx b/apps/docs/core/installation/migration.mdx
index 5678b5e6e..43f0857a7 100644
--- a/apps/docs/core/installation/migration.mdx
+++ b/apps/docs/core/installation/migration.mdx
@@ -119,13 +119,14 @@ KANEO_CLIENT_URL=https://kaneo.example.com
### DATABASE_URL is now optional
-`DATABASE_URL` is derived from `POSTGRES_USER`, `POSTGRES_PASSWORD`, and `POSTGRES_DB` if you leave it unset:
+For the bundled image, `DATABASE_URL` is derived from `POSTGRES_USER`, `POSTGRES_PASSWORD`, `POSTGRES_DB`, and the default Compose hostname if you leave it unset:
```
postgresql://${POSTGRES_USER}:${POSTGRES_PASSWORD}@postgres:5432/${POSTGRES_DB}
```
-If you were setting `DATABASE_URL` explicitly with the same values, you can remove it. Keep it if you use an external database or a non-default hostname.
+If you were setting `DATABASE_URL` explicitly with the same values, you can remove it.
+Keep it if you use an external database, a non-default hostname, or a host-native API process that should connect through `localhost` instead of the Compose hostname.
**Before:**
```env
diff --git a/deploy/kaneo-entrypoint.sh b/deploy/kaneo-entrypoint.sh
index 6ca0fe049..156561a76 100644
--- a/deploy/kaneo-entrypoint.sh
+++ b/deploy/kaneo-entrypoint.sh
@@ -28,7 +28,9 @@ if [ -z "${KANEO_API_URL:-}" ] && [ -n "$client_url" ]; then
echo "KANEO_API_URL not set — derived from KANEO_CLIENT_URL: $KANEO_API_URL"
fi
-# Derive DATABASE_URL from individual postgres vars if not explicitly set
+# Derive DATABASE_URL for the bundled image when it is not explicitly set.
+# This image requires either DATABASE_URL or POSTGRES_PASSWORD so startup
+# fails fast instead of silently falling back to localhost inside the container.
if [ -z "${DATABASE_URL:-}" ]; then
POSTGRES_DB="${POSTGRES_DB:-kaneo}"
POSTGRES_USER="${POSTGRES_USER:-kaneo}"
@@ -38,7 +40,7 @@ if [ -z "${DATABASE_URL:-}" ]; then
export DATABASE_URL="postgresql://${encoded_user}:${encoded_password}@${POSTGRES_HOST:-postgres}:${POSTGRES_PORT:-5432}/${POSTGRES_DB}"
echo "DATABASE_URL not set — derived from POSTGRES_* vars"
else
- echo "ERROR: DATABASE_URL is not set and POSTGRES_PASSWORD is not set" >&2
+ echo "ERROR: DATABASE_URL is not set and POSTGRES_PASSWORD is not set for bundled-image startup" >&2
exit 1
fi
fi
diff --git a/packages/email/tsconfig.json b/packages/email/tsconfig.json
index a70ba3577..41713f753 100644
--- a/packages/email/tsconfig.json
+++ b/packages/email/tsconfig.json
@@ -29,5 +29,5 @@
"noImplicitAny": true
},
"include": ["src"],
- "exclude": ["node_modules"]
+ "exclude": ["node_modules", "src/**/*.test.ts", "src/**/*.test.tsx"]
}
diff --git a/tests/api/database/prepare-database-startup.test.ts b/tests/api/database/prepare-database-startup.test.ts
new file mode 100644
index 000000000..a48f2be00
--- /dev/null
+++ b/tests/api/database/prepare-database-startup.test.ts
@@ -0,0 +1,150 @@
+import { describe, expect, it, vi } from "vitest";
+import { prepareDatabaseStartup } from "../../../apps/api/src/database/prepare-database-startup";
+
+describe("prepare-database-startup", () => {
+ it("waits for database readiness before running startup migrations", async () => {
+ const events: string[] = [];
+
+ await prepareDatabaseStartup({
+ resolveConfig: () => ({
+ connectionString: "postgresql://kaneo:password@postgres:5432/kaneo",
+ source: "POSTGRES_ENV",
+ host: "postgres",
+ port: 5432,
+ database: "kaneo",
+ username: "kaneo",
+ logConfig: {
+ source: "POSTGRES_ENV",
+ host: "postgres",
+ port: 5432,
+ database: "kaneo",
+ username: "kaneo",
+ },
+ }),
+ waitForDatabase: async () => {
+ events.push("wait");
+ },
+ runStartupMigrations: async () => {
+ events.push("migrate");
+ },
+ logInfo: () => {
+ events.push("log");
+ },
+ });
+
+ expect(events).toEqual(["log", "wait", "migrate"]);
+ });
+
+ it("surfaces safe database details and skips migrations when readiness fails", async () => {
+ const waitError = new Error("getaddrinfo EAI_AGAIN postgres");
+ const runStartupMigrations = vi.fn();
+ const logError = vi.fn();
+
+ await expect(
+ prepareDatabaseStartup({
+ resolveConfig: () => ({
+ connectionString: "postgresql://kaneo:password@postgres:5432/kaneo",
+ source: "POSTGRES_ENV",
+ host: "postgres",
+ port: 5432,
+ database: "kaneo",
+ username: "kaneo",
+ logConfig: {
+ source: "POSTGRES_ENV",
+ host: "postgres",
+ port: 5432,
+ database: "kaneo",
+ username: "kaneo",
+ },
+ }),
+ waitForDatabase: async () => {
+ throw waitError;
+ },
+ runStartupMigrations,
+ logError,
+ }),
+ ).rejects.toThrow(
+ "Database startup failed for postgres:5432/kaneo (source: POSTGRES_ENV). If you are running outside Docker Compose, use localhost or set DATABASE_URL explicitly.",
+ );
+
+ expect(runStartupMigrations).not.toHaveBeenCalled();
+ expect(logError).toHaveBeenCalledWith(
+ "❌ Database readiness check failed",
+ expect.objectContaining({
+ source: "POSTGRES_ENV",
+ host: "postgres",
+ port: 5432,
+ database: "kaneo",
+ username: "kaneo",
+ }),
+ waitError,
+ );
+ });
+
+ it("logs migration failures separately from readiness failures", async () => {
+ const migrationError = new Error("permission denied for schema public");
+ const logError = vi.fn();
+
+ await expect(
+ prepareDatabaseStartup({
+ resolveConfig: () => ({
+ connectionString: "postgresql://kaneo:password@postgres:5432/kaneo",
+ source: "POSTGRES_ENV",
+ host: "postgres",
+ port: 5432,
+ database: "kaneo",
+ username: "kaneo",
+ logConfig: {
+ source: "POSTGRES_ENV",
+ host: "postgres",
+ port: 5432,
+ database: "kaneo",
+ username: "kaneo",
+ },
+ }),
+ waitForDatabase: async () => undefined,
+ runStartupMigrations: async () => {
+ throw migrationError;
+ },
+ logError,
+ }),
+ ).rejects.toThrow(
+ "Database migrations failed for postgres:5432/kaneo (source: POSTGRES_ENV).",
+ );
+
+ expect(logError).toHaveBeenCalledWith(
+ "❌ Database migrations failed",
+ expect.objectContaining({
+ source: "POSTGRES_ENV",
+ host: "postgres",
+ port: 5432,
+ database: "kaneo",
+ username: "kaneo",
+ }),
+ migrationError,
+ );
+ });
+
+ it("logs config resolution failures through the startup wrapper", async () => {
+ const configError = new Error(
+ "POSTGRES_PASSWORD must be set when deriving DATABASE_URL from POSTGRES_* variables",
+ );
+ const logError = vi.fn();
+
+ await expect(
+ prepareDatabaseStartup({
+ resolveConfig: () => {
+ throw configError;
+ },
+ waitForDatabase: async () => undefined,
+ runStartupMigrations: async () => undefined,
+ logError,
+ }),
+ ).rejects.toThrow("Database configuration failed during startup.");
+
+ expect(logError).toHaveBeenCalledWith(
+ "❌ Database configuration failed",
+ configError,
+ );
+ });
+});
diff --git a/tests/api/database/resolve-database-url.test.ts b/tests/api/database/resolve-database-url.test.ts
new file mode 100644
index 000000000..1c00c2b21
--- /dev/null
+++ b/tests/api/database/resolve-database-url.test.ts
@@ -0,0 +1,116 @@
+import { afterEach, beforeEach, describe, expect, it } from "vitest";
+import {
+ resolveDatabaseConfig,
+ resolveDatabaseConnectionString,
+} from "../../../apps/api/src/database/resolve-database-url";
+
+const keys = [
+ "DATABASE_URL",
+ "POSTGRES_HOST",
+ "POSTGRES_PORT",
+ "POSTGRES_DB",
+ "POSTGRES_USER",
+ "POSTGRES_PASSWORD",
+] as const;
+
+describe("resolve-database-url", () => {
+ const original: Partial<Record<(typeof keys)[number], string | undefined>> =
+ {};
+
+ beforeEach(() => {
+ for (const key of keys) {
+ original[key] = process.env[key];
+ delete process.env[key];
+ }
+ });
+
+ afterEach(() => {
+ for (const key of keys) {
+ const value = original[key];
+ if (value === undefined) {
+ delete process.env[key];
+ } else {
+ process.env[key] = value;
+ }
+ }
+ });
+
+ it("returns DATABASE_URL unchanged when explicitly configured", () => {
+ process.env.DATABASE_URL = "postgresql://app:[email protected]:5433/appdb";
+
+ expect(resolveDatabaseConnectionString()).toBe(
+ "postgresql://app:[email protected]:5433/appdb",
+ );
+
+ expect(resolveDatabaseConfig()).toMatchObject({
+ connectionString: "postgresql://app:[email protected]:5433/appdb",
+ source: "DATABASE_URL",
+ host: "example.com",
+ port: 5433,
+ database: "appdb",
+ username: "app",
+ });
+ });
+
+ it("derives DATABASE_URL from POSTGRES_* when a derivation signal is present", () => {
+ process.env.POSTGRES_PASSWORD = "password";
+ process.env.POSTGRES_HOST = "db.internal";
+ process.env.POSTGRES_PORT = "6543";
+ process.env.POSTGRES_DB = "kaneo_dev";
+ process.env.POSTGRES_USER = "kaneo";
+
+ expect(resolveDatabaseConfig()).toMatchObject({
+ connectionString:
+ "postgresql://kaneo:[email protected]:6543/kaneo_dev",
+ source: "POSTGRES_ENV",
+ host: "db.internal",
+ port: 6543,
+ database: "kaneo_dev",
+ username: "kaneo",
+ });
+ });
+
+ it("uses bundled-image defaults when deriving from POSTGRES_PASSWORD alone", () => {
+ process.env.POSTGRES_PASSWORD = "password";
+
+ expect(resolveDatabaseConfig()).toMatchObject({
+ connectionString: "postgresql://kaneo:password@postgres:5432/kaneo",
+ source: "POSTGRES_ENV",
+ host: "postgres",
+ port: 5432,
+ database: "kaneo",
+ username: "kaneo",
+ });
+ });
+
+ it("preserves the localhost fallback when only POSTGRES_DB and POSTGRES_USER are set", () => {
+ process.env.POSTGRES_DB = "kaneo";
+ process.env.POSTGRES_USER = "kaneo";
+
+ expect(resolveDatabaseConfig()).toMatchObject({
+ connectionString: "postgresql://localhost:5432/kaneo",
+ source: "LOCAL_FALLBACK",
+ host: "localhost",
+ port: 5432,
+ database: "kaneo",
+ username: "",
+ });
+ });
+
+ it("throws when derivation is attempted without POSTGRES_PASSWORD", () => {
+ process.env.POSTGRES_HOST = "db.internal";
+
+ expect(() => resolveDatabaseConfig()).toThrow(
+ "POSTGRES_PASSWORD must be set when deriving DATABASE_URL from POSTGRES_* variables",
+ );
+ });
+
+ it("exposes safe metadata without a password field", () => {
+ process.env.POSTGRES_PASSWORD = "super-secret";
+
+ const config = resolveDatabaseConfig();
+
+ expect(config.logConfig).not.toHaveProperty("password");
+ expect(JSON.stringify(config.logConfig)).not.toContain("super-secret");
+ });
+});
diff --git a/tests/api/database/wait-for-database.test.ts b/tests/api/database/wait-for-database.test.ts
new file mode 100644
index 000000000..6e38a8e16
--- /dev/null
+++ b/tests/api/database/wait-for-database.test.ts
@@ -0,0 +1,83 @@
+import { describe, expect, it, vi } from "vitest";
+import { waitForDatabase } from "../../../apps/api/src/database/wait-for-database";
+
+describe("wait-for-database", () => {
+ it("throws when maxAttempts is less than 1", async () => {
+ await expect(
+ waitForDatabase({
+ query: async () => undefined,
+ sleep: async () => undefined,
+ maxAttempts: 0,
+ }),
+ ).rejects.toThrow(RangeError);
+
+ await expect(
+ waitForDatabase({
+ query: async () => undefined,
+ sleep: async () => undefined,
+ maxAttempts: -1,
+ }),
+ ).rejects.toThrow(RangeError);
+ });
+
+ it("throws when retryDelayMs is negative", async () => {
+ await expect(
+ waitForDatabase({
+ query: async () => undefined,
+ sleep: async () => undefined,
+ maxAttempts: 1,
+ retryDelayMs: -1,
+ }),
+ ).rejects.toThrow(RangeError);
+ });
+ it("returns on the first successful query", async () => {
+ const query = vi.fn().mockResolvedValue(undefined);
+
+ await waitForDatabase({
+ query,
+ sleep: async () => undefined,
+ maxAttempts: 3,
+ });
+
+ expect(query).toHaveBeenCalledTimes(1);
+ });
+
+ it("retries transient failures until the query succeeds", async () => {
+ const query = vi
+ .fn()
+ .mockRejectedValueOnce(new Error("getaddrinfo EAI_AGAIN postgres"))
+ .mockRejectedValueOnce(new Error("getaddrinfo EAI_AGAIN postgres"))
+ .mockResolvedValue(undefined);
+ const sleep = vi.fn().mockResolvedValue(undefined);
+
+ await waitForDatabase({
+ query,
+ sleep,
+ maxAttempts: 3,
+ retryDelayMs: 25,
+ });
+
+ expect(query).toHaveBeenCalledTimes(3);
+ expect(sleep).toHaveBeenCalledTimes(2);
+ expect(sleep).toHaveBeenNthCalledWith(1, 25);
+ expect(sleep).toHaveBeenNthCalledWith(2, 25);
+ });
+
+ it("throws the last error after exhausting all retries", async () => {
+ const finalError = new Error("getaddrinfo EAI_AGAIN postgres");
+ const query = vi
+ .fn()
+ .mockRejectedValueOnce(new Error("temporary failure"))
+ .mockRejectedValueOnce(finalError);
+
+ await expect(
+ waitForDatabase({
+ query,
+ sleep: async () => undefined,
+ maxAttempts: 2,
+ }),
+ ).rejects.toThrow("getaddrinfo EAI_AGAIN postgres");
+
+ expect(query).toHaveBeenCalledTimes(2);
+ });
+});