-
Notifications
You must be signed in to change notification settings - Fork 17
Expand file tree
/
Copy pathcreateFlowWorker.ts
More file actions
217 lines (193 loc) · 7.04 KB
/
Copy pathcreateFlowWorker.ts
File metadata and controls
217 lines (193 loc) · 7.04 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
import type { AnyFlow, FlowContext } from '@pgflow/dsl';
import { ExecutionController } from '../core/ExecutionController.js';
import { StepTaskPoller, type StepTaskPollerConfig } from './StepTaskPoller.js';
import { StepTaskExecutor, type WorkerIdentity } from './StepTaskExecutor.js';
import { FlowInputProvider } from './FlowInputProvider.js';
import { PgflowSqlClient } from '@pgflow/core';
import { Queries } from '../core/Queries.js';
import type { IExecutor } from '../core/types.js';
import type { Logger, PlatformAdapter } from '../platform/types.js';
import type {
StepTaskWithMessage,
StepTaskHandlerContext,
} from '../core/context.js';
import { createContextSafeConfig } from '../core/context.js';
import { Worker } from '../core/Worker.js';
import postgres from 'postgres';
import { FlowWorkerLifecycle } from './FlowWorkerLifecycle.js';
import { BatchProcessor } from '../core/BatchProcessor.js';
import type {
FlowWorkerConfig,
ResolvedFlowWorkerConfig,
} from '../core/workerConfigTypes.js';
// Re-export type from workerConfigTypes to maintain backward compatibility
export type { FlowWorkerConfig } from '../core/workerConfigTypes.js';
// Default configuration constants
const DEFAULT_FLOW_CONFIG = {
maxConcurrent: 10,
maxPgConnections: 4,
batchSize: 10,
visibilityTimeout: 5,
maxPollSeconds: 2,
pollIntervalMs: 100,
} as const;
/**
* Normalizes flow worker configuration by applying all defaults
*/
function normalizeFlowConfig(
config: FlowWorkerConfig,
sql: postgres.Sql,
platformEnv: Record<string, string | undefined>
): ResolvedFlowWorkerConfig {
return {
...DEFAULT_FLOW_CONFIG,
...config,
sql,
env: platformEnv,
connectionString: config.connectionString,
};
}
/**
* Creates a new Worker instance for processing flow tasks using the two-phase polling approach.
* This eliminates race conditions by separating message polling from task processing.
*
* @param flow - The Flow DSL definition
* @param config - Configuration options for the worker
* @param createLogger - Function to create loggers for different modules
* @param platformAdapter - Platform adapter for creating contexts
* @returns A configured Worker instance ready to be started
*/
export function createFlowWorker<
TFlow extends AnyFlow,
TResources extends Record<string, unknown>
>(
flow: TFlow,
config: FlowWorkerConfig,
createLogger: (module: string) => Logger,
platformAdapter: PlatformAdapter<TResources>
): Worker {
const logger = createLogger('createFlowWorker');
// Use platform's shutdown signal
const abortSignal = platformAdapter.shutdownSignal;
if (!config.sql && !config.connectionString) {
throw new Error(
"Either 'sql' or 'connectionString' must be provided in FlowWorkerConfig."
);
}
const ownsSql = !config.sql;
const sql =
config.sql ||
postgres(config.connectionString as string, {
max: config.maxPgConnections ?? DEFAULT_FLOW_CONFIG.maxPgConnections,
prepare: false,
});
// Normalize config with all defaults applied ONCE
const resolvedConfig = normalizeFlowConfig(config, sql, platformAdapter.env);
// Create the pgflow adapter
const pgflowAdapter = new PgflowSqlClient<TFlow>(sql);
// Use flow slug as queue name, or fallback to 'tasks'
const queueName = flow.slug || 'tasks';
logger.debug(`Using queue name: ${queueName}`);
// Create specialized FlowWorkerLifecycle with the proxied queue and flow
const queries = new Queries(sql);
const lifecycle = new FlowWorkerLifecycle<TFlow>(
queries,
flow,
createLogger('FlowWorkerLifecycle'),
{
compilation: config.compilation,
}
);
// Create frozen worker config ONCE for reuse across all task executions
const frozenWorkerConfig = createContextSafeConfig(resolvedConfig);
// Create FlowInputProvider for lazy loading and caching flow input
const flowInputProvider = new FlowInputProvider<TFlow>(sql);
// Create StepTaskPoller with two-phase approach
const pollerConfig: StepTaskPollerConfig = {
batchSize: resolvedConfig.batchSize,
queueName: flow.slug,
visibilityTimeout: resolvedConfig.visibilityTimeout,
maxPollSeconds: resolvedConfig.maxPollSeconds,
pollIntervalMs: resolvedConfig.pollIntervalMs,
};
// TODO: Pass workerId supplier to defer access until after startup
const poller = new StepTaskPoller<TFlow>(
pgflowAdapter,
abortSignal,
pollerConfig,
() => lifecycle.workerId,
createLogger('StepTaskPoller')
);
// Create executor factory with proper typing
// Note: This factory is only called during task execution (after acknowledgeStart completes),
// so lifecycle.workerId and lifecycle.edgeFunctionName are guaranteed to be set.
const executorFactory = (
taskWithMessage: StepTaskWithMessage<TFlow>,
signal: AbortSignal
): IExecutor => {
const runId = taskWithMessage.task.run_id;
// Populate cache if flow_input was provided by SQL (root non-map steps only)
if (taskWithMessage.flowInput !== null) {
flowInputProvider.populate(runId, taskWithMessage.flowInput);
}
// Build context directly using platform resources
// flowInput is a Promise that either resolves immediately (cached) or lazy-loads
const context: FlowContext & TResources = {
// Core platform resources
env: platformAdapter.env,
shutdownSignal: platformAdapter.shutdownSignal,
// Step task execution context
rawMessage: taskWithMessage.message,
stepTask: taskWithMessage.task,
workerConfig: frozenWorkerConfig, // Reuse cached frozen config
flowInput: flowInputProvider.get(runId), // Lazy-loaded flow input
// Platform-specific resources (generic)
...platformAdapter.platformResources,
};
// Build worker identity for structured logging
// Safe to access here because factory is only called after acknowledgeStart()
const workerIdentity: WorkerIdentity = {
workerId: lifecycle.workerId,
workerName: lifecycle.edgeFunctionName ?? 'unknown',
queueName: queueName,
};
// Type assertion: FlowContext & TResources is compatible with StepTaskHandlerContext<TFlow>
// at runtime, but TypeScript needs help due to generic type variance
return new StepTaskExecutor<TFlow>(
flow,
pgflowAdapter,
signal,
createLogger('StepTaskExecutor'),
context as StepTaskHandlerContext<TFlow>,
workerIdentity
);
};
// Create ExecutionController
const executionController = new ExecutionController<
StepTaskWithMessage<TFlow>
>(
executorFactory,
abortSignal,
{
maxConcurrent: resolvedConfig.maxConcurrent,
},
createLogger('ExecutionController')
);
// Create BatchProcessor
const batchProcessor = new BatchProcessor<StepTaskWithMessage<TFlow>>(
executionController,
poller,
abortSignal,
createLogger('BatchProcessor')
);
// Return Worker
return new Worker(
batchProcessor,
lifecycle,
createLogger('Worker'),
{
requestShutdown: platformAdapter.requestShutdown?.bind(platformAdapter),
cleanup: ownsSql ? () => sql.end() : undefined,
}
);
}