-
Notifications
You must be signed in to change notification settings - Fork 3.7k
Expand file tree
/
Copy pathroute.ts
More file actions
358 lines (318 loc) · 10.3 KB
/
Copy pathroute.ts
File metadata and controls
358 lines (318 loc) · 10.3 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
import { AuditAction, AuditResourceType, recordAudit } from '@sim/audit'
import { db } from '@sim/db'
import { permissions, type WorkspaceMode, workflow, workspace } from '@sim/db/schema'
import { createLogger } from '@sim/logger'
import { generateId } from '@sim/utils/id'
import { and, eq, isNull } from 'drizzle-orm'
import { type NextRequest, NextResponse } from 'next/server'
import { listWorkspacesQuerySchema } from '@/lib/api/contracts'
import { createWorkspaceContract } from '@/lib/api/contracts/workspaces'
import { parseRequest } from '@/lib/api/server'
import { getSession } from '@/lib/auth'
import { getActiveOrganizationId } from '@/lib/auth/session-response'
import { PlatformEvents } from '@/lib/core/telemetry'
import { withRouteHandler } from '@/lib/core/utils/with-route-handler'
import { captureServerEvent } from '@/lib/posthog/server'
import { buildDefaultWorkflowArtifacts } from '@/lib/workflows/defaults'
import { saveWorkflowToNormalizedTables } from '@/lib/workflows/persistence/utils'
import { getRandomWorkspaceColor } from '@/lib/workspaces/colors'
import { listWorkspacesForViewer } from '@/lib/workspaces/list'
import {
getWorkspaceCreationPolicy,
getWorkspaceInvitePolicy,
resolveInviteFlags,
WORKSPACE_MODE,
} from '@/lib/workspaces/policy'
const logger = createLogger('Workspaces')
// Get all workspaces for the current user
export const GET = withRouteHandler(async (request: Request) => {
const session = await getSession()
if (!session?.user?.id) {
return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })
}
const scopeResult = listWorkspacesQuerySchema.safeParse(
Object.fromEntries(new URL(request.url).searchParams.entries())
)
if (!scopeResult.success) {
return NextResponse.json(
{ error: 'Invalid query parameters', details: scopeResult.error.issues },
{ status: 400 }
)
}
const { scope } = scopeResult.data
const activeOrganizationId = getActiveOrganizationId(session)
const payload = await listWorkspacesForViewer({
userId: session.user.id,
activeOrganizationId,
scope,
})
const { lastActiveWorkspaceId, creationPolicy } = payload
if (scope === 'active' && payload.workspaces.length === 0) {
if (!creationPolicy.canCreate) {
return NextResponse.json({ workspaces: [], lastActiveWorkspaceId, creationPolicy })
}
const defaultWorkspace = await createDefaultWorkspace(
session.user.id,
session.user.name,
creationPolicy
)
await migrateExistingWorkflows(session.user.id, defaultWorkspace.id)
const refreshedCreationPolicy = await getWorkspaceCreationPolicy({
userId: session.user.id,
activeOrganizationId,
})
return NextResponse.json({
workspaces: [defaultWorkspace],
lastActiveWorkspaceId,
creationPolicy: refreshedCreationPolicy,
})
}
if (scope === 'active') {
await ensureWorkflowsHaveWorkspace(session.user.id, payload.workspaces[0].id)
}
return NextResponse.json(payload)
})
// POST /api/workspaces - Create a new workspace
export const POST = withRouteHandler(async (req: NextRequest) => {
const session = await getSession()
if (!session?.user?.id) {
return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })
}
try {
const parsed = await parseRequest(createWorkspaceContract, req, {})
if (!parsed.success) return parsed.response
const { name, color, skipDefaultWorkflow } = parsed.data.body
const activeOrganizationId = getActiveOrganizationId(session)
const creationPolicy = await getWorkspaceCreationPolicy({
userId: session.user.id,
activeOrganizationId,
})
if (!creationPolicy.canCreate) {
return NextResponse.json(
{ error: creationPolicy.reason || 'Workspace creation is not available.' },
{ status: creationPolicy.status }
)
}
const newWorkspace = await createWorkspace({
userId: session.user.id,
name,
skipDefaultWorkflow,
explicitColor: color,
organizationId: creationPolicy.organizationId,
workspaceMode: creationPolicy.workspaceMode,
billedAccountUserId: creationPolicy.billedAccountUserId,
})
captureServerEvent(
session.user.id,
'workspace_created',
{
workspace_id: newWorkspace.id,
name: newWorkspace.name,
workspace_mode: newWorkspace.workspaceMode,
organization_id: newWorkspace.organizationId,
},
{
groups: { workspace: newWorkspace.id },
setOnce: { first_workspace_created_at: new Date().toISOString() },
}
)
recordAudit({
workspaceId: newWorkspace.id,
actorId: session.user.id,
actorName: session.user.name,
actorEmail: session.user.email,
action: AuditAction.WORKSPACE_CREATED,
resourceType: AuditResourceType.WORKSPACE,
resourceId: newWorkspace.id,
resourceName: newWorkspace.name,
description: `Created workspace "${newWorkspace.name}"`,
metadata: {
name: newWorkspace.name,
color: newWorkspace.color,
workspaceMode: newWorkspace.workspaceMode,
organizationId: newWorkspace.organizationId,
},
request: req,
})
return NextResponse.json({ workspace: newWorkspace })
} catch (error) {
logger.error('Error creating workspace:', error)
return NextResponse.json({ error: 'Failed to create workspace' }, { status: 500 })
}
})
async function createDefaultWorkspace(
userId: string,
userName: string | null | undefined,
creationPolicy: {
organizationId: string | null
workspaceMode: WorkspaceMode
billedAccountUserId: string
}
) {
const firstName = userName?.split(' ')[0] || null
const workspaceName = firstName ? `${firstName}'s Workspace` : 'My Workspace'
return createWorkspace({
userId,
name: workspaceName,
organizationId: creationPolicy.organizationId,
workspaceMode: creationPolicy.workspaceMode,
billedAccountUserId: creationPolicy.billedAccountUserId,
})
}
interface CreateWorkspaceParams {
userId: string
name: string
skipDefaultWorkflow?: boolean
explicitColor?: string
organizationId: string | null
workspaceMode: WorkspaceMode
billedAccountUserId: string
}
async function createWorkspace({
userId,
name,
skipDefaultWorkflow = false,
explicitColor,
organizationId,
workspaceMode,
billedAccountUserId,
}: CreateWorkspaceParams) {
const workspaceId = generateId()
const workflowId = generateId()
const now = new Date()
const color = explicitColor || getRandomWorkspaceColor()
try {
await db.transaction(async (tx) => {
await tx.insert(workspace).values({
id: workspaceId,
name,
color,
ownerId: userId,
organizationId,
workspaceMode,
billedAccountUserId,
allowPersonalApiKeys: true,
createdAt: now,
updatedAt: now,
})
const permissionRows = [
{
id: generateId(),
entityType: 'workspace' as const,
entityId: workspaceId,
userId,
permissionType: 'admin' as const,
createdAt: now,
updatedAt: now,
},
]
if (
workspaceMode === WORKSPACE_MODE.ORGANIZATION &&
billedAccountUserId &&
billedAccountUserId !== userId
) {
permissionRows.push({
id: generateId(),
entityType: 'workspace' as const,
entityId: workspaceId,
userId: billedAccountUserId,
permissionType: 'admin' as const,
createdAt: now,
updatedAt: now,
})
}
await tx.insert(permissions).values(permissionRows)
if (!skipDefaultWorkflow) {
await tx.insert(workflow).values({
id: workflowId,
userId,
workspaceId,
folderId: null,
name: 'default-agent',
description: 'Your first workflow - start building here!',
lastSynced: now,
createdAt: now,
updatedAt: now,
isDeployed: false,
runCount: 0,
variables: {},
})
const { workflowState } = buildDefaultWorkflowArtifacts()
await saveWorkflowToNormalizedTables(workflowId, workflowState, tx)
}
logger.info(
skipDefaultWorkflow
? `Created ${workspaceMode} workspace ${workspaceId} for user ${userId}`
: `Created ${workspaceMode} workspace ${workspaceId} with initial workflow ${workflowId} for user ${userId}`
)
})
} catch (error) {
logger.error(`Failed to create workspace ${workspaceId}:`, error)
throw error
}
try {
PlatformEvents.workspaceCreated({
workspaceId,
userId,
name,
})
} catch {
// Telemetry should not fail the operation
}
const invitePolicy = await getWorkspaceInvitePolicy({
organizationId,
workspaceMode,
billedAccountUserId,
ownerId: userId,
})
return {
id: workspaceId,
name,
color,
ownerId: userId,
organizationId,
workspaceMode,
billedAccountUserId,
allowPersonalApiKeys: true,
createdAt: now,
updatedAt: now,
role: 'owner',
permissions: 'admin',
...resolveInviteFlags(invitePolicy, billedAccountUserId === userId),
}
}
async function migrateExistingWorkflows(userId: string, workspaceId: string) {
const orphanedWorkflows = await db
.select({ id: workflow.id })
.from(workflow)
.where(and(eq(workflow.userId, userId), isNull(workflow.workspaceId)))
if (orphanedWorkflows.length === 0) {
return // No orphaned workflows to migrate
}
logger.info(
`Migrating ${orphanedWorkflows.length} workflows to workspace ${workspaceId} for user ${userId}`
)
await db
.update(workflow)
.set({
workspaceId: workspaceId,
updatedAt: new Date(),
})
.where(and(eq(workflow.userId, userId), isNull(workflow.workspaceId)))
}
async function ensureWorkflowsHaveWorkspace(userId: string, defaultWorkspaceId: string) {
const orphanedWorkflows = await db
.select()
.from(workflow)
.where(and(eq(workflow.userId, userId), isNull(workflow.workspaceId)))
if (orphanedWorkflows.length > 0) {
await db
.update(workflow)
.set({
workspaceId: defaultWorkspaceId,
updatedAt: new Date(),
})
.where(and(eq(workflow.userId, userId), isNull(workflow.workspaceId)))
logger.info(`Fixed ${orphanedWorkflows.length} orphaned workflows for user ${userId}`)
}
}