|
| 1 | +import type postgres from 'postgres'; |
| 2 | +import type { SupabaseClient } from '@supabase/supabase-js'; |
| 3 | +import type { SupabaseResources } from '@pgflow/dsl/supabase'; |
| 4 | +import type { CreateWorkerFn, Logger, PlatformAdapter } from './types.js'; |
| 5 | +import type { Worker } from '../core/Worker.js'; |
| 6 | +import { createServiceSupabaseClient } from '../core/supabase-utils.js'; |
| 7 | +import { Queries } from '../core/Queries.js'; |
| 8 | +import { isLocalSupabaseEnv } from '../shared/localDetection.js'; |
| 9 | +import { createLoggingFactory } from './logging.js'; |
| 10 | +import { resolveConnectionString, resolveSqlConnection } from './resolveConnection.js'; |
| 11 | +import { getProcessDeps, type ProcessDeps, type ProcessSignal } from './processDeps.js'; |
| 12 | + |
| 13 | +interface ProcessEnv extends Record<string, string | undefined> { |
| 14 | + SUPABASE_URL: string; |
| 15 | + SUPABASE_SERVICE_ROLE_KEY: string; |
| 16 | + WORKER_NAME?: string; |
| 17 | + DATABASE_URL?: string; |
| 18 | + EDGE_WORKER_DB_URL?: string; |
| 19 | + EDGE_WORKER_LOG_LEVEL?: string; |
| 20 | +} |
| 21 | + |
| 22 | +type ProcessAdapterOptions = { |
| 23 | + sql?: postgres.Sql; |
| 24 | + connectionString?: string; |
| 25 | + maxPgConnections?: number; |
| 26 | +}; |
| 27 | + |
| 28 | +export class ProcessPlatformAdapter implements PlatformAdapter<SupabaseResources> { |
| 29 | + private readonly deps: ProcessDeps; |
| 30 | + private readonly logger: Logger; |
| 31 | + private readonly loggingFactory: ReturnType<typeof createLoggingFactory>; |
| 32 | + private readonly abortController = new AbortController(); |
| 33 | + private readonly validatedEnv: ProcessEnv; |
| 34 | + private readonly _connectionString: string | undefined; |
| 35 | + private readonly _platformResources: SupabaseResources; |
| 36 | + private readonly ownsSql: boolean; |
| 37 | + private readonly queries: Queries; |
| 38 | + private worker: Worker | null = null; |
| 39 | + private workerId: string | null = null; |
| 40 | + private shutdownStarted = false; |
| 41 | + |
| 42 | + constructor( |
| 43 | + options?: ProcessAdapterOptions, |
| 44 | + deps: ProcessDeps = getProcessDeps() |
| 45 | + ) { |
| 46 | + this.deps = deps; |
| 47 | + this.assertProcessEnv(deps.env); |
| 48 | + this.validatedEnv = deps.env; |
| 49 | + this._connectionString = resolveConnectionString(this.validatedEnv, { |
| 50 | + hasSql: !!options?.sql, |
| 51 | + connectionString: options?.connectionString, |
| 52 | + }); |
| 53 | + this.ownsSql = !options?.sql; |
| 54 | + this.loggingFactory = createLoggingFactory(this.validatedEnv); |
| 55 | + this.logger = this.loggingFactory.createLogger('ProcessPlatformAdapter'); |
| 56 | + this._platformResources = { |
| 57 | + sql: resolveSqlConnection(this.validatedEnv, options), |
| 58 | + supabase: createServiceSupabaseClient(this.validatedEnv), |
| 59 | + }; |
| 60 | + this.queries = new Queries(this._platformResources.sql); |
| 61 | + } |
| 62 | + |
| 63 | + async startWorker(createWorkerFn: CreateWorkerFn): Promise<void> { |
| 64 | + const workerName = this.validatedEnv.WORKER_NAME || 'pgflow-worker'; |
| 65 | + const workerId = this.deps.randomUUID(); |
| 66 | + |
| 67 | + this.workerId = workerId; |
| 68 | + this.loggingFactory.setWorkerId(workerId); |
| 69 | + this.loggingFactory.setWorkerName(workerName); |
| 70 | + this.registerSignalHandlers(); |
| 71 | + |
| 72 | + this.worker = createWorkerFn(this.loggingFactory.createLogger); |
| 73 | + await this.worker.startOnlyOnce({ |
| 74 | + edgeFunctionName: workerName, |
| 75 | + workerId, |
| 76 | + startMode: 'process', |
| 77 | + }); |
| 78 | + } |
| 79 | + |
| 80 | + async stopWorker(): Promise<void> { |
| 81 | + this.requestShutdown(); |
| 82 | + |
| 83 | + try { |
| 84 | + if (this.worker) { |
| 85 | + await this.worker.stop(); |
| 86 | + } |
| 87 | + if (this.workerId) { |
| 88 | + await this.queries.markWorkerStopped(this.workerId); |
| 89 | + } |
| 90 | + } finally { |
| 91 | + if (this.ownsSql) { |
| 92 | + await this._platformResources.sql.end(); |
| 93 | + } |
| 94 | + } |
| 95 | + } |
| 96 | + |
| 97 | + requestShutdown(): void { |
| 98 | + this.abortController.abort(); |
| 99 | + } |
| 100 | + |
| 101 | + createLogger(module: string): Logger { |
| 102 | + return this.loggingFactory.createLogger(module); |
| 103 | + } |
| 104 | + |
| 105 | + get connectionString(): string | undefined { |
| 106 | + return this._connectionString; |
| 107 | + } |
| 108 | + |
| 109 | + get env(): Record<string, string | undefined> { |
| 110 | + return this.validatedEnv; |
| 111 | + } |
| 112 | + |
| 113 | + get shutdownSignal(): AbortSignal { |
| 114 | + return this.abortController.signal; |
| 115 | + } |
| 116 | + |
| 117 | + get platformResources(): SupabaseResources { |
| 118 | + return this._platformResources; |
| 119 | + } |
| 120 | + |
| 121 | + get isLocalEnvironment(): boolean { |
| 122 | + return isLocalSupabaseEnv(this.validatedEnv); |
| 123 | + } |
| 124 | + |
| 125 | + get sql(): postgres.Sql { |
| 126 | + return this._platformResources.sql; |
| 127 | + } |
| 128 | + |
| 129 | + get supabase(): SupabaseClient { |
| 130 | + return this._platformResources.supabase; |
| 131 | + } |
| 132 | + |
| 133 | + private registerSignalHandlers(): void { |
| 134 | + for (const signal of ['SIGTERM', 'SIGINT', 'SIGQUIT'] satisfies ProcessSignal[]) { |
| 135 | + this.deps.onSignal(signal, () => this.handleSignal()); |
| 136 | + } |
| 137 | + } |
| 138 | + |
| 139 | + private async handleSignal(): Promise<void> { |
| 140 | + if (this.shutdownStarted) { |
| 141 | + this.deps.exit(1); |
| 142 | + } |
| 143 | + |
| 144 | + this.shutdownStarted = true; |
| 145 | + |
| 146 | + try { |
| 147 | + await this.stopWorker(); |
| 148 | + } catch (error) { |
| 149 | + this.logger.error('Process worker shutdown failed', error); |
| 150 | + this.deps.setExitCode(1); |
| 151 | + this.deps.exit(1); |
| 152 | + } |
| 153 | + |
| 154 | + this.deps.setExitCode(0); |
| 155 | + this.deps.exit(0); |
| 156 | + } |
| 157 | + |
| 158 | + private assertProcessEnv(env: Record<string, string | undefined>): asserts env is ProcessEnv { |
| 159 | + const required = ['SUPABASE_URL', 'SUPABASE_SERVICE_ROLE_KEY']; |
| 160 | + const missing = required.filter((key) => !env[key]); |
| 161 | + |
| 162 | + if (missing.length > 0) { |
| 163 | + throw new Error(`Missing required environment variables: ${missing.join(', ')}`); |
| 164 | + } |
| 165 | + } |
| 166 | +} |
0 commit comments