-
Notifications
You must be signed in to change notification settings - Fork 18
feat: add ProcessPlatformAdapter for Node.js process environments
#627
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
jumski
wants to merge
1
commit into
portable-worker-start
Choose a base branch
from
portable-worker-process-adapter
base: portable-worker-start
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
+426
−13
Open
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
166 changes: 166 additions & 0 deletions
166
pkgs/edge-worker/src/platform/ProcessPlatformAdapter.ts
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,166 @@ | ||
| import type postgres from 'postgres'; | ||
| import type { SupabaseClient } from '@supabase/supabase-js'; | ||
| import type { SupabaseResources } from '@pgflow/dsl/supabase'; | ||
| import type { CreateWorkerFn, Logger, PlatformAdapter } from './types.js'; | ||
| import type { Worker } from '../core/Worker.js'; | ||
| import { createServiceSupabaseClient } from '../core/supabase-utils.js'; | ||
| import { Queries } from '../core/Queries.js'; | ||
| import { isLocalSupabaseEnv } from '../shared/localDetection.js'; | ||
| import { createLoggingFactory } from './logging.js'; | ||
| import { resolveConnectionString, resolveSqlConnection } from './resolveConnection.js'; | ||
| import { getProcessDeps, type ProcessDeps, type ProcessSignal } from './processDeps.js'; | ||
|
|
||
| interface ProcessEnv extends Record<string, string | undefined> { | ||
| SUPABASE_URL: string; | ||
| SUPABASE_SERVICE_ROLE_KEY: string; | ||
| WORKER_NAME?: string; | ||
| DATABASE_URL?: string; | ||
| EDGE_WORKER_DB_URL?: string; | ||
| EDGE_WORKER_LOG_LEVEL?: string; | ||
| } | ||
|
|
||
| type ProcessAdapterOptions = { | ||
| sql?: postgres.Sql; | ||
| connectionString?: string; | ||
| maxPgConnections?: number; | ||
| }; | ||
|
|
||
| export class ProcessPlatformAdapter implements PlatformAdapter<SupabaseResources> { | ||
| private readonly deps: ProcessDeps; | ||
| private readonly logger: Logger; | ||
| private readonly loggingFactory: ReturnType<typeof createLoggingFactory>; | ||
| private readonly abortController = new AbortController(); | ||
| private readonly validatedEnv: ProcessEnv; | ||
| private readonly _connectionString: string | undefined; | ||
| private readonly _platformResources: SupabaseResources; | ||
| private readonly ownsSql: boolean; | ||
| private readonly queries: Queries; | ||
| private worker: Worker | null = null; | ||
| private workerId: string | null = null; | ||
| private shutdownStarted = false; | ||
|
|
||
| constructor( | ||
| options?: ProcessAdapterOptions, | ||
| deps: ProcessDeps = getProcessDeps() | ||
| ) { | ||
| this.deps = deps; | ||
| this.assertProcessEnv(deps.env); | ||
| this.validatedEnv = deps.env; | ||
| this._connectionString = resolveConnectionString(this.validatedEnv, { | ||
| hasSql: !!options?.sql, | ||
| connectionString: options?.connectionString, | ||
| }); | ||
| this.ownsSql = !options?.sql; | ||
| this.loggingFactory = createLoggingFactory(this.validatedEnv); | ||
| this.logger = this.loggingFactory.createLogger('ProcessPlatformAdapter'); | ||
| this._platformResources = { | ||
| sql: resolveSqlConnection(this.validatedEnv, options), | ||
| supabase: createServiceSupabaseClient(this.validatedEnv), | ||
| }; | ||
| this.queries = new Queries(this._platformResources.sql); | ||
| } | ||
|
|
||
| async startWorker(createWorkerFn: CreateWorkerFn): Promise<void> { | ||
| const workerName = this.validatedEnv.WORKER_NAME || 'pgflow-worker'; | ||
| const workerId = this.deps.randomUUID(); | ||
|
|
||
| this.workerId = workerId; | ||
| this.loggingFactory.setWorkerId(workerId); | ||
| this.loggingFactory.setWorkerName(workerName); | ||
| this.registerSignalHandlers(); | ||
|
|
||
| this.worker = createWorkerFn(this.loggingFactory.createLogger); | ||
| await this.worker.startOnlyOnce({ | ||
| edgeFunctionName: workerName, | ||
| workerId, | ||
| startMode: 'process', | ||
| }); | ||
| } | ||
|
|
||
| async stopWorker(): Promise<void> { | ||
| this.requestShutdown(); | ||
|
|
||
| try { | ||
| if (this.worker) { | ||
| await this.worker.stop(); | ||
| } | ||
| if (this.workerId) { | ||
| await this.queries.markWorkerStopped(this.workerId); | ||
| } | ||
| } finally { | ||
| if (this.ownsSql) { | ||
| await this._platformResources.sql.end(); | ||
| } | ||
| } | ||
| } | ||
|
|
||
| requestShutdown(): void { | ||
| this.abortController.abort(); | ||
| } | ||
|
|
||
| createLogger(module: string): Logger { | ||
| return this.loggingFactory.createLogger(module); | ||
| } | ||
|
|
||
| get connectionString(): string | undefined { | ||
| return this._connectionString; | ||
| } | ||
|
|
||
| get env(): Record<string, string | undefined> { | ||
| return this.validatedEnv; | ||
| } | ||
|
|
||
| get shutdownSignal(): AbortSignal { | ||
| return this.abortController.signal; | ||
| } | ||
|
|
||
| get platformResources(): SupabaseResources { | ||
| return this._platformResources; | ||
| } | ||
|
|
||
| get isLocalEnvironment(): boolean { | ||
| return isLocalSupabaseEnv(this.validatedEnv); | ||
| } | ||
|
|
||
| get sql(): postgres.Sql { | ||
| return this._platformResources.sql; | ||
| } | ||
|
|
||
| get supabase(): SupabaseClient { | ||
| return this._platformResources.supabase; | ||
| } | ||
|
|
||
| private registerSignalHandlers(): void { | ||
| for (const signal of ['SIGTERM', 'SIGINT', 'SIGQUIT'] satisfies ProcessSignal[]) { | ||
| this.deps.onSignal(signal, () => this.handleSignal()); | ||
| } | ||
| } | ||
|
|
||
| private async handleSignal(): Promise<void> { | ||
| if (this.shutdownStarted) { | ||
| this.deps.exit(1); | ||
| } | ||
|
|
||
| this.shutdownStarted = true; | ||
|
|
||
| try { | ||
| await this.stopWorker(); | ||
| } catch (error) { | ||
| this.logger.error('Process worker shutdown failed', error); | ||
| this.deps.setExitCode(1); | ||
| this.deps.exit(1); | ||
| } | ||
|
|
||
| this.deps.setExitCode(0); | ||
| this.deps.exit(0); | ||
| } | ||
|
|
||
| private assertProcessEnv(env: Record<string, string | undefined>): asserts env is ProcessEnv { | ||
| const required = ['SUPABASE_URL', 'SUPABASE_SERVICE_ROLE_KEY']; | ||
| const missing = required.filter((key) => !env[key]); | ||
|
|
||
| if (missing.length > 0) { | ||
| throw new Error(`Missing required environment variables: ${missing.join(', ')}`); | ||
| } | ||
| } | ||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,39 @@ | ||
| export type ProcessSignal = 'SIGTERM' | 'SIGINT' | 'SIGQUIT'; | ||
|
|
||
| export type ProcessDeps = { | ||
| env: Record<string, string | undefined>; | ||
| onSignal: (signal: ProcessSignal, handler: () => void | Promise<void>) => void; | ||
| exit: (code: number) => never; | ||
| setExitCode: (code: number) => void; | ||
| randomUUID: () => string; | ||
| }; | ||
|
|
||
| type ProcessLike = { | ||
| env?: Record<string, string | undefined>; | ||
| on?: (signal: ProcessSignal, handler: () => void | Promise<void>) => void; | ||
| exit?: (code: number) => never; | ||
| exitCode?: number; | ||
| }; | ||
|
|
||
| type CryptoLike = { | ||
| randomUUID?: () => string; | ||
| }; | ||
|
|
||
| export function getProcessDeps(): ProcessDeps { | ||
| const processLike = (globalThis as { process?: ProcessLike }).process; | ||
| const cryptoLike = globalThis.crypto as CryptoLike | undefined; | ||
|
|
||
| if (!processLike?.env || !processLike.on || !processLike.exit || !cryptoLike?.randomUUID) { | ||
| throw new Error('Process runtime is not available'); | ||
| } | ||
|
|
||
| return { | ||
| env: processLike.env, | ||
| onSignal: (signal, handler) => processLike.on?.(signal, handler), | ||
| exit: (code) => processLike.exit!(code), | ||
| setExitCode: (code) => { | ||
| processLike.exitCode = code; | ||
| }, | ||
| randomUUID: () => cryptoLike.randomUUID!(), | ||
| }; | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Race condition:
stopWorker()can be called concurrentlyIf
stopWorker()is called manually and then a signal arrives before it completes,handleSignal()will callstopWorker()again sinceshutdownStartedis only set inhandleSignal(), not instopWorker(). This causes:worker.stop()called twice (may not be idempotent)markWorkerStopped()called twice (could fail or create duplicate entries)sql.end()potentially called twice (will error on second call)Fix: Add a guard in
stopWorker()or set the shutdown flag there as well:Spotted by Graphite

Is this helpful? React 👍 or 👎 to let us know.