chore: import upstream snapshot with attribution
Publish CLI Package / publish-npm (push) Waiting to run
Publish Python SDK / publish-pypi (push) Waiting to run
Publish TypeScript SDK / publish-npm (push) Waiting to run
CI / Migrate Dev DB (push) Has been skipped
CI / Detect Version (push) Has been cancelled
CI / Migrate DB (push) Has been cancelled
CI / Build Dev ECR (./docker/app.Dockerfile, ECR_APP) (push) Has been cancelled
CI / Build Dev ECR (./docker/db.Dockerfile, ECR_MIGRATIONS) (push) Has been cancelled
CI / Build Dev ECR (./docker/pii.Dockerfile, ECR_PII) (push) Has been cancelled
CI / Build Dev ECR (./docker/realtime.Dockerfile, ECR_REALTIME) (push) Has been cancelled
CI / Deploy Trigger.dev (Dev) (push) Has been cancelled
CI / Build AMD64 (./docker/app.Dockerfile, ECR_APP, ghcr.io/simstudioai/simstudio) (push) Has been cancelled
CI / Build AMD64 (./docker/db.Dockerfile, ECR_MIGRATIONS, ghcr.io/simstudioai/migrations) (push) Has been cancelled
CI / Build AMD64 (./docker/pii.Dockerfile, ECR_PII, ghcr.io/simstudioai/pii) (push) Has been cancelled
CI / Build AMD64 (./docker/realtime.Dockerfile, ECR_REALTIME, ghcr.io/simstudioai/realtime) (push) Has been cancelled
CI / Build ARM64 (GHCR Only) (./docker/app.Dockerfile, ghcr.io/simstudioai/simstudio) (push) Has been cancelled
CI / Build ARM64 (GHCR Only) (./docker/db.Dockerfile, ghcr.io/simstudioai/migrations) (push) Has been cancelled
CI / Build ARM64 (GHCR Only) (./docker/pii.Dockerfile, ghcr.io/simstudioai/pii) (push) Has been cancelled
CI / Build ARM64 (GHCR Only) (./docker/realtime.Dockerfile, ghcr.io/simstudioai/realtime) (push) Has been cancelled
CI / Create GHCR Manifests (ghcr.io/simstudioai/migrations) (push) Has been cancelled
CI / Create GHCR Manifests (ghcr.io/simstudioai/pii) (push) Has been cancelled
CI / Create GHCR Manifests (ghcr.io/simstudioai/realtime) (push) Has been cancelled
CI / Create GHCR Manifests (ghcr.io/simstudioai/simstudio) (push) Has been cancelled
CI / Check Docs Changes (push) Has been cancelled
CI / Process Docs (push) Has been cancelled
CI / Create GitHub Release (push) Has been cancelled
CI / Test and Build (push) Has been cancelled
Publish CLI Package / publish-npm (push) Waiting to run
Publish Python SDK / publish-pypi (push) Waiting to run
Publish TypeScript SDK / publish-npm (push) Waiting to run
CI / Migrate Dev DB (push) Has been skipped
CI / Detect Version (push) Has been cancelled
CI / Migrate DB (push) Has been cancelled
CI / Build Dev ECR (./docker/app.Dockerfile, ECR_APP) (push) Has been cancelled
CI / Build Dev ECR (./docker/db.Dockerfile, ECR_MIGRATIONS) (push) Has been cancelled
CI / Build Dev ECR (./docker/pii.Dockerfile, ECR_PII) (push) Has been cancelled
CI / Build Dev ECR (./docker/realtime.Dockerfile, ECR_REALTIME) (push) Has been cancelled
CI / Deploy Trigger.dev (Dev) (push) Has been cancelled
CI / Build AMD64 (./docker/app.Dockerfile, ECR_APP, ghcr.io/simstudioai/simstudio) (push) Has been cancelled
CI / Build AMD64 (./docker/db.Dockerfile, ECR_MIGRATIONS, ghcr.io/simstudioai/migrations) (push) Has been cancelled
CI / Build AMD64 (./docker/pii.Dockerfile, ECR_PII, ghcr.io/simstudioai/pii) (push) Has been cancelled
CI / Build AMD64 (./docker/realtime.Dockerfile, ECR_REALTIME, ghcr.io/simstudioai/realtime) (push) Has been cancelled
CI / Build ARM64 (GHCR Only) (./docker/app.Dockerfile, ghcr.io/simstudioai/simstudio) (push) Has been cancelled
CI / Build ARM64 (GHCR Only) (./docker/db.Dockerfile, ghcr.io/simstudioai/migrations) (push) Has been cancelled
CI / Build ARM64 (GHCR Only) (./docker/pii.Dockerfile, ghcr.io/simstudioai/pii) (push) Has been cancelled
CI / Build ARM64 (GHCR Only) (./docker/realtime.Dockerfile, ghcr.io/simstudioai/realtime) (push) Has been cancelled
CI / Create GHCR Manifests (ghcr.io/simstudioai/migrations) (push) Has been cancelled
CI / Create GHCR Manifests (ghcr.io/simstudioai/pii) (push) Has been cancelled
CI / Create GHCR Manifests (ghcr.io/simstudioai/realtime) (push) Has been cancelled
CI / Create GHCR Manifests (ghcr.io/simstudioai/simstudio) (push) Has been cancelled
CI / Check Docs Changes (push) Has been cancelled
CI / Process Docs (push) Has been cancelled
CI / Create GitHub Release (push) Has been cancelled
CI / Test and Build (push) Has been cancelled
This commit is contained in:
@@ -0,0 +1,271 @@
|
||||
/**
|
||||
* @vitest-environment node
|
||||
*
|
||||
* Tests for POST/DELETE /api/v1/workflows/[id]/deploy — verifies auth,
|
||||
* workspace admin permission enforcement, optional body handling, and the
|
||||
* mapping of orchestration results to v1 API responses.
|
||||
*/
|
||||
|
||||
import { WorkflowLockedError } from '@sim/platform-authz/workflow'
|
||||
import { createMockRequest, workflowAuthzMockFns } from '@sim/testing'
|
||||
import { NextRequest, NextResponse } from 'next/server'
|
||||
import { beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
|
||||
const {
|
||||
mockCheckRateLimit,
|
||||
mockValidateWorkspaceAccess,
|
||||
mockPerformFullDeploy,
|
||||
mockPerformFullUndeploy,
|
||||
mockCaptureServerEvent,
|
||||
} = vi.hoisted(() => ({
|
||||
mockCheckRateLimit: vi.fn(),
|
||||
mockValidateWorkspaceAccess: vi.fn(),
|
||||
mockPerformFullDeploy: vi.fn(),
|
||||
mockPerformFullUndeploy: vi.fn(),
|
||||
mockCaptureServerEvent: vi.fn(),
|
||||
}))
|
||||
|
||||
vi.mock('@/app/api/v1/middleware', () => ({
|
||||
checkRateLimit: mockCheckRateLimit,
|
||||
createRateLimitResponse: vi.fn(() =>
|
||||
NextResponse.json({ error: 'Unauthorized' }, { status: 401 })
|
||||
),
|
||||
validateWorkspaceAccess: mockValidateWorkspaceAccess,
|
||||
}))
|
||||
|
||||
vi.mock('@/lib/workflows/orchestration', () => ({
|
||||
performFullDeploy: mockPerformFullDeploy,
|
||||
performFullUndeploy: mockPerformFullUndeploy,
|
||||
}))
|
||||
|
||||
vi.mock('@/app/api/v1/logs/meta', () => ({
|
||||
getUserLimits: vi.fn().mockResolvedValue({}),
|
||||
createApiResponse: vi.fn((body: unknown) => ({ body, headers: {} })),
|
||||
}))
|
||||
|
||||
vi.mock('@/lib/posthog/server', () => ({
|
||||
captureServerEvent: mockCaptureServerEvent,
|
||||
}))
|
||||
|
||||
import { DELETE, POST } from '@/app/api/v1/workflows/[id]/deploy/route'
|
||||
|
||||
const WORKFLOW_ID = 'wf-1'
|
||||
const WORKFLOW_RECORD = {
|
||||
id: WORKFLOW_ID,
|
||||
name: 'My Workflow',
|
||||
workspaceId: 'ws-1',
|
||||
isDeployed: true,
|
||||
}
|
||||
|
||||
function makeContext(id = WORKFLOW_ID) {
|
||||
return { params: Promise.resolve({ id }) }
|
||||
}
|
||||
|
||||
function makeRequest(method: string, body?: unknown) {
|
||||
return createMockRequest(
|
||||
method,
|
||||
body,
|
||||
{},
|
||||
`http://localhost:3000/api/v1/workflows/${WORKFLOW_ID}/deploy`
|
||||
)
|
||||
}
|
||||
|
||||
describe('POST /api/v1/workflows/[id]/deploy', () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
mockCheckRateLimit.mockResolvedValue({ allowed: true, userId: 'user-1' })
|
||||
mockValidateWorkspaceAccess.mockResolvedValue(null)
|
||||
workflowAuthzMockFns.mockGetActiveWorkflowRecord.mockResolvedValue(WORKFLOW_RECORD)
|
||||
workflowAuthzMockFns.mockAssertWorkflowMutable.mockResolvedValue(undefined)
|
||||
mockPerformFullDeploy.mockResolvedValue({
|
||||
success: true,
|
||||
deployedAt: new Date('2026-06-12T00:00:00Z'),
|
||||
version: 4,
|
||||
warnings: undefined,
|
||||
})
|
||||
})
|
||||
|
||||
it('rejects unauthenticated requests', async () => {
|
||||
mockCheckRateLimit.mockResolvedValue({ allowed: false, error: 'Invalid API key' })
|
||||
|
||||
const response = await POST(makeRequest('POST'), makeContext())
|
||||
|
||||
expect(response.status).toBe(401)
|
||||
expect(mockPerformFullDeploy).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('returns 404 when the workflow does not exist', async () => {
|
||||
workflowAuthzMockFns.mockGetActiveWorkflowRecord.mockResolvedValue(null)
|
||||
|
||||
const response = await POST(makeRequest('POST'), makeContext())
|
||||
|
||||
expect(response.status).toBe(404)
|
||||
expect(mockPerformFullDeploy).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('masks missing admin permission as 404', async () => {
|
||||
mockValidateWorkspaceAccess.mockResolvedValue(
|
||||
NextResponse.json({ error: 'Access denied' }, { status: 403 })
|
||||
)
|
||||
|
||||
const response = await POST(makeRequest('POST'), makeContext())
|
||||
|
||||
expect(response.status).toBe(404)
|
||||
expect(mockValidateWorkspaceAccess).toHaveBeenCalledWith(
|
||||
expect.objectContaining({ allowed: true }),
|
||||
'user-1',
|
||||
'ws-1',
|
||||
'admin'
|
||||
)
|
||||
expect(mockPerformFullDeploy).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('rejects a malformed JSON body', async () => {
|
||||
const request = new NextRequest(
|
||||
new URL(`http://localhost:3000/api/v1/workflows/${WORKFLOW_ID}/deploy`),
|
||||
{
|
||||
method: 'POST',
|
||||
headers: new Headers({ 'Content-Type': 'application/json' }),
|
||||
body: '{"name": "Release 4"',
|
||||
}
|
||||
)
|
||||
|
||||
const response = await POST(request, makeContext())
|
||||
|
||||
expect(response.status).toBe(400)
|
||||
expect(mockPerformFullDeploy).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('rejects invalid version metadata', async () => {
|
||||
const response = await POST(makeRequest('POST', { name: '' }), makeContext())
|
||||
|
||||
expect(response.status).toBe(400)
|
||||
expect(mockPerformFullDeploy).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('deploys without a request body', async () => {
|
||||
const response = await POST(makeRequest('POST'), makeContext())
|
||||
|
||||
expect(response.status).toBe(200)
|
||||
expect(mockPerformFullDeploy).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
workflowId: WORKFLOW_ID,
|
||||
userId: 'user-1',
|
||||
versionName: undefined,
|
||||
versionDescription: undefined,
|
||||
})
|
||||
)
|
||||
|
||||
const body = await response.json()
|
||||
expect(body.data).toEqual({
|
||||
id: WORKFLOW_ID,
|
||||
isDeployed: true,
|
||||
deployedAt: '2026-06-12T00:00:00.000Z',
|
||||
version: 4,
|
||||
warnings: [],
|
||||
})
|
||||
})
|
||||
|
||||
it('passes version metadata through to the deploy orchestration', async () => {
|
||||
const response = await POST(
|
||||
makeRequest('POST', { name: 'Release 4', description: 'Fixes the agent prompt' }),
|
||||
makeContext()
|
||||
)
|
||||
|
||||
expect(response.status).toBe(200)
|
||||
expect(mockPerformFullDeploy).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
versionName: 'Release 4',
|
||||
versionDescription: 'Fixes the agent prompt',
|
||||
})
|
||||
)
|
||||
expect(mockCaptureServerEvent).toHaveBeenCalledWith(
|
||||
'user-1',
|
||||
'workflow_deployed',
|
||||
expect.objectContaining({ workflow_id: WORKFLOW_ID }),
|
||||
expect.anything()
|
||||
)
|
||||
})
|
||||
|
||||
it('maps validation failures from the orchestration to 400', async () => {
|
||||
mockPerformFullDeploy.mockResolvedValue({
|
||||
success: false,
|
||||
error: 'Invalid schedule configuration',
|
||||
errorCode: 'validation',
|
||||
})
|
||||
|
||||
const response = await POST(makeRequest('POST'), makeContext())
|
||||
|
||||
expect(response.status).toBe(400)
|
||||
const body = await response.json()
|
||||
expect(body.error).toBe('Invalid schedule configuration')
|
||||
})
|
||||
|
||||
it('returns 423 when the workflow is locked', async () => {
|
||||
workflowAuthzMockFns.mockAssertWorkflowMutable.mockRejectedValue(new WorkflowLockedError())
|
||||
|
||||
const response = await POST(makeRequest('POST'), makeContext())
|
||||
|
||||
expect(response.status).toBe(423)
|
||||
expect(mockPerformFullDeploy).not.toHaveBeenCalled()
|
||||
})
|
||||
})
|
||||
|
||||
describe('DELETE /api/v1/workflows/[id]/deploy', () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
mockCheckRateLimit.mockResolvedValue({ allowed: true, userId: 'user-1' })
|
||||
mockValidateWorkspaceAccess.mockResolvedValue(null)
|
||||
workflowAuthzMockFns.mockGetActiveWorkflowRecord.mockResolvedValue(WORKFLOW_RECORD)
|
||||
workflowAuthzMockFns.mockAssertWorkflowMutable.mockResolvedValue(undefined)
|
||||
mockPerformFullUndeploy.mockResolvedValue({ success: true })
|
||||
})
|
||||
|
||||
it('returns 400 when the workflow is not deployed', async () => {
|
||||
workflowAuthzMockFns.mockGetActiveWorkflowRecord.mockResolvedValue({
|
||||
...WORKFLOW_RECORD,
|
||||
isDeployed: false,
|
||||
})
|
||||
|
||||
const response = await DELETE(makeRequest('DELETE'), makeContext())
|
||||
|
||||
expect(response.status).toBe(400)
|
||||
const body = await response.json()
|
||||
expect(body.error).toBe('Workflow is not deployed')
|
||||
expect(mockPerformFullUndeploy).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('undeploys a deployed workflow', async () => {
|
||||
const response = await DELETE(makeRequest('DELETE'), makeContext())
|
||||
|
||||
expect(response.status).toBe(200)
|
||||
expect(mockPerformFullUndeploy).toHaveBeenCalledWith(
|
||||
expect.objectContaining({ workflowId: WORKFLOW_ID, userId: 'user-1' })
|
||||
)
|
||||
|
||||
const body = await response.json()
|
||||
expect(body.data).toEqual({
|
||||
id: WORKFLOW_ID,
|
||||
isDeployed: false,
|
||||
deployedAt: null,
|
||||
warnings: [],
|
||||
})
|
||||
expect(mockCaptureServerEvent).toHaveBeenCalledWith(
|
||||
'user-1',
|
||||
'workflow_undeployed',
|
||||
expect.objectContaining({ workflow_id: WORKFLOW_ID }),
|
||||
expect.anything()
|
||||
)
|
||||
})
|
||||
|
||||
it('masks missing admin permission as 404', async () => {
|
||||
mockValidateWorkspaceAccess.mockResolvedValue(
|
||||
NextResponse.json({ error: 'Access denied' }, { status: 403 })
|
||||
)
|
||||
|
||||
const response = await DELETE(makeRequest('DELETE'), makeContext())
|
||||
|
||||
expect(response.status).toBe(404)
|
||||
expect(mockPerformFullUndeploy).not.toHaveBeenCalled()
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,184 @@
|
||||
import { createLogger } from '@sim/logger'
|
||||
import { assertWorkflowMutable, WorkflowLockedError } from '@sim/platform-authz/workflow'
|
||||
import { getErrorMessage } from '@sim/utils/errors'
|
||||
import { type NextRequest, NextResponse } from 'next/server'
|
||||
import {
|
||||
v1DeployWorkflowBodySchema,
|
||||
v1DeployWorkflowContract,
|
||||
v1UndeployWorkflowContract,
|
||||
} from '@/lib/api/contracts/v1/workflows'
|
||||
import { parseOptionalJsonBody, parseRequest, validationErrorResponse } from '@/lib/api/server'
|
||||
import { generateRequestId } from '@/lib/core/utils/request'
|
||||
import { withRouteHandler } from '@/lib/core/utils/with-route-handler'
|
||||
import { captureServerEvent } from '@/lib/posthog/server'
|
||||
import { performFullDeploy, performFullUndeploy } from '@/lib/workflows/orchestration'
|
||||
import { statusForOrchestrationError } from '@/lib/workflows/orchestration/types'
|
||||
import { createApiResponse, getUserLimits } from '@/app/api/v1/logs/meta'
|
||||
import { checkRateLimit, createRateLimitResponse } from '@/app/api/v1/middleware'
|
||||
import { resolveV1DeploymentWorkflow } from '@/app/api/v1/workflows/utils'
|
||||
|
||||
const logger = createLogger('V1WorkflowDeployAPI')
|
||||
|
||||
export const dynamic = 'force-dynamic'
|
||||
export const runtime = 'nodejs'
|
||||
export const maxDuration = 120
|
||||
|
||||
export const POST = withRouteHandler(
|
||||
async (request: NextRequest, context: { params: Promise<{ id: string }> }) => {
|
||||
const requestId = generateRequestId()
|
||||
|
||||
try {
|
||||
const rateLimit = await checkRateLimit(request, 'workflow-deploy')
|
||||
if (!rateLimit.allowed) {
|
||||
return createRateLimitResponse(rateLimit)
|
||||
}
|
||||
|
||||
const userId = rateLimit.userId!
|
||||
const parsed = await parseRequest(v1DeployWorkflowContract, request, context, {
|
||||
validationErrorResponse: () =>
|
||||
NextResponse.json({ error: 'Invalid workflow ID' }, { status: 400 }),
|
||||
})
|
||||
if (!parsed.success) return parsed.response
|
||||
|
||||
const { id } = parsed.data.params
|
||||
|
||||
const rawBody = await parseOptionalJsonBody(request)
|
||||
if (!rawBody.success) return rawBody.response
|
||||
const body = v1DeployWorkflowBodySchema.safeParse(rawBody.data ?? {})
|
||||
if (!body.success) {
|
||||
return validationErrorResponse(body.error)
|
||||
}
|
||||
|
||||
const target = await resolveV1DeploymentWorkflow(rateLimit, userId, id)
|
||||
if (!target.ok) return target.response
|
||||
const { workflow, workspaceId } = target
|
||||
|
||||
await assertWorkflowMutable(id)
|
||||
|
||||
logger.info(`[${requestId}] Deploying workflow ${id} via v1 API`, { userId })
|
||||
|
||||
const result = await performFullDeploy({
|
||||
workflowId: id,
|
||||
userId,
|
||||
workflowName: workflow.name || undefined,
|
||||
versionName: body.data.name,
|
||||
versionDescription: body.data.description ?? undefined,
|
||||
requestId,
|
||||
request,
|
||||
})
|
||||
|
||||
if (!result.success) {
|
||||
return NextResponse.json(
|
||||
{ error: result.error || 'Failed to deploy workflow' },
|
||||
{ status: statusForOrchestrationError(result.errorCode) }
|
||||
)
|
||||
}
|
||||
|
||||
captureServerEvent(
|
||||
userId,
|
||||
'workflow_deployed',
|
||||
{ workflow_id: id, workspace_id: workspaceId },
|
||||
{
|
||||
groups: { workspace: workspaceId },
|
||||
setOnce: { first_workflow_deployed_at: new Date().toISOString() },
|
||||
}
|
||||
)
|
||||
|
||||
const limits = await getUserLimits(userId)
|
||||
const apiResponse = createApiResponse(
|
||||
{
|
||||
data: {
|
||||
id,
|
||||
isDeployed: true,
|
||||
deployedAt: result.deployedAt?.toISOString() ?? null,
|
||||
version: result.version,
|
||||
warnings: result.warnings ?? [],
|
||||
},
|
||||
},
|
||||
limits,
|
||||
rateLimit
|
||||
)
|
||||
|
||||
return NextResponse.json(apiResponse.body, { headers: apiResponse.headers })
|
||||
} catch (error: unknown) {
|
||||
if (error instanceof WorkflowLockedError) {
|
||||
return NextResponse.json({ error: error.message }, { status: error.status })
|
||||
}
|
||||
const message = getErrorMessage(error, 'Unknown error')
|
||||
logger.error(`[${requestId}] Workflow deploy error`, { error: message })
|
||||
return NextResponse.json({ error: 'Internal server error' }, { status: 500 })
|
||||
}
|
||||
}
|
||||
)
|
||||
|
||||
export const DELETE = withRouteHandler(
|
||||
async (request: NextRequest, context: { params: Promise<{ id: string }> }) => {
|
||||
const requestId = generateRequestId()
|
||||
|
||||
try {
|
||||
const rateLimit = await checkRateLimit(request, 'workflow-deploy')
|
||||
if (!rateLimit.allowed) {
|
||||
return createRateLimitResponse(rateLimit)
|
||||
}
|
||||
|
||||
const userId = rateLimit.userId!
|
||||
const parsed = await parseRequest(v1UndeployWorkflowContract, request, context, {
|
||||
validationErrorResponse: () =>
|
||||
NextResponse.json({ error: 'Invalid workflow ID' }, { status: 400 }),
|
||||
})
|
||||
if (!parsed.success) return parsed.response
|
||||
|
||||
const { id } = parsed.data.params
|
||||
|
||||
const target = await resolveV1DeploymentWorkflow(rateLimit, userId, id)
|
||||
if (!target.ok) return target.response
|
||||
const { workflow, workspaceId } = target
|
||||
|
||||
if (!workflow.isDeployed) {
|
||||
return NextResponse.json({ error: 'Workflow is not deployed' }, { status: 400 })
|
||||
}
|
||||
|
||||
await assertWorkflowMutable(id)
|
||||
|
||||
logger.info(`[${requestId}] Undeploying workflow ${id} via v1 API`, { userId })
|
||||
|
||||
const result = await performFullUndeploy({ workflowId: id, userId, requestId })
|
||||
if (!result.success) {
|
||||
return NextResponse.json(
|
||||
{ error: result.error || 'Failed to undeploy workflow' },
|
||||
{ status: 500 }
|
||||
)
|
||||
}
|
||||
|
||||
captureServerEvent(
|
||||
userId,
|
||||
'workflow_undeployed',
|
||||
{ workflow_id: id, workspace_id: workspaceId },
|
||||
{ groups: { workspace: workspaceId } }
|
||||
)
|
||||
|
||||
const limits = await getUserLimits(userId)
|
||||
const apiResponse = createApiResponse(
|
||||
{
|
||||
data: {
|
||||
id,
|
||||
isDeployed: false,
|
||||
deployedAt: null,
|
||||
warnings: result.warnings ?? [],
|
||||
},
|
||||
},
|
||||
limits,
|
||||
rateLimit
|
||||
)
|
||||
|
||||
return NextResponse.json(apiResponse.body, { headers: apiResponse.headers })
|
||||
} catch (error: unknown) {
|
||||
if (error instanceof WorkflowLockedError) {
|
||||
return NextResponse.json({ error: error.message }, { status: error.status })
|
||||
}
|
||||
const message = getErrorMessage(error, 'Unknown error')
|
||||
logger.error(`[${requestId}] Workflow undeploy error`, { error: message })
|
||||
return NextResponse.json({ error: 'Internal server error' }, { status: 500 })
|
||||
}
|
||||
}
|
||||
)
|
||||
@@ -0,0 +1,216 @@
|
||||
/**
|
||||
* @vitest-environment node
|
||||
*
|
||||
* Tests for POST /api/v1/workflows/[id]/rollback — verifies target version
|
||||
* resolution (previous version by default, explicit version when provided)
|
||||
* and the mapping of activation results to v1 API responses.
|
||||
*/
|
||||
|
||||
import { WorkflowLockedError } from '@sim/platform-authz/workflow'
|
||||
import { createMockRequest, workflowAuthzMockFns } from '@sim/testing'
|
||||
import { NextResponse } from 'next/server'
|
||||
import { beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
|
||||
const {
|
||||
mockCheckRateLimit,
|
||||
mockValidateWorkspaceAccess,
|
||||
mockPerformActivateVersion,
|
||||
mockFindPreviousDeploymentVersion,
|
||||
} = vi.hoisted(() => ({
|
||||
mockCheckRateLimit: vi.fn(),
|
||||
mockValidateWorkspaceAccess: vi.fn(),
|
||||
mockPerformActivateVersion: vi.fn(),
|
||||
mockFindPreviousDeploymentVersion: vi.fn(),
|
||||
}))
|
||||
|
||||
vi.mock('@/lib/workflows/persistence/utils', () => ({
|
||||
findPreviousDeploymentVersion: mockFindPreviousDeploymentVersion,
|
||||
}))
|
||||
|
||||
vi.mock('@/app/api/v1/middleware', () => ({
|
||||
checkRateLimit: mockCheckRateLimit,
|
||||
createRateLimitResponse: vi.fn(() =>
|
||||
NextResponse.json({ error: 'Unauthorized' }, { status: 401 })
|
||||
),
|
||||
validateWorkspaceAccess: mockValidateWorkspaceAccess,
|
||||
}))
|
||||
|
||||
vi.mock('@/lib/workflows/orchestration', () => ({
|
||||
performActivateVersion: mockPerformActivateVersion,
|
||||
}))
|
||||
|
||||
vi.mock('@/app/api/v1/logs/meta', () => ({
|
||||
getUserLimits: vi.fn().mockResolvedValue({}),
|
||||
createApiResponse: vi.fn((body: unknown) => ({ body, headers: {} })),
|
||||
}))
|
||||
|
||||
vi.mock('@/lib/posthog/server', () => ({
|
||||
captureServerEvent: vi.fn(),
|
||||
}))
|
||||
|
||||
import { POST } from '@/app/api/v1/workflows/[id]/rollback/route'
|
||||
|
||||
const WORKFLOW_ID = 'wf-1'
|
||||
const WORKFLOW_RECORD = {
|
||||
id: WORKFLOW_ID,
|
||||
name: 'My Workflow',
|
||||
workspaceId: 'ws-1',
|
||||
isDeployed: true,
|
||||
}
|
||||
|
||||
function makeContext(id = WORKFLOW_ID) {
|
||||
return { params: Promise.resolve({ id }) }
|
||||
}
|
||||
|
||||
function makeRequest(body?: unknown) {
|
||||
return createMockRequest(
|
||||
'POST',
|
||||
body,
|
||||
{},
|
||||
`http://localhost:3000/api/v1/workflows/${WORKFLOW_ID}/rollback`
|
||||
)
|
||||
}
|
||||
|
||||
describe('POST /api/v1/workflows/[id]/rollback', () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
mockCheckRateLimit.mockResolvedValue({ allowed: true, userId: 'user-1' })
|
||||
mockValidateWorkspaceAccess.mockResolvedValue(null)
|
||||
workflowAuthzMockFns.mockGetActiveWorkflowRecord.mockResolvedValue(WORKFLOW_RECORD)
|
||||
workflowAuthzMockFns.mockAssertWorkflowMutable.mockResolvedValue(undefined)
|
||||
mockPerformActivateVersion.mockResolvedValue({
|
||||
success: true,
|
||||
deployedAt: new Date('2026-06-12T00:00:00Z'),
|
||||
})
|
||||
})
|
||||
|
||||
it('rejects unauthenticated requests', async () => {
|
||||
mockCheckRateLimit.mockResolvedValue({ allowed: false, error: 'Invalid API key' })
|
||||
|
||||
const response = await POST(makeRequest(), makeContext())
|
||||
|
||||
expect(response.status).toBe(401)
|
||||
expect(mockPerformActivateVersion).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('returns 404 when the workflow does not exist', async () => {
|
||||
workflowAuthzMockFns.mockGetActiveWorkflowRecord.mockResolvedValue(null)
|
||||
|
||||
const response = await POST(makeRequest(), makeContext())
|
||||
|
||||
expect(response.status).toBe(404)
|
||||
expect(mockPerformActivateVersion).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('returns 423 when the workflow is locked', async () => {
|
||||
workflowAuthzMockFns.mockAssertWorkflowMutable.mockRejectedValue(new WorkflowLockedError())
|
||||
|
||||
const response = await POST(makeRequest(), makeContext())
|
||||
|
||||
expect(response.status).toBe(423)
|
||||
expect(mockPerformActivateVersion).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('rolls back to the previous version when no version is given', async () => {
|
||||
mockFindPreviousDeploymentVersion.mockResolvedValue({ ok: true, version: 4 })
|
||||
|
||||
const response = await POST(makeRequest(), makeContext())
|
||||
|
||||
expect(response.status).toBe(200)
|
||||
expect(mockPerformActivateVersion).toHaveBeenCalledWith(
|
||||
expect.objectContaining({ workflowId: WORKFLOW_ID, version: 4, userId: 'user-1' })
|
||||
)
|
||||
|
||||
const body = await response.json()
|
||||
expect(body.data).toEqual({
|
||||
id: WORKFLOW_ID,
|
||||
isDeployed: true,
|
||||
deployedAt: '2026-06-12T00:00:00.000Z',
|
||||
version: 4,
|
||||
warnings: [],
|
||||
})
|
||||
})
|
||||
|
||||
it('returns 400 when the workflow is not deployed, even with an explicit version', async () => {
|
||||
workflowAuthzMockFns.mockGetActiveWorkflowRecord.mockResolvedValue({
|
||||
...WORKFLOW_RECORD,
|
||||
isDeployed: false,
|
||||
})
|
||||
|
||||
const response = await POST(makeRequest({ version: 2 }), makeContext())
|
||||
|
||||
expect(response.status).toBe(400)
|
||||
const body = await response.json()
|
||||
expect(body.error).toBe('Workflow is not deployed')
|
||||
expect(mockPerformActivateVersion).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('rolls back to an explicit version when provided', async () => {
|
||||
const response = await POST(makeRequest({ version: 2 }), makeContext())
|
||||
|
||||
expect(response.status).toBe(200)
|
||||
expect(mockPerformActivateVersion).toHaveBeenCalledWith(expect.objectContaining({ version: 2 }))
|
||||
expect(mockFindPreviousDeploymentVersion).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('rejects a non-integer version', async () => {
|
||||
const response = await POST(makeRequest({ version: 1.5 }), makeContext())
|
||||
|
||||
expect(response.status).toBe(400)
|
||||
expect(mockPerformActivateVersion).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('returns 400 when there is no active deployment to roll back from', async () => {
|
||||
mockFindPreviousDeploymentVersion.mockResolvedValue({ ok: false, reason: 'no_active_version' })
|
||||
|
||||
const response = await POST(makeRequest(), makeContext())
|
||||
|
||||
expect(response.status).toBe(400)
|
||||
const body = await response.json()
|
||||
expect(body.error).toBe('Workflow has no active deployment to roll back from')
|
||||
expect(mockPerformActivateVersion).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('returns 400 when there is no previous version to roll back to', async () => {
|
||||
mockFindPreviousDeploymentVersion.mockResolvedValue({
|
||||
ok: false,
|
||||
reason: 'no_previous_version',
|
||||
})
|
||||
|
||||
const response = await POST(makeRequest(), makeContext())
|
||||
|
||||
expect(response.status).toBe(400)
|
||||
const body = await response.json()
|
||||
expect(body.error).toBe('No previous deployment version to roll back to')
|
||||
expect(mockPerformActivateVersion).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('maps a missing target version to 404', async () => {
|
||||
mockPerformActivateVersion.mockResolvedValue({
|
||||
success: false,
|
||||
error: 'Deployment version not found',
|
||||
errorCode: 'not_found',
|
||||
})
|
||||
|
||||
const response = await POST(makeRequest({ version: 99 }), makeContext())
|
||||
|
||||
expect(response.status).toBe(404)
|
||||
})
|
||||
|
||||
it('masks missing admin permission as 404', async () => {
|
||||
mockValidateWorkspaceAccess.mockResolvedValue(
|
||||
NextResponse.json({ error: 'Access denied' }, { status: 403 })
|
||||
)
|
||||
|
||||
const response = await POST(makeRequest(), makeContext())
|
||||
|
||||
expect(response.status).toBe(404)
|
||||
expect(mockValidateWorkspaceAccess).toHaveBeenCalledWith(
|
||||
expect.objectContaining({ allowed: true }),
|
||||
'user-1',
|
||||
'ws-1',
|
||||
'admin'
|
||||
)
|
||||
expect(mockPerformActivateVersion).not.toHaveBeenCalled()
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,128 @@
|
||||
import { createLogger } from '@sim/logger'
|
||||
import { assertWorkflowMutable, WorkflowLockedError } from '@sim/platform-authz/workflow'
|
||||
import { getErrorMessage } from '@sim/utils/errors'
|
||||
import { type NextRequest, NextResponse } from 'next/server'
|
||||
import {
|
||||
v1RollbackWorkflowBodySchema,
|
||||
v1RollbackWorkflowContract,
|
||||
} from '@/lib/api/contracts/v1/workflows'
|
||||
import { parseOptionalJsonBody, parseRequest, validationErrorResponse } from '@/lib/api/server'
|
||||
import { generateRequestId } from '@/lib/core/utils/request'
|
||||
import { withRouteHandler } from '@/lib/core/utils/with-route-handler'
|
||||
import { captureServerEvent } from '@/lib/posthog/server'
|
||||
import { performActivateVersion } from '@/lib/workflows/orchestration'
|
||||
import { statusForOrchestrationError } from '@/lib/workflows/orchestration/types'
|
||||
import { findPreviousDeploymentVersion } from '@/lib/workflows/persistence/utils'
|
||||
import { createApiResponse, getUserLimits } from '@/app/api/v1/logs/meta'
|
||||
import { checkRateLimit, createRateLimitResponse } from '@/app/api/v1/middleware'
|
||||
import { resolveV1DeploymentWorkflow } from '@/app/api/v1/workflows/utils'
|
||||
|
||||
const logger = createLogger('V1WorkflowRollbackAPI')
|
||||
|
||||
export const dynamic = 'force-dynamic'
|
||||
export const runtime = 'nodejs'
|
||||
export const maxDuration = 120
|
||||
|
||||
export const POST = withRouteHandler(
|
||||
async (request: NextRequest, context: { params: Promise<{ id: string }> }) => {
|
||||
const requestId = generateRequestId()
|
||||
|
||||
try {
|
||||
const rateLimit = await checkRateLimit(request, 'workflow-rollback')
|
||||
if (!rateLimit.allowed) {
|
||||
return createRateLimitResponse(rateLimit)
|
||||
}
|
||||
|
||||
const userId = rateLimit.userId!
|
||||
const parsed = await parseRequest(v1RollbackWorkflowContract, request, context, {
|
||||
validationErrorResponse: () =>
|
||||
NextResponse.json({ error: 'Invalid workflow ID' }, { status: 400 }),
|
||||
})
|
||||
if (!parsed.success) return parsed.response
|
||||
|
||||
const { id } = parsed.data.params
|
||||
|
||||
const rawBody = await parseOptionalJsonBody(request)
|
||||
if (!rawBody.success) return rawBody.response
|
||||
const body = v1RollbackWorkflowBodySchema.safeParse(rawBody.data ?? {})
|
||||
if (!body.success) {
|
||||
return validationErrorResponse(body.error)
|
||||
}
|
||||
|
||||
const target = await resolveV1DeploymentWorkflow(rateLimit, userId, id)
|
||||
if (!target.ok) return target.response
|
||||
const { workflow, workspaceId } = target
|
||||
|
||||
if (!workflow.isDeployed) {
|
||||
return NextResponse.json({ error: 'Workflow is not deployed' }, { status: 400 })
|
||||
}
|
||||
|
||||
await assertWorkflowMutable(id)
|
||||
|
||||
let targetVersion = body.data.version
|
||||
if (targetVersion === undefined) {
|
||||
const previous = await findPreviousDeploymentVersion(id)
|
||||
if (!previous.ok) {
|
||||
const message =
|
||||
previous.reason === 'no_active_version'
|
||||
? 'Workflow has no active deployment to roll back from'
|
||||
: 'No previous deployment version to roll back to'
|
||||
return NextResponse.json({ error: message }, { status: 400 })
|
||||
}
|
||||
targetVersion = previous.version
|
||||
}
|
||||
|
||||
logger.info(
|
||||
`[${requestId}] Rolling back workflow ${id} to version ${targetVersion} via v1 API`,
|
||||
{ userId }
|
||||
)
|
||||
|
||||
const result = await performActivateVersion({
|
||||
workflowId: id,
|
||||
version: targetVersion,
|
||||
userId,
|
||||
workflow: workflow as Record<string, unknown>,
|
||||
requestId,
|
||||
request,
|
||||
})
|
||||
|
||||
if (!result.success) {
|
||||
return NextResponse.json(
|
||||
{ error: result.error || 'Failed to roll back workflow' },
|
||||
{ status: statusForOrchestrationError(result.errorCode) }
|
||||
)
|
||||
}
|
||||
|
||||
captureServerEvent(
|
||||
userId,
|
||||
'deployment_version_activated',
|
||||
{ workflow_id: id, workspace_id: workspaceId, version: targetVersion },
|
||||
{ groups: { workspace: workspaceId } }
|
||||
)
|
||||
|
||||
const limits = await getUserLimits(userId)
|
||||
const apiResponse = createApiResponse(
|
||||
{
|
||||
data: {
|
||||
id,
|
||||
isDeployed: true,
|
||||
deployedAt: result.deployedAt?.toISOString() ?? null,
|
||||
version: targetVersion,
|
||||
warnings: result.warnings ?? [],
|
||||
},
|
||||
},
|
||||
limits,
|
||||
rateLimit
|
||||
)
|
||||
|
||||
return NextResponse.json(apiResponse.body, { headers: apiResponse.headers })
|
||||
} catch (error: unknown) {
|
||||
if (error instanceof WorkflowLockedError) {
|
||||
return NextResponse.json({ error: error.message }, { status: error.status })
|
||||
}
|
||||
const message = getErrorMessage(error, 'Unknown error')
|
||||
logger.error(`[${requestId}] Workflow rollback error`, { error: message })
|
||||
return NextResponse.json({ error: 'Internal server error' }, { status: 500 })
|
||||
}
|
||||
}
|
||||
)
|
||||
@@ -0,0 +1,100 @@
|
||||
import { db } from '@sim/db'
|
||||
import { workflowBlocks } from '@sim/db/schema'
|
||||
import { createLogger } from '@sim/logger'
|
||||
import { getActiveWorkflowRecord } from '@sim/platform-authz/workflow'
|
||||
import { getErrorMessage } from '@sim/utils/errors'
|
||||
import { generateId } from '@sim/utils/id'
|
||||
import { eq } from 'drizzle-orm'
|
||||
import { type NextRequest, NextResponse } from 'next/server'
|
||||
import { v1GetWorkflowContract } from '@/lib/api/contracts/v1/workflows'
|
||||
import { parseRequest } from '@/lib/api/server'
|
||||
import { withRouteHandler } from '@/lib/core/utils/with-route-handler'
|
||||
import { extractInputFieldsFromBlocks } from '@/lib/workflows/input-format'
|
||||
import { createApiResponse, getUserLimits } from '@/app/api/v1/logs/meta'
|
||||
import {
|
||||
checkRateLimit,
|
||||
createRateLimitResponse,
|
||||
validateWorkspaceAccess,
|
||||
} from '@/app/api/v1/middleware'
|
||||
|
||||
const logger = createLogger('V1WorkflowDetailsAPI')
|
||||
|
||||
export const revalidate = 0
|
||||
|
||||
export const GET = withRouteHandler(
|
||||
async (request: NextRequest, context: { params: Promise<{ id: string }> }) => {
|
||||
const requestId = generateId().slice(0, 8)
|
||||
|
||||
try {
|
||||
const rateLimit = await checkRateLimit(request, 'workflow-detail')
|
||||
if (!rateLimit.allowed) {
|
||||
return createRateLimitResponse(rateLimit)
|
||||
}
|
||||
|
||||
const userId = rateLimit.userId!
|
||||
const parsed = await parseRequest(v1GetWorkflowContract, request, context, {
|
||||
validationErrorResponse: () =>
|
||||
NextResponse.json({ error: 'Invalid workflow ID' }, { status: 400 }),
|
||||
})
|
||||
if (!parsed.success) return parsed.response
|
||||
|
||||
const { id } = parsed.data.params
|
||||
|
||||
logger.info(`[${requestId}] Fetching workflow details for ${id}`, { userId })
|
||||
|
||||
const workflowData = await getActiveWorkflowRecord(id)
|
||||
if (!workflowData) {
|
||||
return NextResponse.json({ error: 'Workflow not found' }, { status: 404 })
|
||||
}
|
||||
|
||||
const accessError = await validateWorkspaceAccess(
|
||||
rateLimit,
|
||||
userId,
|
||||
workflowData.workspaceId!
|
||||
)
|
||||
if (accessError) {
|
||||
return NextResponse.json({ error: 'Workflow not found' }, { status: 404 })
|
||||
}
|
||||
|
||||
const blockRows = await db
|
||||
.select({
|
||||
id: workflowBlocks.id,
|
||||
type: workflowBlocks.type,
|
||||
subBlocks: workflowBlocks.subBlocks,
|
||||
})
|
||||
.from(workflowBlocks)
|
||||
.where(eq(workflowBlocks.workflowId, id))
|
||||
|
||||
const blocksRecord = Object.fromEntries(
|
||||
blockRows.map((block) => [block.id, { type: block.type, subBlocks: block.subBlocks }])
|
||||
)
|
||||
const inputs = extractInputFieldsFromBlocks(blocksRecord)
|
||||
|
||||
const response = {
|
||||
id: workflowData.id,
|
||||
name: workflowData.name,
|
||||
description: workflowData.description,
|
||||
folderId: workflowData.folderId,
|
||||
workspaceId: workflowData.workspaceId,
|
||||
isDeployed: workflowData.isDeployed,
|
||||
deployedAt: workflowData.deployedAt?.toISOString() || null,
|
||||
runCount: workflowData.runCount,
|
||||
lastRunAt: workflowData.lastRunAt?.toISOString() || null,
|
||||
variables: workflowData.variables || {},
|
||||
inputs,
|
||||
createdAt: workflowData.createdAt.toISOString(),
|
||||
updatedAt: workflowData.updatedAt.toISOString(),
|
||||
}
|
||||
|
||||
const limits = await getUserLimits(userId)
|
||||
|
||||
const apiResponse = createApiResponse({ data: response }, limits, rateLimit)
|
||||
|
||||
return NextResponse.json(apiResponse.body, { headers: apiResponse.headers })
|
||||
} catch (error: unknown) {
|
||||
const message = getErrorMessage(error, 'Unknown error')
|
||||
logger.error(`[${requestId}] Workflow details fetch error`, { error: message })
|
||||
return NextResponse.json({ error: 'Internal server error' }, { status: 500 })
|
||||
}
|
||||
}
|
||||
)
|
||||
@@ -0,0 +1,178 @@
|
||||
import { db } from '@sim/db'
|
||||
import { workflow } from '@sim/db/schema'
|
||||
import { createLogger } from '@sim/logger'
|
||||
import { getErrorMessage } from '@sim/utils/errors'
|
||||
import { generateId } from '@sim/utils/id'
|
||||
import { and, asc, eq, gt, isNull, or } from 'drizzle-orm'
|
||||
import { type NextRequest, NextResponse } from 'next/server'
|
||||
import { v1ListWorkflowsContract } from '@/lib/api/contracts/v1/workflows'
|
||||
import { getValidationErrorMessage, parseRequest } from '@/lib/api/server'
|
||||
import { withRouteHandler } from '@/lib/core/utils/with-route-handler'
|
||||
import { createApiResponse, getUserLimits } from '@/app/api/v1/logs/meta'
|
||||
import {
|
||||
checkRateLimit,
|
||||
createRateLimitResponse,
|
||||
validateWorkspaceAccess,
|
||||
} from '@/app/api/v1/middleware'
|
||||
|
||||
const logger = createLogger('V1WorkflowsAPI')
|
||||
|
||||
export const dynamic = 'force-dynamic'
|
||||
export const revalidate = 0
|
||||
|
||||
interface CursorData {
|
||||
sortOrder: number
|
||||
createdAt: string
|
||||
id: string
|
||||
}
|
||||
|
||||
function encodeCursor(data: CursorData): string {
|
||||
return Buffer.from(JSON.stringify(data)).toString('base64')
|
||||
}
|
||||
|
||||
function decodeCursor(cursor: string): CursorData | null {
|
||||
try {
|
||||
return JSON.parse(Buffer.from(cursor, 'base64').toString())
|
||||
} catch {
|
||||
return null
|
||||
}
|
||||
}
|
||||
|
||||
export const GET = withRouteHandler(async (request: NextRequest) => {
|
||||
const requestId = generateId().slice(0, 8)
|
||||
|
||||
try {
|
||||
const rateLimit = await checkRateLimit(request, 'workflows')
|
||||
if (!rateLimit.allowed) {
|
||||
return createRateLimitResponse(rateLimit)
|
||||
}
|
||||
|
||||
const userId = rateLimit.userId!
|
||||
const parsed = await parseRequest(
|
||||
v1ListWorkflowsContract,
|
||||
request,
|
||||
{},
|
||||
{
|
||||
validationErrorResponse: (error) =>
|
||||
NextResponse.json(
|
||||
{
|
||||
error: getValidationErrorMessage(error, 'Invalid parameters'),
|
||||
details: error.issues,
|
||||
},
|
||||
{ status: 400 }
|
||||
),
|
||||
}
|
||||
)
|
||||
if (!parsed.success) return parsed.response
|
||||
|
||||
const params = parsed.data.query
|
||||
|
||||
logger.info(`[${requestId}] Fetching workflows for workspace ${params.workspaceId}`, {
|
||||
userId,
|
||||
filters: {
|
||||
folderId: params.folderId,
|
||||
deployedOnly: params.deployedOnly,
|
||||
},
|
||||
})
|
||||
|
||||
const accessError = await validateWorkspaceAccess(rateLimit, userId, params.workspaceId)
|
||||
if (accessError) return accessError
|
||||
|
||||
const conditions = [eq(workflow.workspaceId, params.workspaceId), isNull(workflow.archivedAt)]
|
||||
|
||||
if (params.folderId) {
|
||||
conditions.push(eq(workflow.folderId, params.folderId))
|
||||
}
|
||||
|
||||
if (params.deployedOnly) {
|
||||
conditions.push(eq(workflow.isDeployed, true))
|
||||
}
|
||||
|
||||
if (params.cursor) {
|
||||
const cursorData = decodeCursor(params.cursor)
|
||||
if (cursorData) {
|
||||
const cursorCondition = or(
|
||||
gt(workflow.sortOrder, cursorData.sortOrder),
|
||||
and(
|
||||
eq(workflow.sortOrder, cursorData.sortOrder),
|
||||
gt(workflow.createdAt, new Date(cursorData.createdAt))
|
||||
),
|
||||
and(
|
||||
eq(workflow.sortOrder, cursorData.sortOrder),
|
||||
eq(workflow.createdAt, new Date(cursorData.createdAt)),
|
||||
gt(workflow.id, cursorData.id)
|
||||
)
|
||||
)
|
||||
if (cursorCondition) {
|
||||
conditions.push(cursorCondition)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const orderByClause = [asc(workflow.sortOrder), asc(workflow.createdAt), asc(workflow.id)]
|
||||
|
||||
const rows = await db
|
||||
.select({
|
||||
id: workflow.id,
|
||||
name: workflow.name,
|
||||
description: workflow.description,
|
||||
folderId: workflow.folderId,
|
||||
workspaceId: workflow.workspaceId,
|
||||
isDeployed: workflow.isDeployed,
|
||||
deployedAt: workflow.deployedAt,
|
||||
runCount: workflow.runCount,
|
||||
lastRunAt: workflow.lastRunAt,
|
||||
sortOrder: workflow.sortOrder,
|
||||
createdAt: workflow.createdAt,
|
||||
updatedAt: workflow.updatedAt,
|
||||
})
|
||||
.from(workflow)
|
||||
.where(and(...conditions))
|
||||
.orderBy(...orderByClause)
|
||||
.limit(params.limit + 1)
|
||||
|
||||
const hasMore = rows.length > params.limit
|
||||
const data = rows.slice(0, params.limit)
|
||||
|
||||
let nextCursor: string | undefined
|
||||
if (hasMore && data.length > 0) {
|
||||
const lastWorkflow = data[data.length - 1]
|
||||
nextCursor = encodeCursor({
|
||||
sortOrder: lastWorkflow.sortOrder,
|
||||
createdAt: lastWorkflow.createdAt.toISOString(),
|
||||
id: lastWorkflow.id,
|
||||
})
|
||||
}
|
||||
|
||||
const formattedWorkflows = data.map((w) => ({
|
||||
id: w.id,
|
||||
name: w.name,
|
||||
description: w.description,
|
||||
folderId: w.folderId,
|
||||
workspaceId: w.workspaceId,
|
||||
isDeployed: w.isDeployed,
|
||||
deployedAt: w.deployedAt?.toISOString() || null,
|
||||
runCount: w.runCount,
|
||||
lastRunAt: w.lastRunAt?.toISOString() || null,
|
||||
createdAt: w.createdAt.toISOString(),
|
||||
updatedAt: w.updatedAt.toISOString(),
|
||||
}))
|
||||
|
||||
const limits = await getUserLimits(userId)
|
||||
|
||||
const response = createApiResponse(
|
||||
{
|
||||
data: formattedWorkflows,
|
||||
nextCursor,
|
||||
},
|
||||
limits,
|
||||
rateLimit
|
||||
)
|
||||
|
||||
return NextResponse.json(response.body, { headers: response.headers })
|
||||
} catch (error: unknown) {
|
||||
const message = getErrorMessage(error, 'Unknown error')
|
||||
logger.error(`[${requestId}] Workflows fetch error`, { error: message })
|
||||
return NextResponse.json({ error: 'Internal server error' }, { status: 500 })
|
||||
}
|
||||
})
|
||||
@@ -0,0 +1,39 @@
|
||||
import { type ActiveWorkflowRecord, getActiveWorkflowRecord } from '@sim/platform-authz/workflow'
|
||||
import { NextResponse } from 'next/server'
|
||||
import { type RateLimitResult, validateWorkspaceAccess } from '@/app/api/v1/middleware'
|
||||
|
||||
function workflowNotFoundResponse(): NextResponse {
|
||||
return NextResponse.json({ error: 'Workflow not found' }, { status: 404 })
|
||||
}
|
||||
|
||||
/**
|
||||
* Resolves the target workflow for a v1 deployment mutation: loads the active
|
||||
* record and verifies the caller's admin permission on its workspace. Access
|
||||
* failures are masked as 404, matching the v1 workflow read surface so
|
||||
* unauthorized callers cannot probe workflow existence.
|
||||
*/
|
||||
export async function resolveV1DeploymentWorkflow(
|
||||
rateLimit: RateLimitResult,
|
||||
userId: string,
|
||||
workflowId: string
|
||||
): Promise<
|
||||
| { ok: true; workflow: ActiveWorkflowRecord; workspaceId: string }
|
||||
| { ok: false; response: NextResponse }
|
||||
> {
|
||||
const workflow = await getActiveWorkflowRecord(workflowId)
|
||||
if (!workflow?.workspaceId) {
|
||||
return { ok: false, response: workflowNotFoundResponse() }
|
||||
}
|
||||
|
||||
const accessError = await validateWorkspaceAccess(
|
||||
rateLimit,
|
||||
userId,
|
||||
workflow.workspaceId,
|
||||
'admin'
|
||||
)
|
||||
if (accessError) {
|
||||
return { ok: false, response: workflowNotFoundResponse() }
|
||||
}
|
||||
|
||||
return { ok: true, workflow, workspaceId: workflow.workspaceId }
|
||||
}
|
||||
Reference in New Issue
Block a user