Skip to content

OpenPanel is an open-source web and product analytics platform, an open-source alternative to Mixpanel with optional self-hosting.

self-hosting: openpanel init replaces the quiz

Carl-Gerhard Lindesvärdc2fd5c8d13c3
diff --git a/self-hosting/cli/src/commands/init.ts b/self-hosting/cli/src/commands/init.ts
new file mode 100644
index 000000000..ca815a76e
--- /dev/null
+++ b/self-hosting/cli/src/commands/init.ts
@@ -0,0 +1,278 @@
+import { cpus } from 'node:os';
+import {
+ cancel,
+ log as clackLog,
+ confirm,
+ intro,
+ isCancel,
+ note,
+ outro,
+ select,
+ text,
+} from '@clack/prompts';
+import { checkHost, DOCKER_INSTALL_COMMAND, type HostCheck } from '../host';
+import {
+ defaultAnswers,
+ generateInstall,
+ generateSecrets,
+ hostOf,
+ type InitAnswers,
+} from '../init/generate';
+import { isInstallDir, writeFiles } from '../install';
+import { run } from '../run';
+import { bold } from '../ui';
+import { compose } from './compose';
+
+export interface InitFlags {
+ dir: string;
+ yes: boolean;
+ force: boolean;
+ domain?: string;
+ proxy?: string;
+ workers?: string;
+ partitions?: string;
+ postgresUrl?: string;
+ clickhouseUrl?: string;
+ redisUrl?: string;
+ resendKey?: string;
+ emailSender?: string;
+}
+
+const MIN_WORKERS = 1;
+
+const defaultWorkers = () =>
+ Math.max(Math.floor(cpus().length / 2), MIN_WORKERS);
+
+const isHttpUrl = (value: string) => /^https?:\/\/[^\s/]+/.test(value);
+
+const parsePositiveInt = (value: string | undefined, fallback: number) => {
+ const parsed = Number.parseInt(value ?? '', 10);
+ return Number.isInteger(parsed) && parsed >= MIN_WORKERS ? parsed : fallback;
+};
+
+const stripTrailingSlash = (value: string) => value.replace(/\/+$/, '');
+
+// Cancelling any prompt (Ctrl+C) ends the wizard cleanly instead of throwing.
+const answer = <T>(value: T | symbol): T => {
+ if (isCancel(value)) {
+ cancel('Cancelled. Nothing was written.');
+ process.exit(0);
+ }
+ return value as T;
+};
+
+const askUrl = async (label: string, example: string) =>
+ answer(
+ await text({
+ message: `${label} URL`,
+ placeholder: example,
+ validate: (value) => (value?.trim() ? undefined : 'Required'),
+ })
+ );
+
+const askExternal = async (
+ flags: InitFlags
+): Promise<InitAnswers['external']> => {
+ const fromFlags = {
+ postgres: flags.postgresUrl,
+ clickhouse: flags.clickhouseUrl,
+ redis: flags.redisUrl,
+ };
+ const given = Object.entries(fromFlags).filter(([, url]) => url);
+ if (given.length > 0 || flags.yes) {
+ return Object.fromEntries(given);
+ }
+ const useBundled = answer(
+ await confirm({
+ message: 'Run Postgres, ClickHouse and Redis in Docker for you?',
+ initialValue: true,
+ })
+ );
+ if (useBundled) {
+ return {};
+ }
+ return {
+ postgres: await askUrl('Postgres', 'postgresql://user:pw@host:5432/db'),
+ clickhouse: await askUrl('ClickHouse', 'http://user:pw@host:8123/db'),
+ redis: await askUrl('Redis', 'redis://user:pw@host:6379/0'),
+ };
+};
+
+const askEmail = async (flags: InitFlags, host: string) => {
+ if (flags.resendKey || flags.yes) {
+ return { resendApiKey: flags.resendKey, emailSender: flags.emailSender };
+ }
+ const resendApiKey = answer(
+ await text({
+ message: 'Resend API key for sending email (optional, Enter to skip)',
+ })
+ );
+ if (!resendApiKey) {
+ return {};
+ }
+ const emailSender = answer(
+ await text({
+ message: 'Send email from',
+ initialValue: `no-reply@${host}`,
+ validate: (value) =>
+ value?.includes('@') ? undefined : 'Enter an email',
+ })
+ );
+ return { resendApiKey, emailSender };
+};
+
+const askAnswers = async (flags: InitFlags): Promise<InitAnswers> => {
+ const domain = stripTrailingSlash(
+ flags.domain ??
+ answer(
+ await text({
+ message: 'Where will OpenPanel live?',
+ placeholder: 'https://analytics.example.com',
+ validate: (value) =>
+ value && isHttpUrl(value)
+ ? undefined
+ : 'Start with http:// or https://',
+ })
+ )
+ );
+ if (!isHttpUrl(domain)) {
+ throw new Error(
+ `--domain must start with http:// or https:// (got "${domain}")`
+ );
+ }
+
+ const external = await askExternal(flags);
+ const proxy =
+ flags.proxy ??
+ (flags.yes
+ ? 'caddy'
+ : answer(
+ await select({
+ message: 'HTTPS and routing',
+ options: [
+ {
+ value: 'caddy',
+ label: 'Caddy, with automatic HTTPS',
+ hint: 'recommended',
+ },
+ { value: 'external', label: 'I run my own reverse proxy' },
+ ],
+ })
+ ));
+ if (proxy !== 'caddy' && proxy !== 'external') {
+ throw new Error(`--proxy must be "caddy" or "external" (got "${proxy}")`);
+ }
+
+ return {
+ ...defaultAnswers(domain),
+ external,
+ proxy,
+ workers: parsePositiveInt(flags.workers, defaultWorkers()),
+ partitions: parsePositiveInt(
+ flags.partitions,
+ defaultAnswers(domain).partitions
+ ),
+ ...(await askEmail(flags, hostOf(domain))),
+ };
+};
+
+const reportHostProblems = (results: HostCheck[]) => {
+ for (const result of results.filter((check) => !check.ok)) {
+ clackLog.error(result.title);
+ if (result.hint) {
+ clackLog.message(result.hint);
+ }
+ }
+};
+
+// Linux only, and only after showing the exact command: installing Docker is
+// the user's call, not ours.
+const offerDockerInstall = async (flags: InitFlags): Promise<boolean> => {
+ const canOffer = process.platform === 'linux' && !flags.yes;
+ if (!canOffer) {
+ return false;
+ }
+ const command = DOCKER_INSTALL_COMMAND.at(-1) as string;
+ const approved = answer(
+ await confirm({
+ message: `Install Docker now? This runs: ${command}`,
+ initialValue: true,
+ })
+ );
+ if (!approved) {
+ return false;
+ }
+ return (await run(DOCKER_INSTALL_COMMAND, { inherit: true })).code === 0;
+};
+
+const ensureDocker = async (flags: InitFlags): Promise<boolean> => {
+ let results = await checkHost();
+ const dockerMissing = results.some(
+ (check) => check.id === 'host/docker' && !check.ok
+ );
+ if (dockerMissing && (await offerDockerInstall(flags))) {
+ results = await checkHost();
+ }
+ // Low RAM is a warning, not a blocker; everything else has to work.
+ const blockers = results.filter(
+ (check) => !check.ok && check.id !== 'host/memory'
+ );
+ reportHostProblems(results);
+ return blockers.length === 0;
+};
+
+// Only Caddy publishes worker.<domain>; with your own proxy there is no URL to print.
+const queueDashboardLines = (answers: InitAnswers, adminPassword: string) =>
+ answers.proxy === 'caddy'
+ ? [
+ '',
+ `Queue dashboard: https://worker.${hostOf(answers.domain)}/bullboard/`,
+ ' user: admin',
+ ` password: ${adminPassword} (also ADMIN_PASSWORD in .env)`,
+ ]
+ : [];
+
+export const init = async (flags: InitFlags): Promise<number> => {
+ intro(bold('OpenPanel setup'));
+
+ if (isInstallDir(flags.dir) && !flags.force) {
+ clackLog.error(`${flags.dir} already has an install.`);
+ clackLog.message(
+ 'Run `openpanel doctor` to check it, or `openpanel upgrade` to update it.\nUse --force to overwrite (originals are kept as .bak).'
+ );
+ return 1;
+ }
+ if (!(await ensureDocker(flags))) {
+ return 1;
+ }
+
+ const answers = await askAnswers(flags);
+ const secrets = generateSecrets();
+ const written = await writeFiles(
+ flags.dir,
+ await generateInstall(answers, secrets)
+ );
+
+ note(
+ [
+ `Files: ${written.length} written to ${flags.dir}`,
+ `Dashboard: ${answers.domain}`,
+ `Workers: ${answers.workers}`,
+ ...queueDashboardLines(answers, secrets.adminPassword),
+ ].join('\n'),
+ 'Installed'
+ );
+
+ const start =
+ !flags.yes &&
+ answer(
+ await confirm({ message: 'Start OpenPanel now?', initialValue: true })
+ );
+ if (start) {
+ return compose('up', flags.dir);
+ }
+ outro(
+ `Start it with: openpanel up${flags.dir === process.cwd() ? '' : ` --dir ${flags.dir}`}`
+ );
+ return 0;
+};
diff --git a/self-hosting/cli/src/init/generate.ts b/self-hosting/cli/src/init/generate.ts
new file mode 100644
index 000000000..8ec2b3c84
--- /dev/null
+++ b/self-hosting/cli/src/init/generate.ts
@@ -0,0 +1,175 @@
+import { password } from 'bun';
+import { randomBytes } from 'node:crypto';
+import { parseDocument } from 'yaml';
+import {
+ DEFAULT_EVENTS_TOPIC_PARTITIONS,
+ renderRedpandaBootstrap,
+ templates,
+} from '../templates';
+
+const BCRYPT_COST = 10;
+const SECRET_BYTES = { cookie: 16, encryption: 32, admin: 12 } as const;
+
+export const BUNDLED_URLS = {
+ clickhouse: 'http://op-ch:8123/openpanel',
+ redis: 'redis://op-kv:6379',
+ postgres: 'postgresql://postgres:postgres@op-db:5432/postgres?schema=public',
+} as const;
+
+type DataService = keyof typeof BUNDLED_URLS;
+
+// The compose service (and its volume prefix) behind each data service.
+const COMPOSE_SERVICE: Record<DataService, string> = {
+ clickhouse: 'op-ch',
+ redis: 'op-kv',
+ postgres: 'op-db',
+};
+
+export interface InitAnswers {
+ // https://analytics.example.com, no trailing slash
+ domain: string;
+ // A URL means "use mine"; absent means install the bundled one.
+ external: Partial<Record<DataService, string>>;
+ proxy: 'caddy' | 'external';
+ workers: number;
+ partitions: number;
+ resendApiKey?: string;
+ emailSender?: string;
+}
+
+export interface Secrets {
+ cookieSecret: string;
+ encryptionKey: string;
+ adminPassword: string;
+}
+
+export const generateSecrets = (): Secrets => ({
+ cookieSecret: randomBytes(SECRET_BYTES.cookie).toString('hex'),
+ encryptionKey: randomBytes(SECRET_BYTES.encryption).toString('hex'),
+ adminPassword: randomBytes(SECRET_BYTES.admin).toString('hex'),
+});
+
+export const hostOf = (domain: string): string =>
+ domain.replace(/^https?:\/\//, '');
+
+// Values can contain `$` (bcrypt hashes do), so never pass them as the
+// replacement string, where `$&` and friends are special.
+const fill = (text: string, values: Record<string, string>): string =>
+ Object.entries(values).reduce(
+ (result, [name, value]) => result.replaceAll(`$${name}`, () => value),
+ text
+ );
+
+const renderEnv = (answers: InitAnswers, secrets: Secrets): string => {
+ const urlFor = (service: DataService) =>
+ answers.external[service] ?? BUNDLED_URLS[service];
+ const filled = fill(templates.env, {
+ // Longest names first: `$DATABASE_URL_DIRECT` must not be eaten by `$DATABASE_URL`.
+ DATABASE_URL_DIRECT: urlFor('postgres'),
+ DATABASE_URL: urlFor('postgres'),
+ CLICKHOUSE_URL: urlFor('clickhouse'),
+ REDIS_URL: urlFor('redis'),
+ DASHBOARD_URL: answers.domain,
+ API_URL: `${answers.domain}/api`,
+ COOKIE_SECRET: secrets.cookieSecret,
+ ADMIN_USERNAME: 'admin',
+ ADMIN_PASSWORD: secrets.adminPassword,
+ ENCRYPTION_KEY: secrets.encryptionKey,
+ RESEND_API_KEY: answers.resendApiKey ?? '',
+ EMAIL_SENDER: answers.emailSender ?? '',
+ KAFKA_EVENTS_TOPIC_PARTITIONS: String(answers.partitions),
+ });
+ // An empty value means "unset"; drop the line instead of writing KEY="".
+ return filled
+ .split('\n')
+ .filter((line) => !line.includes('=""'))
+ .join('\n');
+};
+
+const removeService = (
+ compose: ReturnType<typeof parseDocument>,
+ name: string
+) => {
+ compose.deleteIn(['services', name]);
+ const services = compose.getIn(['services'], true) as {
+ items: { key: { value: string } }[];
+ };
+ for (const { key } of services.items) {
+ const dependsOn = ['services', key.value, 'depends_on'];
+ if (compose.hasIn(dependsOn)) {
+ compose.deleteIn([...dependsOn, name]);
+ }
+ }
+ const volumes = compose.getIn(['volumes'], true) as
+ | { items: { key: { value: string } }[] }
+ | undefined;
+ for (const { key } of volumes?.items ?? []) {
+ if (key.value.startsWith(name)) {
+ compose.deleteIn(['volumes', key.value]);
+ }
+ }
+};
+
+const renderCompose = (answers: InitAnswers): string => {
+ const compose = parseDocument(templates.compose);
+ for (const service of Object.keys(answers.external) as DataService[]) {
+ removeService(compose, COMPOSE_SERVICE[service]);
+ }
+ if (answers.proxy === 'external') {
+ removeService(compose, 'op-proxy');
+ }
+ // Interpolated by compose from .env, so scaling is one edit and `up -d`.
+ compose.setIn(
+ ['services', 'op-worker', 'deploy', 'replicas'],
+ `\${OP_WORKER_REPLICAS:-${answers.workers}}`
+ );
+ return compose.toString({ flowCollectionPadding: false, lineWidth: 0 });
+};
+
+const renderCaddyfile = async (
+ answers: InitAnswers,
+ secrets: Secrets
+): Promise<string> => {
+ const hash = await password.hash(secrets.adminPassword, {
+ algorithm: 'bcrypt',
+ cost: BCRYPT_COST,
+ });
+ const host = hostOf(answers.domain);
+ return fill(templates.caddy, {
+ DOMAIN_NAME: host,
+ BASIC_AUTH_PASSWORD: hash,
+ SSL_CONFIG: host.includes('localhost:443') ? '\n\ttls internal' : '',
+ });
+};
+
+// Everything `init` writes, keyed by path relative to the install dir.
+export const generateInstall = async (
+ answers: InitAnswers,
+ secrets: Secrets
+): Promise<Map<string, string>> => {
+ const files = new Map<string, string>([
+ ['.env', renderEnv(answers, secrets)],
+ ['docker-compose.yml', renderCompose(answers)],
+ ['redpanda/bootstrap.yaml', renderRedpandaBootstrap(answers.partitions)],
+ ]);
+ if (!answers.external.clickhouse) {
+ files.set('clickhouse/clickhouse-config.xml', templates.clickhouseConfig);
+ files.set(
+ 'clickhouse/clickhouse-user-config.xml',
+ templates.clickhouseUserConfig
+ );
+ files.set('clickhouse/init-db.sh', templates.clickhouseInit);
+ }
+ if (answers.proxy === 'caddy') {
+ files.set('caddy/Caddyfile', await renderCaddyfile(answers, secrets));
+ }
+ return files;
+};
+
+export const defaultAnswers = (domain: string): InitAnswers => ({
+ domain,
+ external: {},
+ proxy: 'caddy',
+ workers: 1,
+ partitions: DEFAULT_EVENTS_TOPIC_PARTITIONS,
+});
diff --git a/self-hosting/cli/src/install.ts b/self-hosting/cli/src/install.ts
index 9fe5caa9a..6b0696001 100644
--- a/self-hosting/cli/src/install.ts
+++ b/self-hosting/cli/src/install.ts
@@ -1,5 +1,5 @@
import { existsSync, readFileSync } from 'node:fs';
-import { copyFile, mkdir, writeFile } from 'node:fs/promises';
+import { chmod, copyFile, mkdir, writeFile } from 'node:fs/promises';
import { dirname, join } from 'node:path';
import { parseDocument } from 'yaml';
import type { Install } from './doctor/types';
@@ -35,21 +35,14 @@ export const loadInstall = (dir: string): Install => {
};
};
+const EXECUTABLE_MODE = 0o755;
+
// Originals are kept next to the file as `<name>.bak` so a bad fix is one `mv`
// away from undone. Only files that actually change are touched.
-export const writeInstall = async (
+export const writeFiles = async (
dir: string,
- install: Install
+ outputs: Map<string, string>
): Promise<string[]> => {
- const outputs = new Map<string, string>([
- [COMPOSE_FILE, install.compose.toString(YAML_OUTPUT)],
- [ENV_FILE, install.env.toString()],
- ...(install.caddyfile === null
- ? []
- : ([[CADDYFILE, install.caddyfile]] as const)),
- ...install.files,
- ]);
-
const written: string[] = [];
for (const [relativePath, content] of outputs) {
const target = join(dir, relativePath);
@@ -62,7 +55,26 @@ export const writeInstall = async (
await copyFile(target, `${target}.bak`);
}
await writeFile(target, content);
+ if (relativePath.endsWith('.sh')) {
+ await chmod(target, EXECUTABLE_MODE);
+ }
written.push(relativePath);
}
return written;
};
+
+export const writeInstall = (
+ dir: string,
+ install: Install
+): Promise<string[]> =>
+ writeFiles(
+ dir,
+ new Map<string, string>([
+ [COMPOSE_FILE, install.compose.toString(YAML_OUTPUT)],
+ [ENV_FILE, install.env.toString()],
+ ...(install.caddyfile === null
+ ? []
+ : ([[CADDYFILE, install.caddyfile]] as const)),
+ ...install.files,
+ ])
+ );
diff --git a/self-hosting/cli/src/main.ts b/self-hosting/cli/src/main.ts
index 33f8f0b7d..270889cc7 100644
--- a/self-hosting/cli/src/main.ts
+++ b/self-hosting/cli/src/main.ts
@@ -3,6 +3,7 @@ import { join, resolve } from 'node:path';
import { parseArgs } from 'node:util';
import { compose, isComposeCommand } from './commands/compose';
import { doctor } from './commands/doctor';
+import { init } from './commands/init';
import { isInstallDir } from './install';
import { log } from './ui';
@@ -14,6 +15,7 @@ const HELP = `openpanel ${VERSION} — run and maintain a self-hosted OpenPanel
Usage: openpanel <command> [options]
Commands:
+ init Interactive setup (--yes --domain <url> to skip prompts)
doctor [--fix] [--check] Check the host and your install; --fix repairs it
up | down | restart Start, stop, or recreate the stack
logs [service] Follow logs
@@ -44,6 +46,17 @@ const main = async (): Promise<number> => {
options: {
dir: { type: 'string' },
fix: { type: 'boolean', default: false },
+ yes: { type: 'boolean', short: 'y', default: false },
+ force: { type: 'boolean', default: false },
+ domain: { type: 'string' },
+ proxy: { type: 'string' },
+ workers: { type: 'string' },
+ partitions: { type: 'string' },
+ 'postgres-url': { type: 'string' },
+ 'clickhouse-url': { type: 'string' },
+ 'redis-url': { type: 'string' },
+ 'resend-key': { type: 'string' },
+ 'email-sender': { type: 'string' },
check: { type: 'boolean', default: false },
help: { type: 'boolean', short: 'h', default: false },
version: { type: 'boolean', short: 'v', default: false },
@@ -61,6 +74,22 @@ const main = async (): Promise<number> => {
}
const dir = resolveDir(values.dir);
+ if (command === 'init') {
+ return init({
+ dir,
+ yes: values.yes,
+ force: values.force,
+ domain: values.domain,
+ proxy: values.proxy,
+ workers: values.workers,
+ partitions: values.partitions,
+ postgresUrl: values['postgres-url'],
+ clickhouseUrl: values['clickhouse-url'],
+ redisUrl: values['redis-url'],
+ resendKey: values['resend-key'],
+ emailSender: values['email-sender'],
+ });
+ }
if (command === 'doctor') {
return doctor({ dir, fix: values.fix, check: values.check });
}
diff --git a/self-hosting/cli/src/templates.ts b/self-hosting/cli/src/templates.ts
index 224d5d633..7e02da2be 100644
--- a/self-hosting/cli/src/templates.ts
+++ b/self-hosting/cli/src/templates.ts
@@ -2,6 +2,13 @@ import envTemplate from '../../.env.template' with { type: 'text' };
import caddyTemplate from '../../caddy/Caddyfile.template' with {
type: 'text',
};
+import clickhouseConfig from '../../clickhouse/clickhouse-config.xml' with {
+ type: 'text',
+};
+import clickhouseUserConfig from '../../clickhouse/clickhouse-user-config.xml' with {
+ type: 'text',
+};
+import clickhouseInit from '../../clickhouse/init-db.sh' with { type: 'text' };
import composeTemplate from '../../docker-compose.template.yml' with {
type: 'text',
};
@@ -9,8 +16,15 @@ import redpandaTemplate from '../../redpanda/bootstrap.template.yaml' with {
type: 'text',
};
+// `with { type: 'text' }` yields a string, but bun-types types *.xml as a DOM
+// Document, so the two XML imports are narrowed here.
+const asText = (value: unknown) => value as string;
+
export const templates = {
caddy: caddyTemplate,
+ clickhouseConfig: asText(clickhouseConfig),
+ clickhouseInit,
+ clickhouseUserConfig: asText(clickhouseUserConfig),
compose: composeTemplate,
env: envTemplate,
redpanda: redpandaTemplate,
diff --git a/self-hosting/cli/src/text-imports.d.ts b/self-hosting/cli/src/text-imports.d.ts
index ca0e0565d..216cd14e3 100644
--- a/self-hosting/cli/src/text-imports.d.ts
+++ b/self-hosting/cli/src/text-imports.d.ts
@@ -2,3 +2,8 @@ declare module '*.template' {
const text: string;
export default text;
}
+
+declare module '*.sh' {
+ const text: string;
+ export default text;
+}
diff --git a/self-hosting/cli/test/init.test.ts b/self-hosting/cli/test/init.test.ts
new file mode 100644
index 000000000..f8f47415f
--- /dev/null
+++ b/self-hosting/cli/test/init.test.ts
@@ -0,0 +1,120 @@
+import { describe, expect, test } from 'bun:test';
+import { password } from 'bun';
+import { mkdtempSync, rmSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import { parseDocument } from 'yaml';
+import { runDoctor } from '../src/doctor';
+import {
+ BUNDLED_URLS,
+ defaultAnswers,
+ generateInstall,
+ generateSecrets,
+} from '../src/init/generate';
+import { loadInstall, writeFiles } from '../src/install';
+
+const DOMAIN = 'https://analytics.example.com';
+const secrets = generateSecrets();
+
+const generate = async (
+ overrides: Partial<ReturnType<typeof defaultAnswers>> = {}
+) => generateInstall({ ...defaultAnswers(DOMAIN), ...overrides }, secrets);
+
+const composeOf = (files: Map<string, string>) =>
+ parseDocument(files.get('docker-compose.yml') as string).toJS();
+
+describe('init output', () => {
+ test('a fresh install has nothing for doctor to report', async () => {
+ const dir = mkdtempSync(join(tmpdir(), 'op-init-'));
+ try {
+ await writeFiles(dir, await generate());
+ expect(runDoctor(loadInstall(dir))).toEqual([]);
+ } finally {
+ rmSync(dir, { recursive: true, force: true });
+ }
+ });
+
+ test('bundled defaults wire every service and write the clickhouse files', async () => {
+ const files = await generate();
+ const compose = composeOf(files);
+
+ expect(Object.keys(compose.services).sort()).toEqual([
+ 'op-api',
+ 'op-ch',
+ 'op-dashboard',
+ 'op-db',
+ 'op-kv',
+ 'op-proxy',
+ 'op-rp',
+ 'op-worker',
+ ]);
+ expect(files.get('.env')).toContain(
+ `CLICKHOUSE_URL="${BUNDLED_URLS.clickhouse}"`
+ );
+ expect(files.has('clickhouse/init-db.sh')).toBe(true);
+ expect(files.has('caddy/Caddyfile')).toBe(true);
+ });
+
+ test('an external database removes its service, dependency and volume', async () => {
+ const url = 'postgresql://u:[email protected]:5432/op';
+ const files = await generate({ external: { postgres: url } });
+ const compose = composeOf(files);
+
+ expect(compose.services).not.toHaveProperty('op-db');
+ expect(compose.services['op-api'].depends_on).not.toHaveProperty('op-db');
+ expect(compose.volumes).not.toHaveProperty('op-db-data');
+ expect(files.get('.env')).toContain(`DATABASE_URL="${url}"`);
+ expect(files.get('.env')).toContain(`DATABASE_URL_DIRECT="${url}"`);
+ });
+
+ test('an external clickhouse skips its config files', async () => {
+ const files = await generate({
+ external: { clickhouse: 'http://ch.internal:8123/op' },
+ });
+ expect(files.has('clickhouse/init-db.sh')).toBe(false);
+ expect(composeOf(files).services).not.toHaveProperty('op-ch');
+ });
+
+ test('bringing your own proxy drops caddy entirely', async () => {
+ const files = await generate({ proxy: 'external' });
+ const compose = composeOf(files);
+
+ expect(compose.services).not.toHaveProperty('op-proxy');
+ expect(compose.services['op-api'].depends_on).toBeDefined();
+ expect(compose.volumes).not.toHaveProperty('op-proxy-data');
+ expect(files.has('caddy/Caddyfile')).toBe(false);
+ });
+
+ test('worker count is an overridable compose variable', async () => {
+ const compose = composeOf(await generate({ workers: 3 }));
+ expect(compose.services['op-worker'].deploy.replicas).toBe(
+ '${OP_WORKER_REPLICAS:-3}'
+ );
+ });
+
+ test('the caddy hash verifies against the admin password', async () => {
+ const caddyfile = (await generate()).get('caddy/Caddyfile') as string;
+ const hash = /admin (\$2b\$\S+)/.exec(caddyfile)?.[1] as string;
+ expect(await password.verify(secrets.adminPassword, hash)).toBe(true);
+ });
+
+ test('empty optional values are dropped, set ones written', async () => {
+ const bare = (await generate()).get('.env') as string;
+ expect(bare).not.toContain('RESEND_API_KEY');
+ expect(bare).not.toContain('=""');
+
+ const withEmail = (
+ await generate({ resendApiKey: 're_123', emailSender: '[email protected]' })
+ ).get('.env') as string;
+ expect(withEmail).toContain('RESEND_API_KEY="re_123"');
+ expect(withEmail).toContain('EMAIL_SENDER="[email protected]"');
+ });
+
+ test('the partition count reaches both .env and the redpanda bootstrap', async () => {
+ const files = await generate({ partitions: 12 });
+ expect(files.get('.env')).toContain('KAFKA_EVENTS_TOPIC_PARTITIONS="12"');
+ expect(files.get('redpanda/bootstrap.yaml')).toContain(
+ 'default_topic_partitions: 12'
+ );
+ });
+});
diff --git a/self-hosting/docker-compose.template.yml b/self-hosting/docker-compose.template.yml
index f8cf6ec20..ce2e6010d 100644
--- a/self-hosting/docker-compose.template.yml
+++ b/self-hosting/docker-compose.template.yml
@@ -1,5 +1,3 @@
-version: "3"
-
services:
op-proxy:
image: caddy:2-alpine