-
Notifications
You must be signed in to change notification settings - Fork 3.5k
Expand file tree
/
Copy pathmigrate-deployment-versions.ts
More file actions
370 lines (333 loc) · 11.4 KB
/
migrate-deployment-versions.ts
File metadata and controls
370 lines (333 loc) · 11.4 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
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
#!/usr/bin/env bun
// This script is intentionally self-contained for execution in the migrations image.
// Do not import from the main app code; duplicate minimal schema and DB setup here.
import { sql } from 'drizzle-orm'
import { drizzle } from 'drizzle-orm/postgres-js'
import postgres from 'postgres'
import { v4 as uuidv4 } from 'uuid'
// ---------- Minimal env helpers ----------
function getEnv(name: string): string | undefined {
if (typeof process !== 'undefined' && process.env && name in process.env) {
return process.env[name]
}
return undefined
}
const CONNECTION_STRING = getEnv('POSTGRES_URL') ?? getEnv('DATABASE_URL')
if (!CONNECTION_STRING) {
console.error('Missing POSTGRES_URL or DATABASE_URL environment variable')
process.exit(1)
}
// ---------- Minimal schema (only what we need) ----------
import { boolean, index, integer, json, jsonb, pgTable, text, timestamp } from 'drizzle-orm/pg-core'
// Tables referenced by the script
const workflow = pgTable(
'workflow',
{
id: text('id').primaryKey(),
userId: text('user_id').notNull(),
name: text('name').notNull(),
isDeployed: boolean('is_deployed').notNull().default(false),
deployedState: json('deployed_state'),
deployedAt: timestamp('deployed_at'),
},
(table) => ({
userIdIdx: index('workflow_user_id_idx').on(table.userId),
})
)
const workflowBlocks = pgTable(
'workflow_blocks',
{
id: text('id').primaryKey(),
workflowId: text('workflow_id').notNull(),
type: text('type').notNull(),
name: text('name').notNull(),
positionX: text('position_x').notNull(),
positionY: text('position_y').notNull(),
enabled: boolean('enabled').notNull().default(true),
horizontalHandles: boolean('horizontal_handles').notNull().default(true),
isWide: boolean('is_wide').notNull().default(false),
advancedMode: boolean('advanced_mode').notNull().default(false),
triggerMode: boolean('trigger_mode').notNull().default(false),
height: text('height').notNull().default('0'),
subBlocks: jsonb('sub_blocks').notNull().default('{}'),
outputs: jsonb('outputs').notNull().default('{}'),
data: jsonb('data').default('{}'),
parentId: text('parent_id'),
extent: text('extent'),
createdAt: timestamp('created_at').notNull().defaultNow(),
updatedAt: timestamp('updated_at').notNull().defaultNow(),
},
(table) => ({
workflowIdIdx: index('workflow_blocks_workflow_id_idx').on(table.workflowId),
})
)
const workflowEdges = pgTable(
'workflow_edges',
{
id: text('id').primaryKey(),
workflowId: text('workflow_id').notNull(),
sourceBlockId: text('source_block_id').notNull(),
targetBlockId: text('target_block_id').notNull(),
sourceHandle: text('source_handle'),
targetHandle: text('target_handle'),
createdAt: timestamp('created_at').notNull().defaultNow(),
},
(table) => ({
workflowIdIdx: index('workflow_edges_workflow_id_idx').on(table.workflowId),
})
)
const workflowSubflows = pgTable(
'workflow_subflows',
{
id: text('id').primaryKey(),
workflowId: text('workflow_id').notNull(),
type: text('type').notNull(),
config: jsonb('config').notNull().default('{}'),
createdAt: timestamp('created_at').notNull().defaultNow(),
updatedAt: timestamp('updated_at').notNull().defaultNow(),
},
(table) => ({
workflowIdIdx: index('workflow_subflows_workflow_id_idx').on(table.workflowId),
})
)
const workflowDeploymentVersion = pgTable(
'workflow_deployment_version',
{
id: text('id').primaryKey(),
workflowId: text('workflow_id').notNull(),
version: integer('version').notNull(),
state: json('state').notNull(),
isActive: boolean('is_active').notNull().default(false),
createdAt: timestamp('created_at').notNull().defaultNow(),
createdBy: text('created_by'),
},
(table) => ({
workflowIdIdx: index('workflow_deployment_version_workflow_id_idx').on(table.workflowId),
})
)
// ---------- DB client ----------
const postgresClient = postgres(CONNECTION_STRING, {
prepare: false,
idle_timeout: 20,
connect_timeout: 30,
max: 10,
onnotice: () => {},
})
const db = drizzle(postgresClient)
// ---------- Minimal types ----------
type WorkflowState = {
blocks: Record<string, any>
edges: Array<{
id: string
source: string
target: string
sourceHandle?: string | null
targetHandle?: string | null
}>
loops: Record<string, any>
parallels: Record<string, any>
}
// ---------- Normalized loader (inline of loadWorkflowFromNormalizedTables) ----------
async function loadWorkflowFromNormalizedTables(workflowId: string) {
const [blocks, edges, subflows] = await Promise.all([
db.select().from(workflowBlocks).where(sql`${workflowBlocks.workflowId} = ${workflowId}`),
db.select().from(workflowEdges).where(sql`${workflowEdges.workflowId} = ${workflowId}`),
db.select().from(workflowSubflows).where(sql`${workflowSubflows.workflowId} = ${workflowId}`),
])
if (blocks.length === 0) return null
const blocksMap: Record<string, any> = {}
for (const block of blocks as any[]) {
const parentId = (block.parentId as string | null) || null
const extent = (block.extent as string | null) || null
blocksMap[block.id] = {
id: block.id,
type: block.type,
name: block.name,
position: {
x: Number(block.positionX),
y: Number(block.positionY),
},
enabled: block.enabled,
horizontalHandles: block.horizontalHandles,
isWide: block.isWide,
advancedMode: block.advancedMode,
triggerMode: block.triggerMode,
height: Number(block.height),
subBlocks: block.subBlocks || {},
outputs: block.outputs || {},
data: {
...(block.data || {}),
...(parentId && { parentId }),
...(extent && { extent }),
},
parentId,
extent,
}
}
const edgesArray = (edges as any[]).map((edge) => ({
id: edge.id,
source: edge.sourceBlockId,
target: edge.targetBlockId,
sourceHandle: edge.sourceHandle,
targetHandle: edge.targetHandle,
}))
const loops: Record<string, any> = {}
const parallels: Record<string, any> = {}
for (const sub of subflows as any[]) {
const config = sub.config || {}
if (sub.type === 'loop') {
loops[sub.id] = { id: sub.id, ...config }
} else if (sub.type === 'parallel') {
parallels[sub.id] = { id: sub.id, ...config }
}
}
return {
blocks: blocksMap,
edges: edgesArray,
loops,
parallels,
isFromNormalizedTables: true,
}
}
// ---------- Migration ----------
const DRY_RUN = process.argv.includes('--dry-run')
const BATCH_SIZE = 50
async function migrateWorkflows() {
console.log('Starting deployment version migration...')
console.log(`Mode: ${DRY_RUN ? 'DRY RUN' : 'LIVE'}`)
console.log(`Batch size: ${BATCH_SIZE}`)
console.log('---')
try {
const workflows = await db
.select({
id: workflow.id,
name: workflow.name,
isDeployed: workflow.isDeployed,
deployedState: workflow.deployedState,
deployedAt: workflow.deployedAt,
userId: workflow.userId,
})
.from(workflow)
console.log(`Found ${workflows.length} workflows to process`)
const existingVersions = await db
.select({ workflowId: workflowDeploymentVersion.workflowId })
.from(workflowDeploymentVersion)
const existingWorkflowIds = new Set(existingVersions.map((v) => v.workflowId as string))
console.log(`${existingWorkflowIds.size} workflows already have deployment versions`)
let successCount = 0
let skipCount = 0
let errorCount = 0
for (let i = 0; i < workflows.length; i += BATCH_SIZE) {
const batch = workflows.slice(i, i + BATCH_SIZE)
console.log(
`\nProcessing batch ${Math.floor(i / BATCH_SIZE) + 1} (workflows ${i + 1}-${Math.min(i + BATCH_SIZE, workflows.length)})`
)
const deploymentVersions: Array<{
id: string
workflowId: string
version: number
state: WorkflowState
createdAt: Date
createdBy: string
isActive: boolean
}> = []
for (const wf of batch as any[]) {
if (existingWorkflowIds.has(wf.id)) {
console.log(` [SKIP] ${wf.id} (${wf.name}) - already has deployment version`)
skipCount++
continue
}
let state: WorkflowState | null = null
if (wf.deployedState) {
state = wf.deployedState as WorkflowState
console.log(` [DEPLOYED] ${wf.id} (${wf.name}) - using existing deployedState`)
} else {
const normalized = await loadWorkflowFromNormalizedTables(wf.id)
if (normalized) {
state = {
blocks: normalized.blocks,
edges: normalized.edges,
loops: normalized.loops,
parallels: normalized.parallels,
}
console.log(
` [NORMALIZED] ${wf.id} (${wf.name}) - loaded from normalized tables (was deployed: ${wf.isDeployed})`
)
} else {
console.log(` [SKIP] ${wf.id} (${wf.name}) - no state available`)
skipCount++
continue
}
}
if (state) {
deploymentVersions.push({
id: uuidv4(),
workflowId: wf.id,
version: 1,
state,
createdAt: wf.deployedAt || new Date(),
createdBy: wf.userId || 'migration',
isActive: true,
})
successCount++
}
}
if (deploymentVersions.length > 0) {
if (DRY_RUN) {
console.log(` [DRY RUN] Would insert ${deploymentVersions.length} deployment versions`)
console.log(` [DRY RUN] Would mark ${deploymentVersions.length} workflows as deployed`)
} else {
try {
await db.insert(workflowDeploymentVersion).values(deploymentVersions)
console.log(` [SUCCESS] Inserted ${deploymentVersions.length} deployment versions`)
const workflowIds = deploymentVersions.map((v) => v.workflowId)
await db
.update(workflow)
.set({
isDeployed: true,
deployedAt: new Date(),
})
.where(
sql`${workflow.id} IN (${sql.join(
workflowIds.map((id) => sql`${id}`),
sql`, `
)})`
)
console.log(` [SUCCESS] Marked ${workflowIds.length} workflows as deployed`)
} catch (error) {
console.error(` [ERROR] Failed to insert batch:`, error)
errorCount += deploymentVersions.length
successCount -= deploymentVersions.length
}
}
}
}
console.log('\n---')
console.log('Migration Summary:')
console.log(` Success: ${successCount} workflows`)
console.log(` Skipped: ${skipCount} workflows`)
console.log(` Errors: ${errorCount} workflows`)
if (DRY_RUN) {
console.log('\n[DRY RUN] No changes were made to the database.')
console.log('Run without --dry-run flag to apply changes.')
} else {
console.log('\nMigration completed successfully!')
}
} catch (error) {
console.error('Fatal error during migration:', error)
process.exit(1)
} finally {
try {
await postgresClient.end({ timeout: 5 })
} catch {}
}
}
migrateWorkflows()
.then(() => {
console.log('\nDone!')
process.exit(0)
})
.catch((error) => {
console.error('Unexpected error:', error)
process.exit(1)
})