import { resolve } from 'node:path' import { type ChxInlinePluginRegistration, compareCodePoints, isDistributedEngine, isMergeTreeEngine, type MigrationPlan, type ResolvedChxConfig, type SchemaDefinition, } from '@chkit/core' import { loadSchemaDefinitions } from '@chkit/core/schema-loader' import { AUTH_COMMANDS, loadCredentials, resolveBaseUrl } from './auth/index.js' import { type BackfillJobFinding, checkSubmittedBackfillJobs } from './backfill/check.js' import { BACKFILL_EXTEND_COMMANDS, handleBackfillCommand, } from './backfill/index.js' import { resolveBackfillStateDir } from './backfill/plugin-options.js' import { createRemoteExecutor } from './query/remote-executor.js' import { listServices } from './service/api.js' import { SERVICE_COMMAND } from './service/commands.js' import { loadSelectedService, loadServiceAliases } from './service/storage.js' import type { SelectedService } from './service/types.js' export { type Credentials, loadCredentials, resolveBaseUrl, } from './auth/index.js' export { createJobsClient, type JobsClient } from './backfill/index.js' export { CONNECT_CHOICES, type ConnectChoice, type OnboardingOptions, runOnboarding, } from './onboarding/index.js' export { loadSelectedService, loadServiceAliases, removeServiceAlias, saveServiceAlias, } from './service/storage.js' export type { SelectedService, ServiceAliases } from './service/types.js' export type ObsessionDBPluginOptions = Record interface PluginCommand { name: string description: string flags?: ReadonlyArray<{ name: string; type: string; description: string }> run: (context: Record) => unknown } interface BeforePluginCommandContext { targetPlugin: string command: string config: Record configPath: string jsonMode: boolean args: string[] flags: Record options: Record print: (value: unknown) => void } interface BeforePluginCommandResult { handled: boolean exitCode?: number } interface GetContextInput { config: ResolvedChxConfig configPath: string command: string flags: Record defaults: Record } interface ObsessionDBPlugin { manifest: { name: 'obsessiondb'; apiVersion: 1 } commands: PluginCommand[] extendCommands: Array<{ command: string[] flags: Array<{ name: string type: 'boolean' | 'string' description: string }> }> hooks: { getContext( input: GetContextInput, ): Promise<{ executor: unknown } | undefined> onInit(context: { command: string configPath: string isInteractive: boolean jsonMode: boolean flags: Record config?: ResolvedChxConfig }): Promise onSchemaLoaded(context: { config: ResolvedChxConfig flags: Record jsonMode?: boolean definitions: SchemaDefinition[] }): SchemaDefinition[] | undefined onSnapshotLoaded(context: { config: ResolvedChxConfig flags: Record definitions: SchemaDefinition[] }): SchemaDefinition[] onPlanCreated(context: { config: ResolvedChxConfig flags: Record plan: MigrationPlan }): MigrationPlan | undefined onCheck(context: { config: ResolvedChxConfig configPath: string flags: Record }): Promise onCheckReport(context: { result: ObsessionDBCheckResult print: (line: string) => void }): void onBeforePluginCommand( context: BeforePluginCommandContext, ): Promise } } interface ObsessionDBCheckResult { plugin: 'obsessiondb' evaluated: boolean ok: boolean findings: Array< | { code: 'obsessiondb_distributed_unsupported' message: string severity: 'error' } | BackfillJobFinding > metadata?: Record } type ObsessionDBRegistration = ChxInlinePluginRegistration< ObsessionDBPlugin, ObsessionDBPluginOptions > export function isObsessionDBHost(url: string): boolean { try { const { hostname } = new URL(url) return ( hostname === 'obsessiondb.com' || hostname.endsWith('.obsessiondb.com') || hostname === 'obsession.numia-dev.com' || hostname.endsWith('.obsession.numia-dev.com') ) } catch { return false } } export function resolveStripBehavior( config: ResolvedChxConfig, flags: Record, ): boolean { // Parsed flags keep their `--` prefix (see `parseFlags`), like `--service`. if (flags['--force-shared-engines']) return false if (flags['--no-shared-engines']) return true // Auto-detect: keep ObsessionDB settings such as storage_policy when // targeting ObsessionDB const url = config.clickhouse?.url if (url && isObsessionDBHost(url)) return false return true } /** * ObsessionDB runs one shared-storage service with no shards, and its users * have no grant for the Distributed engine. Returns one message per Distributed * table so `generate` and `check` fail before ClickHouse rejects the CREATE. */ export function findDistributedTables(definitions: SchemaDefinition[]): string[] { return definitions.flatMap((def) => def.kind === 'table' && isDistributedEngine(def.engine) ? [ `Table ${def.database}.${def.name} uses the Distributed engine, which ObsessionDB does not support: ObsessionDB has no shards, so every replica already reads the same shared storage. Remove the Distributed table from the schema and query or insert into its local table directly.`, ] : [], ) } export function stripSharedPrefix(engine: string): string { return engine.replace(/^Shared/, '') } async function resolveServiceOverride(input: { configPath: string credentials: NonNullable>> name: string }): Promise { const services = await listServices(input.credentials) const service = services.find((candidate) => candidate.name === input.name) if (service) { return { service_slug: service.slug, service_name: service.name } } const aliases = await loadServiceAliases(input.configPath) const alias = aliases[input.name] if (alias) return alias const availableServices = services.map((candidate) => candidate.name).join(', ') || '' const availableAliases = Object.keys(aliases).sort(compareCodePoints).join(', ') || '' throw new Error( `obsessiondb: service "${input.name}" not found. Available services: ${availableServices}. Available aliases: ${availableAliases}`, ) } function stripCloudSettings( settings: Record | undefined, ): { settings: Record | undefined stripped: string[] } { if (!settings) return { settings, stripped: [] } const CLOUD_ONLY_SETTINGS = ['storage_policy'] const stripped: string[] = [] let result: Record | undefined for (const key of CLOUD_ONLY_SETTINGS) { if (key in settings) { if (!result) result = { ...settings } delete result[key] stripped.push(key) } } if (!result) return { settings, stripped: [] } return { settings: Object.keys(result).length > 0 ? result : undefined, stripped, } } const OBSESSIONDB_STORAGE_POLICY = "'s3'" /** * A target the plugin knows is ObsessionDB: an ObsessionDB host, not forced to * strip. `--force-shared-engines` on another host may be a self-hosted server * with its own policies, so it keeps storage_policy without these rules. */ export function isObsessionDBTarget( config: ResolvedChxConfig, flags: Record, ): boolean { const url = config.clickhouse?.url return !resolveStripBehavior(config, flags) && url !== undefined && isObsessionDBHost(url) } /** * ObsessionDB writes `storage_policy = 's3'` into every Shared table, the only * policy such a table can have, so a table that does not declare it has it, and * pull reads it back. On an ObsessionDB target the schema and the snapshot both * get it, so neither plans a change against the other and pull's file matches * the snapshot (#466). */ export function withObsessionDBStoragePolicy(definitions: SchemaDefinition[]): SchemaDefinition[] { return definitions.map((def) => { if (def.kind !== 'table' || !isMergeTreeEngine(def.engine) || def.settings?.storage_policy !== undefined) return def return { ...def, settings: { ...def.settings, storage_policy: OBSESSIONDB_STORAGE_POLICY } } }) } /** * A Shared table needs a policy on remote object storage, and ALTER accepts only * one that keeps the current policy's volumes; ObsessionDB services offer only * 's3' for Shared tables today. chkit cannot list a service's policies offline, * so on an ObsessionDB target a plan that changes it fails in generate, with * the reason, instead of at migrate. */ export function storagePolicyChangeErrors(plan: MigrationPlan): string[] { return plan.operations .filter( (op) => (op.type === 'alter_table_modify_setting' || op.type === 'alter_table_reset_setting') && op.key.endsWith(':setting:storage_policy'), ) .map((op) => { const table = op.key.replace(/^table:/, '').replace(/:setting:storage_policy$/, '') return `obsessiondb: ${table} cannot change storage_policy: a Shared table needs a policy on remote object storage that keeps the volumes of its current one, and ObsessionDB services offer only 's3' for Shared tables today. Keep storage_policy: "${OBSESSIONDB_STORAGE_POLICY}" in the schema, or leave it out.` }) } /** * Strip the `Shared` engine prefix and ObsessionDB settings such as * storage_policy. Definitions the CLI loads are canonicalized first, and core's * normalizeEngine already writes the standard engine name for every target, so * on that path only the settings strip changes anything. */ export function rewriteSharedEngines(definitions: SchemaDefinition[]): { definitions: SchemaDefinition[] count: number strippedSettings: string[] } { let count = 0 const allStrippedSettings: string[] = [] const rewritten = definitions.map((def) => { if (def.kind !== 'table') return def const hasSharedEngine = def.engine.startsWith('Shared') const { settings, stripped } = stripCloudSettings(def.settings) if (!hasSharedEngine && stripped.length === 0) return def if (hasSharedEngine) count++ allStrippedSettings.push(...stripped) return { ...def, engine: hasSharedEngine ? stripSharedPrefix(def.engine) : def.engine, settings, } }) return { definitions: rewritten, count, strippedSettings: allStrippedSettings, } } function createObsessionDBPlugin( _options: ObsessionDBPluginOptions, ): ObsessionDBPlugin { return { manifest: { name: 'obsessiondb', apiVersion: 1 }, commands: [...AUTH_COMMANDS, SERVICE_COMMAND] as unknown as PluginCommand[], extendCommands: [ { // Only `generate` and `snapshot rebuild` run the onSchemaLoaded hooks, // so only they act on these flags. migrate, status, drift and check // keep accepting them, so existing scripts that pass them to those // commands don't break. command: ['generate', 'migrate', 'status', 'drift', 'check', 'snapshot'], flags: [ { name: '--force-shared-engines', type: 'boolean', description: 'Keep the storage_policy table setting even when the URL is not recognized as ObsessionDB (takes effect in generate and snapshot rebuild)', }, { name: '--no-shared-engines', type: 'boolean', description: 'Strip the storage_policy table setting even when targeting ObsessionDB (takes effect in generate and snapshot rebuild)', }, ], }, { command: ['generate', 'migrate', 'status', 'drift', 'check', 'query', 'pull'], flags: [ { name: '--service', type: 'string', description: 'Override the selected ObsessionDB service by name for this command', }, ], }, ...BACKFILL_EXTEND_COMMANDS, ], hooks: { async getContext({ config, configPath, command, flags }) { const creds = await loadCredentials() if (!creds) return const effectiveCreds = { ...creds, base_url: resolveBaseUrl(creds.base_url), } const serviceOverride = flags['--service'] const overrideName = typeof serviceOverride === 'string' ? serviceOverride.trim() : '' let service: SelectedService | null if (overrideName.length > 0) { service = await resolveServiceOverride({ configPath, credentials: effectiveCreds, name: overrideName, }) } else { service = await loadSelectedService(configPath) } if (!service) { if (command === 'query' && !config.clickhouse) { throw new Error( 'authenticated but no ObsessionDB service is selected. Run `chkit obsessiondb service select` or pass `--service `.', ) } return } return { executor: createRemoteExecutor({ credentials: effectiveCreds, serviceSlug: service.service_slug, }), } }, async onInit(context) { if (context.jsonMode) return if (context.command === 'obsessiondb') return const creds = await loadCredentials() if (!creds) return const effectiveCreds = { ...creds, base_url: resolveBaseUrl(creds.base_url), } const serviceOverride = context.flags['--service'] const overrideName = typeof serviceOverride === 'string' ? serviceOverride.trim() : '' let service: SelectedService | null if (overrideName.length > 0) { try { service = await resolveServiceOverride({ configPath: context.configPath, credentials: effectiveCreds, name: overrideName, }) } catch { return } } else { service = await loadSelectedService(context.configPath) } if (service) { console.log(`obsessiondb: using service "${service.service_name}"\n`) } else if (context.command === 'query' || context.config?.clickhouse) { // Suppress the "no service selected" reminder when the user has a // direct `clickhouse` target configured: ObsessionDB was layered in // from a global `chkit obsessiondb login` profile, not chosen for this // project, so service selection is irrelevant and the notice is noise. return } else { console.log( 'obsessiondb: authenticated but no service selected (run `chkit obsessiondb service select` or pass `--service `)', ) } }, onSchemaLoaded(context) { const shouldStrip = resolveStripBehavior(context.config, context.flags) if (!shouldStrip) { const distributed = findDistributedTables(context.definitions) if (distributed.length > 0) throw new Error(distributed.join('\n')) return isObsessionDBTarget(context.config, context.flags) ? withObsessionDBStoragePolicy(context.definitions) : undefined } const rewritten = rewriteSharedEngines(context.definitions) if (!context.jsonMode && rewritten.count > 0) { console.log( `obsessiondb: Rewrote ${rewritten.count} Shared engine(s) to standard ClickHouse equivalents.`, ) } if (!context.jsonMode && rewritten.strippedSettings.length > 0) { const unique = [...new Set(rewritten.strippedSettings)] console.log( `obsessiondb: Stripped cloud-only setting(s): ${unique.join(', ')}`, ) } return rewritten.definitions }, // The same settings rewrite as onSchemaLoaded, without its notices and // checks: they are about the schema, not about the last snapshot. onSnapshotLoaded(context) { if (resolveStripBehavior(context.config, context.flags)) { return rewriteSharedEngines(context.definitions).definitions } return isObsessionDBTarget(context.config, context.flags) ? withObsessionDBStoragePolicy(context.definitions) : context.definitions }, onPlanCreated(context) { if (!isObsessionDBTarget(context.config, context.flags)) return undefined const errors = storagePolicyChangeErrors(context.plan) if (errors.length > 0) throw new Error(errors.join('\n')) return undefined }, async onCheck({ config, configPath, flags }) { // Same target decision as onSchemaLoaded: ObsessionDB host or // --force-shared-engines. const distributedFindings = resolveStripBehavior(config, flags) ? undefined : findDistributedTables( await loadSchemaDefinitions(config.schema, { cwd: resolve(configPath, '..') }), ).map((message) => ({ code: 'obsessiondb_distributed_unsupported' as const, message, severity: 'error' as const, })) // Submitted backfill jobs run on ObsessionDB whatever the check target is. const backfillJobs = await checkSubmittedBackfillJobs({ config, configPath, stateDir: resolveBackfillStateDir(config.plugins), }) if (!distributedFindings && !backfillJobs) return undefined const findings = [...(distributedFindings ?? []), ...(backfillJobs?.findings ?? [])] return { plugin: 'obsessiondb', evaluated: true, ok: findings.length === 0, findings, ...(backfillJobs ? { metadata: { backfillJobs: backfillJobs.counts } } : {}), } }, onCheckReport({ result, print }) { if (result.ok) return for (const finding of result.findings) print(`obsessiondb: ${finding.message}`) }, async onBeforePluginCommand(context) { return handleBackfillCommand(context) }, }, } } export function obsessiondb( options: ObsessionDBPluginOptions = {}, ): ObsessionDBRegistration { return { plugin: createObsessionDBPlugin(options), name: 'obsessiondb', enabled: true, options, } }