chore: import upstream snapshot with attribution
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) Has been cancelled
Publish Python SDK / publish-pypi (push) Has been cancelled
Publish TypeScript SDK / publish-npm (push) Has been cancelled
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) Has been cancelled
Publish Python SDK / publish-pypi (push) Has been cancelled
Publish TypeScript SDK / publish-npm (push) Has been cancelled
This commit is contained in:
@@ -0,0 +1,195 @@
|
||||
import { createLogger } from '@sim/logger'
|
||||
import { generateId } from '@sim/utils/id'
|
||||
import { type NextRequest, NextResponse } from 'next/server'
|
||||
import { updateKnowledgeChunkContract } from '@/lib/api/contracts/knowledge'
|
||||
import { parseRequest } from '@/lib/api/server'
|
||||
import { getSession } from '@/lib/auth'
|
||||
import { withRouteHandler } from '@/lib/core/utils/with-route-handler'
|
||||
import { deleteChunk, updateChunk } from '@/lib/knowledge/chunks/service'
|
||||
import { checkChunkAccess, checkChunkWriteAccess } from '@/app/api/knowledge/utils'
|
||||
|
||||
const logger = createLogger('ChunkByIdAPI')
|
||||
|
||||
export const GET = withRouteHandler(
|
||||
async (
|
||||
req: NextRequest,
|
||||
{ params }: { params: Promise<{ id: string; documentId: string; chunkId: string }> }
|
||||
) => {
|
||||
const requestId = generateId().slice(0, 8)
|
||||
const { id: knowledgeBaseId, documentId, chunkId } = await params
|
||||
|
||||
try {
|
||||
const session = await getSession()
|
||||
if (!session?.user?.id) {
|
||||
logger.warn(`[${requestId}] Unauthorized chunk access attempt`)
|
||||
return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })
|
||||
}
|
||||
|
||||
const accessCheck = await checkChunkAccess(
|
||||
knowledgeBaseId,
|
||||
documentId,
|
||||
chunkId,
|
||||
session.user.id
|
||||
)
|
||||
|
||||
if (!accessCheck.hasAccess) {
|
||||
if (accessCheck.notFound) {
|
||||
logger.warn(
|
||||
`[${requestId}] ${accessCheck.reason}: KB=${knowledgeBaseId}, Doc=${documentId}, Chunk=${chunkId}`
|
||||
)
|
||||
return NextResponse.json({ error: accessCheck.reason }, { status: 404 })
|
||||
}
|
||||
logger.warn(
|
||||
`[${requestId}] User ${session.user.id} attempted unauthorized chunk access: ${accessCheck.reason}`
|
||||
)
|
||||
return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })
|
||||
}
|
||||
|
||||
logger.info(
|
||||
`[${requestId}] Retrieved chunk: ${chunkId} from document ${documentId} in knowledge base ${knowledgeBaseId}`
|
||||
)
|
||||
|
||||
return NextResponse.json({
|
||||
success: true,
|
||||
data: accessCheck.chunk,
|
||||
})
|
||||
} catch (error) {
|
||||
logger.error(`[${requestId}] Error fetching chunk`, error)
|
||||
return NextResponse.json({ error: 'Failed to fetch chunk' }, { status: 500 })
|
||||
}
|
||||
}
|
||||
)
|
||||
|
||||
export const PUT = withRouteHandler(
|
||||
async (
|
||||
req: NextRequest,
|
||||
context: { params: Promise<{ id: string; documentId: string; chunkId: string }> }
|
||||
) => {
|
||||
const requestId = generateId().slice(0, 8)
|
||||
const { id: knowledgeBaseId, documentId, chunkId } = await context.params
|
||||
|
||||
try {
|
||||
const session = await getSession()
|
||||
if (!session?.user?.id) {
|
||||
logger.warn(`[${requestId}] Unauthorized chunk update attempt`)
|
||||
return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })
|
||||
}
|
||||
|
||||
const accessCheck = await checkChunkWriteAccess(
|
||||
knowledgeBaseId,
|
||||
documentId,
|
||||
chunkId,
|
||||
session.user.id
|
||||
)
|
||||
|
||||
if (!accessCheck.hasAccess) {
|
||||
if (accessCheck.notFound) {
|
||||
logger.warn(
|
||||
`[${requestId}] ${accessCheck.reason}: KB=${knowledgeBaseId}, Doc=${documentId}, Chunk=${chunkId}`
|
||||
)
|
||||
return NextResponse.json({ error: accessCheck.reason }, { status: 404 })
|
||||
}
|
||||
logger.warn(
|
||||
`[${requestId}] User ${session.user.id} attempted unauthorized chunk update: ${accessCheck.reason}`
|
||||
)
|
||||
return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })
|
||||
}
|
||||
|
||||
if (accessCheck.document?.connectorId) {
|
||||
logger.warn(
|
||||
`[${requestId}] User ${session.user.id} attempted to update chunk on connector-synced document: Doc=${documentId}`
|
||||
)
|
||||
return NextResponse.json(
|
||||
{ error: 'Chunks from connector-synced documents are read-only' },
|
||||
{ status: 403 }
|
||||
)
|
||||
}
|
||||
|
||||
const parsed = await parseRequest(updateKnowledgeChunkContract, req, context)
|
||||
if (!parsed.success) return parsed.response
|
||||
|
||||
const validatedData = parsed.data.body
|
||||
|
||||
const updatedChunk = await updateChunk(
|
||||
chunkId,
|
||||
validatedData,
|
||||
requestId,
|
||||
accessCheck.knowledgeBase?.workspaceId
|
||||
)
|
||||
|
||||
logger.info(
|
||||
`[${requestId}] Chunk updated: ${chunkId} in document ${documentId} in knowledge base ${knowledgeBaseId}`
|
||||
)
|
||||
|
||||
return NextResponse.json({
|
||||
success: true,
|
||||
data: updatedChunk,
|
||||
})
|
||||
} catch (error) {
|
||||
logger.error(`[${requestId}] Error updating chunk`, error)
|
||||
return NextResponse.json({ error: 'Failed to update chunk' }, { status: 500 })
|
||||
}
|
||||
}
|
||||
)
|
||||
|
||||
export const DELETE = withRouteHandler(
|
||||
async (
|
||||
req: NextRequest,
|
||||
{ params }: { params: Promise<{ id: string; documentId: string; chunkId: string }> }
|
||||
) => {
|
||||
const requestId = generateId().slice(0, 8)
|
||||
const { id: knowledgeBaseId, documentId, chunkId } = await params
|
||||
|
||||
try {
|
||||
const session = await getSession()
|
||||
if (!session?.user?.id) {
|
||||
logger.warn(`[${requestId}] Unauthorized chunk delete attempt`)
|
||||
return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })
|
||||
}
|
||||
|
||||
const accessCheck = await checkChunkWriteAccess(
|
||||
knowledgeBaseId,
|
||||
documentId,
|
||||
chunkId,
|
||||
session.user.id
|
||||
)
|
||||
|
||||
if (!accessCheck.hasAccess) {
|
||||
if (accessCheck.notFound) {
|
||||
logger.warn(
|
||||
`[${requestId}] ${accessCheck.reason}: KB=${knowledgeBaseId}, Doc=${documentId}, Chunk=${chunkId}`
|
||||
)
|
||||
return NextResponse.json({ error: accessCheck.reason }, { status: 404 })
|
||||
}
|
||||
logger.warn(
|
||||
`[${requestId}] User ${session.user.id} attempted unauthorized chunk deletion: ${accessCheck.reason}`
|
||||
)
|
||||
return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })
|
||||
}
|
||||
|
||||
if (accessCheck.document?.connectorId) {
|
||||
logger.warn(
|
||||
`[${requestId}] User ${session.user.id} attempted to delete chunk on connector-synced document: Doc=${documentId}`
|
||||
)
|
||||
return NextResponse.json(
|
||||
{ error: 'Chunks from connector-synced documents are read-only' },
|
||||
{ status: 403 }
|
||||
)
|
||||
}
|
||||
|
||||
await deleteChunk(chunkId, documentId, requestId)
|
||||
|
||||
logger.info(
|
||||
`[${requestId}] Chunk deleted: ${chunkId} from document ${documentId} in knowledge base ${knowledgeBaseId}`
|
||||
)
|
||||
|
||||
return NextResponse.json({
|
||||
success: true,
|
||||
data: { message: 'Chunk deleted successfully' },
|
||||
})
|
||||
} catch (error) {
|
||||
logger.error(`[${requestId}] Error deleting chunk`, error)
|
||||
return NextResponse.json({ error: 'Failed to delete chunk' }, { status: 500 })
|
||||
}
|
||||
}
|
||||
)
|
||||
@@ -0,0 +1,334 @@
|
||||
import { createLogger } from '@sim/logger'
|
||||
import { authorizeWorkflowByWorkspacePermission } from '@sim/platform-authz/workflow'
|
||||
import { getErrorMessage } from '@sim/utils/errors'
|
||||
import { type NextRequest, NextResponse } from 'next/server'
|
||||
import {
|
||||
bulkKnowledgeChunksContract,
|
||||
createChunkBodySchema,
|
||||
listKnowledgeChunksQuerySchema,
|
||||
} from '@/lib/api/contracts/knowledge'
|
||||
import { isZodError, parseJsonBody, parseRequest } from '@/lib/api/server'
|
||||
import { checkSessionOrInternalAuth } from '@/lib/auth/hybrid'
|
||||
import { generateRequestId } from '@/lib/core/utils/request'
|
||||
import { withRouteHandler } from '@/lib/core/utils/with-route-handler'
|
||||
import { batchChunkOperation, createChunk, queryChunks } from '@/lib/knowledge/chunks/service'
|
||||
import { checkDocumentAccess, checkDocumentWriteAccess } from '@/app/api/knowledge/utils'
|
||||
import { calculateCost } from '@/providers/utils'
|
||||
|
||||
const logger = createLogger('DocumentChunksAPI')
|
||||
|
||||
export const GET = withRouteHandler(
|
||||
async (req: NextRequest, { params }: { params: Promise<{ id: string; documentId: string }> }) => {
|
||||
const requestId = generateRequestId()
|
||||
const { id: knowledgeBaseId, documentId } = await params
|
||||
|
||||
try {
|
||||
const auth = await checkSessionOrInternalAuth(req, { requireWorkflowId: false })
|
||||
if (!auth.success || !auth.userId) {
|
||||
logger.warn(`[${requestId}] Unauthorized chunks access attempt`)
|
||||
return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })
|
||||
}
|
||||
const userId = auth.userId
|
||||
|
||||
const accessCheck = await checkDocumentAccess(knowledgeBaseId, documentId, userId)
|
||||
|
||||
if (!accessCheck.hasAccess) {
|
||||
if (accessCheck.notFound) {
|
||||
logger.warn(
|
||||
`[${requestId}] ${accessCheck.reason}: KB=${knowledgeBaseId}, Doc=${documentId}`
|
||||
)
|
||||
return NextResponse.json({ error: accessCheck.reason }, { status: 404 })
|
||||
}
|
||||
logger.warn(
|
||||
`[${requestId}] User ${userId} attempted unauthorized chunks access: ${accessCheck.reason}`
|
||||
)
|
||||
return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })
|
||||
}
|
||||
|
||||
const doc = accessCheck.document
|
||||
if (!doc) {
|
||||
logger.warn(
|
||||
`[${requestId}] Document data not available: KB=${knowledgeBaseId}, Doc=${documentId}`
|
||||
)
|
||||
return NextResponse.json({ error: 'Document not found' }, { status: 404 })
|
||||
}
|
||||
|
||||
if (doc.processingStatus !== 'completed') {
|
||||
logger.warn(
|
||||
`[${requestId}] Document ${documentId} is not ready for chunk access (status: ${doc.processingStatus})`
|
||||
)
|
||||
return NextResponse.json(
|
||||
{
|
||||
error: 'Document is not ready for access',
|
||||
details: `Document status: ${doc.processingStatus}`,
|
||||
retryAfter: doc.processingStatus === 'processing' ? 5 : null,
|
||||
},
|
||||
{ status: 400 }
|
||||
)
|
||||
}
|
||||
|
||||
const { searchParams } = new URL(req.url)
|
||||
const queryResult = listKnowledgeChunksQuerySchema.safeParse({
|
||||
search: searchParams.get('search') || undefined,
|
||||
enabled: searchParams.get('enabled') || undefined,
|
||||
limit: searchParams.get('limit') || undefined,
|
||||
offset: searchParams.get('offset') || undefined,
|
||||
sortBy: searchParams.get('sortBy') || undefined,
|
||||
sortOrder: searchParams.get('sortOrder') || undefined,
|
||||
})
|
||||
if (!queryResult.success) {
|
||||
return NextResponse.json(
|
||||
{ error: 'Invalid query parameters', details: queryResult.error.issues },
|
||||
{ status: 400 }
|
||||
)
|
||||
}
|
||||
|
||||
const result = await queryChunks(documentId, queryResult.data, requestId)
|
||||
|
||||
return NextResponse.json({
|
||||
success: true,
|
||||
data: result.chunks,
|
||||
pagination: result.pagination,
|
||||
})
|
||||
} catch (error) {
|
||||
logger.error(`[${requestId}] Error fetching chunks`, error)
|
||||
return NextResponse.json({ error: 'Failed to fetch chunks' }, { status: 500 })
|
||||
}
|
||||
}
|
||||
)
|
||||
|
||||
export const POST = withRouteHandler(
|
||||
async (req: NextRequest, { params }: { params: Promise<{ id: string; documentId: string }> }) => {
|
||||
const requestId = generateRequestId()
|
||||
const { id: knowledgeBaseId, documentId } = await params
|
||||
|
||||
try {
|
||||
const auth = await checkSessionOrInternalAuth(req, { requireWorkflowId: false })
|
||||
if (!auth.success || !auth.userId) {
|
||||
logger.warn(`[${requestId}] Authentication failed: ${auth.error || 'Unauthorized'}`)
|
||||
return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })
|
||||
}
|
||||
const userId = auth.userId
|
||||
|
||||
const parsedBody = await parseJsonBody(req)
|
||||
if (!parsedBody.success) return parsedBody.response
|
||||
const { workflowId, ...searchParams } = parsedBody.data as Record<string, unknown>
|
||||
|
||||
if (workflowId) {
|
||||
if (typeof workflowId !== 'string') {
|
||||
return NextResponse.json({ error: 'workflowId must be a string' }, { status: 400 })
|
||||
}
|
||||
const authorization = await authorizeWorkflowByWorkspacePermission({
|
||||
workflowId,
|
||||
userId,
|
||||
action: 'write',
|
||||
})
|
||||
if (!authorization.allowed) {
|
||||
return NextResponse.json(
|
||||
{ error: authorization.message || 'Access denied' },
|
||||
{ status: authorization.status }
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
const accessCheck = await checkDocumentWriteAccess(knowledgeBaseId, documentId, userId)
|
||||
|
||||
if (!accessCheck.hasAccess) {
|
||||
if (accessCheck.notFound) {
|
||||
logger.warn(
|
||||
`[${requestId}] ${accessCheck.reason}: KB=${knowledgeBaseId}, Doc=${documentId}`
|
||||
)
|
||||
return NextResponse.json({ error: accessCheck.reason }, { status: 404 })
|
||||
}
|
||||
logger.warn(
|
||||
`[${requestId}] User ${userId} attempted unauthorized chunk creation: ${accessCheck.reason}`
|
||||
)
|
||||
return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })
|
||||
}
|
||||
|
||||
const doc = accessCheck.document
|
||||
if (!doc) {
|
||||
logger.warn(
|
||||
`[${requestId}] Document data not available: KB=${knowledgeBaseId}, Doc=${documentId}`
|
||||
)
|
||||
return NextResponse.json({ error: 'Document not found' }, { status: 404 })
|
||||
}
|
||||
|
||||
if (doc.connectorId) {
|
||||
logger.warn(
|
||||
`[${requestId}] User ${userId} attempted to create chunk on connector-synced document: Doc=${documentId}`
|
||||
)
|
||||
return NextResponse.json(
|
||||
{ error: 'Chunks from connector-synced documents are read-only' },
|
||||
{ status: 403 }
|
||||
)
|
||||
}
|
||||
|
||||
if (doc.processingStatus === 'failed') {
|
||||
logger.warn(`[${requestId}] Document ${documentId} is in failed state, cannot add chunks`)
|
||||
return NextResponse.json({ error: 'Cannot add chunks to failed document' }, { status: 400 })
|
||||
}
|
||||
|
||||
try {
|
||||
const validatedData = createChunkBodySchema.parse(searchParams)
|
||||
|
||||
const docTags = {
|
||||
tag1: doc.tag1 ?? null,
|
||||
tag2: doc.tag2 ?? null,
|
||||
tag3: doc.tag3 ?? null,
|
||||
tag4: doc.tag4 ?? null,
|
||||
tag5: doc.tag5 ?? null,
|
||||
tag6: doc.tag6 ?? null,
|
||||
tag7: doc.tag7 ?? null,
|
||||
number1: doc.number1 ?? null,
|
||||
number2: doc.number2 ?? null,
|
||||
number3: doc.number3 ?? null,
|
||||
number4: doc.number4 ?? null,
|
||||
number5: doc.number5 ?? null,
|
||||
date1: doc.date1 ?? null,
|
||||
date2: doc.date2 ?? null,
|
||||
boolean1: doc.boolean1 ?? null,
|
||||
boolean2: doc.boolean2 ?? null,
|
||||
boolean3: doc.boolean3 ?? null,
|
||||
}
|
||||
|
||||
const newChunk = await createChunk(
|
||||
knowledgeBaseId,
|
||||
documentId,
|
||||
docTags,
|
||||
validatedData,
|
||||
requestId,
|
||||
accessCheck.knowledgeBase?.workspaceId
|
||||
)
|
||||
|
||||
let cost = null
|
||||
try {
|
||||
cost = calculateCost(
|
||||
accessCheck.knowledgeBase.embeddingModel,
|
||||
newChunk.tokenCount,
|
||||
0,
|
||||
false
|
||||
)
|
||||
} catch (error) {
|
||||
logger.warn(`[${requestId}] Failed to calculate cost for chunk upload`, {
|
||||
error: getErrorMessage(error, 'Unknown error'),
|
||||
})
|
||||
}
|
||||
|
||||
return NextResponse.json({
|
||||
success: true,
|
||||
data: {
|
||||
...newChunk,
|
||||
documentId,
|
||||
documentName: doc.filename,
|
||||
...(cost
|
||||
? {
|
||||
cost: {
|
||||
input: cost.input,
|
||||
output: cost.output,
|
||||
total: cost.total,
|
||||
tokens: {
|
||||
prompt: newChunk.tokenCount,
|
||||
completion: 0,
|
||||
total: newChunk.tokenCount,
|
||||
},
|
||||
model: accessCheck.knowledgeBase.embeddingModel,
|
||||
pricing: cost.pricing,
|
||||
},
|
||||
}
|
||||
: {}),
|
||||
},
|
||||
})
|
||||
} catch (validationError) {
|
||||
if (isZodError(validationError)) {
|
||||
logger.warn(`[${requestId}] Invalid chunk creation data`, {
|
||||
errors: validationError.issues,
|
||||
})
|
||||
return NextResponse.json(
|
||||
{ error: 'Invalid request data', details: validationError.issues },
|
||||
{ status: 400 }
|
||||
)
|
||||
}
|
||||
throw validationError
|
||||
}
|
||||
} catch (error) {
|
||||
logger.error(`[${requestId}] Error creating chunk`, error)
|
||||
return NextResponse.json({ error: 'Failed to create chunk' }, { status: 500 })
|
||||
}
|
||||
}
|
||||
)
|
||||
|
||||
export const PATCH = withRouteHandler(
|
||||
async (req: NextRequest, { params }: { params: Promise<{ id: string; documentId: string }> }) => {
|
||||
const requestId = generateRequestId()
|
||||
const { id: knowledgeBaseId, documentId } = await params
|
||||
|
||||
try {
|
||||
const auth = await checkSessionOrInternalAuth(req, { requireWorkflowId: false })
|
||||
if (!auth.success || !auth.userId) {
|
||||
logger.warn(`[${requestId}] Unauthorized batch chunk operation attempt`)
|
||||
return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })
|
||||
}
|
||||
const userId = auth.userId
|
||||
|
||||
const accessCheck = await checkDocumentWriteAccess(knowledgeBaseId, documentId, userId)
|
||||
|
||||
if (!accessCheck.hasAccess) {
|
||||
if (accessCheck.notFound) {
|
||||
logger.warn(
|
||||
`[${requestId}] ${accessCheck.reason}: KB=${knowledgeBaseId}, Doc=${documentId}`
|
||||
)
|
||||
return NextResponse.json({ error: accessCheck.reason }, { status: 404 })
|
||||
}
|
||||
logger.warn(
|
||||
`[${requestId}] User ${userId} attempted unauthorized batch chunk operation: ${accessCheck.reason}`
|
||||
)
|
||||
return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })
|
||||
}
|
||||
|
||||
if (accessCheck.document?.connectorId) {
|
||||
logger.warn(
|
||||
`[${requestId}] User ${userId} attempted batch chunk operation on connector-synced document: Doc=${documentId}`
|
||||
)
|
||||
return NextResponse.json(
|
||||
{ error: 'Chunks from connector-synced documents are read-only' },
|
||||
{ status: 403 }
|
||||
)
|
||||
}
|
||||
|
||||
const parsed = await parseRequest(
|
||||
bulkKnowledgeChunksContract,
|
||||
req,
|
||||
{ params },
|
||||
{
|
||||
validationErrorResponse: (error) => {
|
||||
logger.warn(`[${requestId}] Invalid batch operation data`, { errors: error.issues })
|
||||
return NextResponse.json(
|
||||
{ error: 'Invalid request data', details: error.issues },
|
||||
{ status: 400 }
|
||||
)
|
||||
},
|
||||
}
|
||||
)
|
||||
if (!parsed.success) return parsed.response
|
||||
const validatedData = parsed.data.body
|
||||
const { operation, chunkIds } = validatedData
|
||||
|
||||
const result = await batchChunkOperation(documentId, operation, chunkIds, requestId)
|
||||
|
||||
return NextResponse.json({
|
||||
success: true,
|
||||
data: {
|
||||
operation,
|
||||
successCount: result.processed,
|
||||
errorCount: result.errors.length,
|
||||
processed: result.processed,
|
||||
errors: result.errors,
|
||||
},
|
||||
})
|
||||
} catch (error) {
|
||||
logger.error(`[${requestId}] Error in batch chunk operation`, error)
|
||||
return NextResponse.json({ error: 'Failed to perform batch operation' }, { status: 500 })
|
||||
}
|
||||
}
|
||||
)
|
||||
@@ -0,0 +1,560 @@
|
||||
/**
|
||||
* Tests for document by ID API route
|
||||
*
|
||||
* @vitest-environment node
|
||||
*/
|
||||
import { auditMock, authMockFns, createMockRequest, knowledgeApiUtilsMock } from '@sim/testing'
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
|
||||
const { mockDbChain } = vi.hoisted(() => {
|
||||
const mockDbChain = {
|
||||
select: vi.fn().mockReturnThis(),
|
||||
from: vi.fn().mockReturnThis(),
|
||||
where: vi.fn().mockReturnThis(),
|
||||
limit: vi.fn().mockReturnThis(),
|
||||
update: vi.fn().mockReturnThis(),
|
||||
set: vi.fn().mockReturnThis(),
|
||||
delete: vi.fn().mockReturnThis(),
|
||||
transaction: vi.fn(),
|
||||
}
|
||||
return { mockDbChain }
|
||||
})
|
||||
|
||||
vi.mock('@sim/db', () => ({
|
||||
db: mockDbChain,
|
||||
}))
|
||||
|
||||
vi.mock('@/app/api/knowledge/utils', () => knowledgeApiUtilsMock)
|
||||
|
||||
vi.mock('@/lib/knowledge/documents/service', () => ({
|
||||
updateDocument: vi.fn(),
|
||||
deleteDocument: vi.fn(),
|
||||
markDocumentAsFailedTimeout: vi.fn(),
|
||||
retryDocumentProcessing: vi.fn(),
|
||||
processDocumentAsync: vi.fn(),
|
||||
}))
|
||||
|
||||
vi.mock('@sim/audit', () => auditMock)
|
||||
|
||||
import {
|
||||
deleteDocument,
|
||||
markDocumentAsFailedTimeout,
|
||||
retryDocumentProcessing,
|
||||
updateDocument,
|
||||
} from '@/lib/knowledge/documents/service'
|
||||
import { DELETE, GET, PUT } from '@/app/api/knowledge/[id]/documents/[documentId]/route'
|
||||
import { checkDocumentAccess, checkDocumentWriteAccess } from '@/app/api/knowledge/utils'
|
||||
|
||||
describe('Document By ID API Route', () => {
|
||||
const mockDocument = {
|
||||
id: 'doc-123',
|
||||
knowledgeBaseId: 'kb-123',
|
||||
filename: 'test-document.pdf',
|
||||
fileUrl: 'https://example.com/test-document.pdf',
|
||||
fileSize: 1024,
|
||||
mimeType: 'application/pdf',
|
||||
chunkCount: 5,
|
||||
tokenCount: 100,
|
||||
characterCount: 500,
|
||||
processingStatus: 'completed' as const,
|
||||
processingStartedAt: new Date('2023-01-01T10:00:00Z'),
|
||||
processingCompletedAt: new Date('2023-01-01T10:05:00Z'),
|
||||
processingError: null,
|
||||
enabled: true,
|
||||
uploadedAt: new Date('2023-01-01T09:00:00Z'),
|
||||
tag1: null,
|
||||
tag2: null,
|
||||
tag3: null,
|
||||
tag4: null,
|
||||
tag5: null,
|
||||
tag6: null,
|
||||
tag7: null,
|
||||
number1: null,
|
||||
number2: null,
|
||||
number3: null,
|
||||
number4: null,
|
||||
number5: null,
|
||||
date1: null,
|
||||
date2: null,
|
||||
boolean1: null,
|
||||
boolean2: null,
|
||||
boolean3: null,
|
||||
deletedAt: null,
|
||||
}
|
||||
|
||||
const resetMocks = () => {
|
||||
vi.clearAllMocks()
|
||||
Object.values(mockDbChain).forEach((fn) => {
|
||||
if (typeof fn === 'function') {
|
||||
fn.mockClear().mockReset()
|
||||
if (fn !== mockDbChain.transaction) {
|
||||
fn.mockReturnThis()
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
resetMocks()
|
||||
|
||||
vi.stubGlobal('crypto', {
|
||||
randomUUID: vi.fn().mockReturnValue('mock-uuid-1234-5678'),
|
||||
})
|
||||
})
|
||||
|
||||
afterEach(() => {
|
||||
vi.clearAllMocks()
|
||||
})
|
||||
|
||||
describe('GET /api/knowledge/[id]/documents/[documentId]', () => {
|
||||
const mockParams = Promise.resolve({ id: 'kb-123', documentId: 'doc-123' })
|
||||
|
||||
it('should retrieve document successfully for authenticated user', async () => {
|
||||
authMockFns.mockGetSession.mockResolvedValue({
|
||||
user: { id: 'user-123', email: 'test@example.com' },
|
||||
})
|
||||
vi.mocked(checkDocumentAccess).mockResolvedValue({
|
||||
hasAccess: true,
|
||||
document: mockDocument,
|
||||
knowledgeBase: { id: 'kb-123', userId: 'user-123' },
|
||||
})
|
||||
|
||||
const req = createMockRequest('GET')
|
||||
const response = await GET(req, { params: mockParams })
|
||||
const data = await response.json()
|
||||
|
||||
expect(response.status).toBe(200)
|
||||
expect(data.success).toBe(true)
|
||||
expect(data.data.id).toBe('doc-123')
|
||||
expect(data.data.filename).toBe('test-document.pdf')
|
||||
expect(vi.mocked(checkDocumentAccess)).toHaveBeenCalledWith('kb-123', 'doc-123', 'user-123')
|
||||
})
|
||||
|
||||
it('should return unauthorized for unauthenticated user', async () => {
|
||||
authMockFns.mockGetSession.mockResolvedValue(null)
|
||||
|
||||
const req = createMockRequest('GET')
|
||||
const response = await GET(req, { params: mockParams })
|
||||
const data = await response.json()
|
||||
|
||||
expect(response.status).toBe(401)
|
||||
expect(data.error).toBe('Unauthorized')
|
||||
})
|
||||
|
||||
it('should return not found for non-existent document', async () => {
|
||||
authMockFns.mockGetSession.mockResolvedValue({
|
||||
user: { id: 'user-123', email: 'test@example.com' },
|
||||
})
|
||||
vi.mocked(checkDocumentAccess).mockResolvedValue({
|
||||
hasAccess: false,
|
||||
notFound: true,
|
||||
reason: 'Document not found',
|
||||
})
|
||||
|
||||
const req = createMockRequest('GET')
|
||||
const response = await GET(req, { params: mockParams })
|
||||
const data = await response.json()
|
||||
|
||||
expect(response.status).toBe(404)
|
||||
expect(data.error).toBe('Document not found')
|
||||
})
|
||||
|
||||
it('should return unauthorized for document without access', async () => {
|
||||
authMockFns.mockGetSession.mockResolvedValue({
|
||||
user: { id: 'user-123', email: 'test@example.com' },
|
||||
})
|
||||
vi.mocked(checkDocumentAccess).mockResolvedValue({
|
||||
hasAccess: false,
|
||||
reason: 'Access denied',
|
||||
})
|
||||
|
||||
const req = createMockRequest('GET')
|
||||
const response = await GET(req, { params: mockParams })
|
||||
const data = await response.json()
|
||||
|
||||
expect(response.status).toBe(401)
|
||||
expect(data.error).toBe('Unauthorized')
|
||||
})
|
||||
|
||||
it('should handle database errors', async () => {
|
||||
authMockFns.mockGetSession.mockResolvedValue({
|
||||
user: { id: 'user-123', email: 'test@example.com' },
|
||||
})
|
||||
vi.mocked(checkDocumentAccess).mockRejectedValue(new Error('Database error'))
|
||||
|
||||
const req = createMockRequest('GET')
|
||||
const response = await GET(req, { params: mockParams })
|
||||
const data = await response.json()
|
||||
|
||||
expect(response.status).toBe(500)
|
||||
expect(data.error).toBe('Failed to fetch document')
|
||||
})
|
||||
})
|
||||
|
||||
describe('PUT /api/knowledge/[id]/documents/[documentId] - Regular Updates', () => {
|
||||
const mockParams = Promise.resolve({ id: 'kb-123', documentId: 'doc-123' })
|
||||
const validUpdateData = {
|
||||
filename: 'updated-document.pdf',
|
||||
enabled: false,
|
||||
chunkCount: 10,
|
||||
tokenCount: 200,
|
||||
}
|
||||
|
||||
it('should update document successfully', async () => {
|
||||
authMockFns.mockGetSession.mockResolvedValue({
|
||||
user: { id: 'user-123', email: 'test@example.com' },
|
||||
})
|
||||
vi.mocked(checkDocumentWriteAccess).mockResolvedValue({
|
||||
hasAccess: true,
|
||||
document: mockDocument,
|
||||
knowledgeBase: { id: 'kb-123', userId: 'user-123' },
|
||||
})
|
||||
|
||||
const updatedDocument = {
|
||||
...mockDocument,
|
||||
...validUpdateData,
|
||||
deletedAt: null,
|
||||
}
|
||||
vi.mocked(updateDocument).mockResolvedValue(updatedDocument)
|
||||
|
||||
const req = createMockRequest('PUT', validUpdateData)
|
||||
const response = await PUT(req, { params: mockParams })
|
||||
const data = await response.json()
|
||||
|
||||
expect(response.status).toBe(200)
|
||||
expect(data.success).toBe(true)
|
||||
expect(data.data.filename).toBe('updated-document.pdf')
|
||||
expect(data.data.enabled).toBe(false)
|
||||
expect(vi.mocked(updateDocument)).toHaveBeenCalledWith(
|
||||
'doc-123',
|
||||
validUpdateData,
|
||||
expect.any(String)
|
||||
)
|
||||
})
|
||||
|
||||
it('should validate update data', async () => {
|
||||
authMockFns.mockGetSession.mockResolvedValue({
|
||||
user: { id: 'user-123', email: 'test@example.com' },
|
||||
})
|
||||
vi.mocked(checkDocumentWriteAccess).mockResolvedValue({
|
||||
hasAccess: true,
|
||||
document: mockDocument,
|
||||
knowledgeBase: { id: 'kb-123', userId: 'user-123' },
|
||||
})
|
||||
|
||||
const invalidData = {
|
||||
filename: '', // Invalid: empty filename
|
||||
chunkCount: -1, // Invalid: negative count
|
||||
processingStatus: 'invalid', // Invalid: not in enum
|
||||
}
|
||||
|
||||
const req = createMockRequest('PUT', invalidData)
|
||||
const response = await PUT(req, { params: mockParams })
|
||||
const data = await response.json()
|
||||
|
||||
expect(response.status).toBe(400)
|
||||
expect(data.error).toBe('Invalid request data')
|
||||
expect(data.details).toBeDefined()
|
||||
})
|
||||
})
|
||||
|
||||
describe('PUT /api/knowledge/[id]/documents/[documentId] - Mark Failed Due to Timeout', () => {
|
||||
const mockParams = Promise.resolve({ id: 'kb-123', documentId: 'doc-123' })
|
||||
|
||||
it('should mark document as failed due to timeout successfully', async () => {
|
||||
const processingDocument = {
|
||||
...mockDocument,
|
||||
processingStatus: 'processing',
|
||||
processingStartedAt: new Date(Date.now() - 200000), // 200 seconds ago
|
||||
}
|
||||
|
||||
authMockFns.mockGetSession.mockResolvedValue({
|
||||
user: { id: 'user-123', email: 'test@example.com' },
|
||||
})
|
||||
vi.mocked(checkDocumentWriteAccess).mockResolvedValue({
|
||||
hasAccess: true,
|
||||
document: processingDocument,
|
||||
knowledgeBase: { id: 'kb-123', userId: 'user-123' },
|
||||
})
|
||||
|
||||
vi.mocked(markDocumentAsFailedTimeout).mockResolvedValue({
|
||||
success: true,
|
||||
processingDuration: 200000,
|
||||
})
|
||||
|
||||
const req = createMockRequest('PUT', { markFailedDueToTimeout: true })
|
||||
const response = await PUT(req, { params: mockParams })
|
||||
const data = await response.json()
|
||||
|
||||
expect(response.status).toBe(200)
|
||||
expect(data.success).toBe(true)
|
||||
expect(data.data.documentId).toBe('doc-123')
|
||||
expect(data.data.status).toBe('failed')
|
||||
expect(data.data.message).toBe('Document marked as failed due to timeout')
|
||||
expect(vi.mocked(markDocumentAsFailedTimeout)).toHaveBeenCalledWith(
|
||||
'doc-123',
|
||||
processingDocument.processingStartedAt,
|
||||
expect.any(String)
|
||||
)
|
||||
})
|
||||
|
||||
it('should reject marking failed for non-processing document', async () => {
|
||||
authMockFns.mockGetSession.mockResolvedValue({
|
||||
user: { id: 'user-123', email: 'test@example.com' },
|
||||
})
|
||||
vi.mocked(checkDocumentWriteAccess).mockResolvedValue({
|
||||
hasAccess: true,
|
||||
document: { ...mockDocument, processingStatus: 'completed' },
|
||||
knowledgeBase: { id: 'kb-123', userId: 'user-123' },
|
||||
})
|
||||
|
||||
const req = createMockRequest('PUT', { markFailedDueToTimeout: true })
|
||||
const response = await PUT(req, { params: mockParams })
|
||||
const data = await response.json()
|
||||
|
||||
expect(response.status).toBe(400)
|
||||
expect(data.error).toContain('Document is not in processing state')
|
||||
})
|
||||
|
||||
it('should reject marking failed for recently started processing', async () => {
|
||||
const recentProcessingDocument = {
|
||||
...mockDocument,
|
||||
processingStatus: 'processing',
|
||||
processingStartedAt: new Date(Date.now() - 60000), // 60 seconds ago
|
||||
}
|
||||
|
||||
authMockFns.mockGetSession.mockResolvedValue({
|
||||
user: { id: 'user-123', email: 'test@example.com' },
|
||||
})
|
||||
vi.mocked(checkDocumentWriteAccess).mockResolvedValue({
|
||||
hasAccess: true,
|
||||
document: recentProcessingDocument,
|
||||
knowledgeBase: { id: 'kb-123', userId: 'user-123' },
|
||||
})
|
||||
|
||||
vi.mocked(markDocumentAsFailedTimeout).mockRejectedValue(
|
||||
new Error('Document has not been processing long enough to be considered dead')
|
||||
)
|
||||
|
||||
const req = createMockRequest('PUT', { markFailedDueToTimeout: true })
|
||||
const response = await PUT(req, { params: mockParams })
|
||||
const data = await response.json()
|
||||
|
||||
expect(response.status).toBe(400)
|
||||
expect(data.error).toContain('Document has not been processing long enough')
|
||||
})
|
||||
})
|
||||
|
||||
describe('PUT /api/knowledge/[id]/documents/[documentId] - Retry Processing', () => {
|
||||
const mockParams = Promise.resolve({ id: 'kb-123', documentId: 'doc-123' })
|
||||
|
||||
it('should retry processing successfully', async () => {
|
||||
const failedDocument = {
|
||||
...mockDocument,
|
||||
processingStatus: 'failed',
|
||||
processingError: 'Previous processing failed',
|
||||
}
|
||||
|
||||
authMockFns.mockGetSession.mockResolvedValue({
|
||||
user: { id: 'user-123', email: 'test@example.com' },
|
||||
})
|
||||
vi.mocked(checkDocumentWriteAccess).mockResolvedValue({
|
||||
hasAccess: true,
|
||||
document: failedDocument,
|
||||
knowledgeBase: { id: 'kb-123', userId: 'user-123' },
|
||||
})
|
||||
|
||||
vi.mocked(retryDocumentProcessing).mockResolvedValue({
|
||||
success: true,
|
||||
status: 'pending',
|
||||
message: 'Document retry processing started',
|
||||
})
|
||||
|
||||
const req = createMockRequest('PUT', { retryProcessing: true })
|
||||
const response = await PUT(req, { params: mockParams })
|
||||
const data = await response.json()
|
||||
|
||||
expect(response.status).toBe(200)
|
||||
expect(data.success).toBe(true)
|
||||
expect(data.data.status).toBe('pending')
|
||||
expect(data.data.message).toBe('Document retry processing started')
|
||||
expect(vi.mocked(retryDocumentProcessing)).toHaveBeenCalledWith(
|
||||
'kb-123',
|
||||
'doc-123',
|
||||
{
|
||||
filename: failedDocument.filename,
|
||||
fileUrl: failedDocument.fileUrl,
|
||||
fileSize: failedDocument.fileSize,
|
||||
mimeType: failedDocument.mimeType,
|
||||
},
|
||||
expect.any(String)
|
||||
)
|
||||
})
|
||||
|
||||
it('should reject retry for non-failed document', async () => {
|
||||
authMockFns.mockGetSession.mockResolvedValue({
|
||||
user: { id: 'user-123', email: 'test@example.com' },
|
||||
})
|
||||
vi.mocked(checkDocumentWriteAccess).mockResolvedValue({
|
||||
hasAccess: true,
|
||||
document: { ...mockDocument, processingStatus: 'completed' },
|
||||
knowledgeBase: { id: 'kb-123', userId: 'user-123' },
|
||||
})
|
||||
|
||||
const req = createMockRequest('PUT', { retryProcessing: true })
|
||||
const response = await PUT(req, { params: mockParams })
|
||||
const data = await response.json()
|
||||
|
||||
expect(response.status).toBe(400)
|
||||
expect(data.error).toBe('Document is not in failed state')
|
||||
})
|
||||
})
|
||||
|
||||
describe('PUT /api/knowledge/[id]/documents/[documentId] - Authentication & Authorization', () => {
|
||||
const mockParams = Promise.resolve({ id: 'kb-123', documentId: 'doc-123' })
|
||||
const validUpdateData = { filename: 'updated-document.pdf' }
|
||||
|
||||
it('should return unauthorized for unauthenticated user', async () => {
|
||||
authMockFns.mockGetSession.mockResolvedValue(null)
|
||||
|
||||
const req = createMockRequest('PUT', validUpdateData)
|
||||
const response = await PUT(req, { params: mockParams })
|
||||
const data = await response.json()
|
||||
|
||||
expect(response.status).toBe(401)
|
||||
expect(data.error).toBe('Unauthorized')
|
||||
})
|
||||
|
||||
it('should return not found for non-existent document', async () => {
|
||||
authMockFns.mockGetSession.mockResolvedValue({
|
||||
user: { id: 'user-123', email: 'test@example.com' },
|
||||
})
|
||||
vi.mocked(checkDocumentWriteAccess).mockResolvedValue({
|
||||
hasAccess: false,
|
||||
notFound: true,
|
||||
reason: 'Document not found',
|
||||
})
|
||||
|
||||
const req = createMockRequest('PUT', validUpdateData)
|
||||
const response = await PUT(req, { params: mockParams })
|
||||
const data = await response.json()
|
||||
|
||||
expect(response.status).toBe(404)
|
||||
expect(data.error).toBe('Document not found')
|
||||
})
|
||||
|
||||
it('should handle database errors during update', async () => {
|
||||
authMockFns.mockGetSession.mockResolvedValue({
|
||||
user: { id: 'user-123', email: 'test@example.com' },
|
||||
})
|
||||
vi.mocked(checkDocumentWriteAccess).mockResolvedValue({
|
||||
hasAccess: true,
|
||||
document: mockDocument,
|
||||
knowledgeBase: { id: 'kb-123', userId: 'user-123' },
|
||||
})
|
||||
|
||||
vi.mocked(updateDocument).mockRejectedValue(new Error('Database error'))
|
||||
|
||||
const req = createMockRequest('PUT', validUpdateData)
|
||||
const response = await PUT(req, { params: mockParams })
|
||||
const data = await response.json()
|
||||
|
||||
expect(response.status).toBe(500)
|
||||
expect(data.error).toBe('Failed to update document')
|
||||
})
|
||||
})
|
||||
|
||||
describe('DELETE /api/knowledge/[id]/documents/[documentId]', () => {
|
||||
const mockParams = Promise.resolve({ id: 'kb-123', documentId: 'doc-123' })
|
||||
|
||||
it('should delete document successfully', async () => {
|
||||
authMockFns.mockGetSession.mockResolvedValue({
|
||||
user: { id: 'user-123', email: 'test@example.com' },
|
||||
})
|
||||
vi.mocked(checkDocumentWriteAccess).mockResolvedValue({
|
||||
hasAccess: true,
|
||||
document: mockDocument,
|
||||
knowledgeBase: { id: 'kb-123', userId: 'user-123' },
|
||||
})
|
||||
|
||||
vi.mocked(deleteDocument).mockResolvedValue({
|
||||
success: true,
|
||||
message: 'Document deleted successfully',
|
||||
})
|
||||
|
||||
const req = createMockRequest('DELETE')
|
||||
const response = await DELETE(req, { params: mockParams })
|
||||
const data = await response.json()
|
||||
|
||||
expect(response.status).toBe(200)
|
||||
expect(data.success).toBe(true)
|
||||
expect(data.data.message).toBe('Document deleted successfully')
|
||||
expect(vi.mocked(deleteDocument)).toHaveBeenCalledWith('doc-123', expect.any(String))
|
||||
})
|
||||
|
||||
it('should return unauthorized for unauthenticated user', async () => {
|
||||
authMockFns.mockGetSession.mockResolvedValue(null)
|
||||
|
||||
const req = createMockRequest('DELETE')
|
||||
const response = await DELETE(req, { params: mockParams })
|
||||
const data = await response.json()
|
||||
|
||||
expect(response.status).toBe(401)
|
||||
expect(data.error).toBe('Unauthorized')
|
||||
})
|
||||
|
||||
it('should return not found for non-existent document', async () => {
|
||||
authMockFns.mockGetSession.mockResolvedValue({
|
||||
user: { id: 'user-123', email: 'test@example.com' },
|
||||
})
|
||||
vi.mocked(checkDocumentWriteAccess).mockResolvedValue({
|
||||
hasAccess: false,
|
||||
notFound: true,
|
||||
reason: 'Document not found',
|
||||
})
|
||||
|
||||
const req = createMockRequest('DELETE')
|
||||
const response = await DELETE(req, { params: mockParams })
|
||||
const data = await response.json()
|
||||
|
||||
expect(response.status).toBe(404)
|
||||
expect(data.error).toBe('Document not found')
|
||||
})
|
||||
|
||||
it('should return unauthorized for document without access', async () => {
|
||||
authMockFns.mockGetSession.mockResolvedValue({
|
||||
user: { id: 'user-123', email: 'test@example.com' },
|
||||
})
|
||||
vi.mocked(checkDocumentWriteAccess).mockResolvedValue({
|
||||
hasAccess: false,
|
||||
reason: 'Access denied',
|
||||
})
|
||||
|
||||
const req = createMockRequest('DELETE')
|
||||
const response = await DELETE(req, { params: mockParams })
|
||||
const data = await response.json()
|
||||
|
||||
expect(response.status).toBe(401)
|
||||
expect(data.error).toBe('Unauthorized')
|
||||
})
|
||||
|
||||
it('should handle database errors during deletion', async () => {
|
||||
authMockFns.mockGetSession.mockResolvedValue({
|
||||
user: { id: 'user-123', email: 'test@example.com' },
|
||||
})
|
||||
vi.mocked(checkDocumentWriteAccess).mockResolvedValue({
|
||||
hasAccess: true,
|
||||
document: mockDocument,
|
||||
knowledgeBase: { id: 'kb-123', userId: 'user-123' },
|
||||
})
|
||||
vi.mocked(deleteDocument).mockRejectedValue(new Error('Database error'))
|
||||
|
||||
const req = createMockRequest('DELETE')
|
||||
const response = await DELETE(req, { params: mockParams })
|
||||
const data = await response.json()
|
||||
|
||||
expect(response.status).toBe(500)
|
||||
expect(data.error).toBe('Failed to delete document')
|
||||
})
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,286 @@
|
||||
import { AuditAction, AuditResourceType, recordAudit } from '@sim/audit'
|
||||
import { createLogger } from '@sim/logger'
|
||||
import { type NextRequest, NextResponse } from 'next/server'
|
||||
import { updateKnowledgeDocumentContract } from '@/lib/api/contracts/knowledge'
|
||||
import { parseRequest } from '@/lib/api/server'
|
||||
import { checkSessionOrInternalAuth } from '@/lib/auth/hybrid'
|
||||
import { generateRequestId } from '@/lib/core/utils/request'
|
||||
import { withRouteHandler } from '@/lib/core/utils/with-route-handler'
|
||||
import {
|
||||
deleteDocument,
|
||||
markDocumentAsFailedTimeout,
|
||||
retryDocumentProcessing,
|
||||
updateDocument,
|
||||
} from '@/lib/knowledge/documents/service'
|
||||
import { captureServerEvent } from '@/lib/posthog/server'
|
||||
import { checkDocumentAccess, checkDocumentWriteAccess } from '@/app/api/knowledge/utils'
|
||||
|
||||
const logger = createLogger('DocumentByIdAPI')
|
||||
|
||||
export const GET = withRouteHandler(
|
||||
async (req: NextRequest, { params }: { params: Promise<{ id: string; documentId: string }> }) => {
|
||||
const requestId = generateRequestId()
|
||||
const { id: knowledgeBaseId, documentId } = await params
|
||||
|
||||
try {
|
||||
const auth = await checkSessionOrInternalAuth(req, { requireWorkflowId: false })
|
||||
if (!auth.success || !auth.userId) {
|
||||
logger.warn(`[${requestId}] Unauthorized document access attempt`)
|
||||
return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })
|
||||
}
|
||||
const userId = auth.userId
|
||||
|
||||
const accessCheck = await checkDocumentAccess(knowledgeBaseId, documentId, userId)
|
||||
|
||||
if (!accessCheck.hasAccess) {
|
||||
if (accessCheck.notFound) {
|
||||
logger.warn(
|
||||
`[${requestId}] ${accessCheck.reason}: KB=${knowledgeBaseId}, Doc=${documentId}`
|
||||
)
|
||||
return NextResponse.json({ error: accessCheck.reason }, { status: 404 })
|
||||
}
|
||||
logger.warn(
|
||||
`[${requestId}] User ${userId} attempted unauthorized document access: ${accessCheck.reason}`
|
||||
)
|
||||
return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })
|
||||
}
|
||||
|
||||
logger.info(
|
||||
`[${requestId}] Retrieved document: ${documentId} from knowledge base ${knowledgeBaseId}`
|
||||
)
|
||||
|
||||
return NextResponse.json({
|
||||
success: true,
|
||||
data: accessCheck.document,
|
||||
})
|
||||
} catch (error) {
|
||||
logger.error(`[${requestId}] Error fetching document`, error)
|
||||
return NextResponse.json({ error: 'Failed to fetch document' }, { status: 500 })
|
||||
}
|
||||
}
|
||||
)
|
||||
|
||||
export const PUT = withRouteHandler(
|
||||
async (req: NextRequest, { params }: { params: Promise<{ id: string; documentId: string }> }) => {
|
||||
const requestId = generateRequestId()
|
||||
const { id: knowledgeBaseId, documentId } = await params
|
||||
|
||||
try {
|
||||
const auth = await checkSessionOrInternalAuth(req, { requireWorkflowId: false })
|
||||
if (!auth.success || !auth.userId) {
|
||||
logger.warn(`[${requestId}] Unauthorized document update attempt`)
|
||||
return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })
|
||||
}
|
||||
const userId = auth.userId
|
||||
|
||||
const accessCheck = await checkDocumentWriteAccess(knowledgeBaseId, documentId, userId)
|
||||
|
||||
if (!accessCheck.hasAccess) {
|
||||
if (accessCheck.notFound) {
|
||||
logger.warn(
|
||||
`[${requestId}] ${accessCheck.reason}: KB=${knowledgeBaseId}, Doc=${documentId}`
|
||||
)
|
||||
return NextResponse.json({ error: accessCheck.reason }, { status: 404 })
|
||||
}
|
||||
logger.warn(
|
||||
`[${requestId}] User ${userId} attempted unauthorized document update: ${accessCheck.reason}`
|
||||
)
|
||||
return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })
|
||||
}
|
||||
|
||||
const parsed = await parseRequest(
|
||||
updateKnowledgeDocumentContract,
|
||||
req,
|
||||
{ params },
|
||||
{
|
||||
validationErrorResponse: (error) => {
|
||||
logger.warn(`[${requestId}] Invalid document update data`, { errors: error.issues })
|
||||
return NextResponse.json(
|
||||
{ error: 'Invalid request data', details: error.issues },
|
||||
{ status: 400 }
|
||||
)
|
||||
},
|
||||
}
|
||||
)
|
||||
if (!parsed.success) return parsed.response
|
||||
|
||||
const validatedData = parsed.data.body
|
||||
|
||||
const updateData: any = {}
|
||||
|
||||
if (validatedData.markFailedDueToTimeout) {
|
||||
const doc = accessCheck.document
|
||||
|
||||
if (doc.processingStatus !== 'processing') {
|
||||
return NextResponse.json(
|
||||
{ error: `Document is not in processing state (current: ${doc.processingStatus})` },
|
||||
{ status: 400 }
|
||||
)
|
||||
}
|
||||
|
||||
if (!doc.processingStartedAt) {
|
||||
return NextResponse.json(
|
||||
{ error: 'Document has no processing start time' },
|
||||
{ status: 400 }
|
||||
)
|
||||
}
|
||||
|
||||
try {
|
||||
await markDocumentAsFailedTimeout(documentId, doc.processingStartedAt, requestId)
|
||||
|
||||
return NextResponse.json({
|
||||
success: true,
|
||||
data: {
|
||||
documentId,
|
||||
status: 'failed',
|
||||
message: 'Document marked as failed due to timeout',
|
||||
},
|
||||
})
|
||||
} catch (error) {
|
||||
if (error instanceof Error) {
|
||||
return NextResponse.json({ error: error.message }, { status: 400 })
|
||||
}
|
||||
throw error
|
||||
}
|
||||
} else if (validatedData.retryProcessing) {
|
||||
const doc = accessCheck.document
|
||||
|
||||
if (doc.processingStatus !== 'failed') {
|
||||
return NextResponse.json({ error: 'Document is not in failed state' }, { status: 400 })
|
||||
}
|
||||
|
||||
const docData = {
|
||||
filename: doc.filename,
|
||||
fileUrl: doc.fileUrl,
|
||||
fileSize: doc.fileSize,
|
||||
mimeType: doc.mimeType,
|
||||
}
|
||||
|
||||
const result = await retryDocumentProcessing(
|
||||
knowledgeBaseId,
|
||||
documentId,
|
||||
docData,
|
||||
requestId
|
||||
)
|
||||
|
||||
return NextResponse.json({
|
||||
success: true,
|
||||
data: {
|
||||
documentId,
|
||||
status: result.status,
|
||||
message: result.message,
|
||||
},
|
||||
})
|
||||
} else {
|
||||
const updatedDocument = await updateDocument(documentId, validatedData, requestId)
|
||||
|
||||
logger.info(
|
||||
`[${requestId}] Document updated: ${documentId} in knowledge base ${knowledgeBaseId}`
|
||||
)
|
||||
|
||||
recordAudit({
|
||||
workspaceId: accessCheck.knowledgeBase?.workspaceId ?? null,
|
||||
actorId: userId,
|
||||
actorName: auth.userName,
|
||||
actorEmail: auth.userEmail,
|
||||
action: AuditAction.DOCUMENT_UPDATED,
|
||||
resourceType: AuditResourceType.DOCUMENT,
|
||||
resourceId: documentId,
|
||||
resourceName: validatedData.filename ?? accessCheck.document?.filename,
|
||||
description: `Updated document "${validatedData.filename ?? accessCheck.document?.filename}" in knowledge base "${knowledgeBaseId}"`,
|
||||
metadata: {
|
||||
knowledgeBaseId,
|
||||
knowledgeBaseName: accessCheck.knowledgeBase?.name,
|
||||
fileName: validatedData.filename ?? accessCheck.document?.filename,
|
||||
updatedFields: Object.keys(validatedData).filter(
|
||||
(k) => validatedData[k as keyof typeof validatedData] !== undefined
|
||||
),
|
||||
...(validatedData.enabled !== undefined && { enabled: validatedData.enabled }),
|
||||
},
|
||||
request: req,
|
||||
})
|
||||
|
||||
return NextResponse.json({
|
||||
success: true,
|
||||
data: updatedDocument,
|
||||
})
|
||||
}
|
||||
} catch (error) {
|
||||
logger.error(`[${requestId}] Error updating document ${documentId}`, error)
|
||||
return NextResponse.json({ error: 'Failed to update document' }, { status: 500 })
|
||||
}
|
||||
}
|
||||
)
|
||||
|
||||
export const DELETE = withRouteHandler(
|
||||
async (req: NextRequest, { params }: { params: Promise<{ id: string; documentId: string }> }) => {
|
||||
const requestId = generateRequestId()
|
||||
const { id: knowledgeBaseId, documentId } = await params
|
||||
|
||||
try {
|
||||
const auth = await checkSessionOrInternalAuth(req, { requireWorkflowId: false })
|
||||
if (!auth.success || !auth.userId) {
|
||||
logger.warn(`[${requestId}] Unauthorized document delete attempt`)
|
||||
return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })
|
||||
}
|
||||
const userId = auth.userId
|
||||
|
||||
const accessCheck = await checkDocumentWriteAccess(knowledgeBaseId, documentId, userId)
|
||||
|
||||
if (!accessCheck.hasAccess) {
|
||||
if (accessCheck.notFound) {
|
||||
logger.warn(
|
||||
`[${requestId}] ${accessCheck.reason}: KB=${knowledgeBaseId}, Doc=${documentId}`
|
||||
)
|
||||
return NextResponse.json({ error: accessCheck.reason }, { status: 404 })
|
||||
}
|
||||
logger.warn(
|
||||
`[${requestId}] User ${userId} attempted unauthorized document deletion: ${accessCheck.reason}`
|
||||
)
|
||||
return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })
|
||||
}
|
||||
|
||||
const result = await deleteDocument(documentId, requestId)
|
||||
|
||||
logger.info(
|
||||
`[${requestId}] Document deleted: ${documentId} from knowledge base ${knowledgeBaseId}`
|
||||
)
|
||||
|
||||
recordAudit({
|
||||
workspaceId: accessCheck.knowledgeBase?.workspaceId ?? null,
|
||||
actorId: userId,
|
||||
actorName: auth.userName,
|
||||
actorEmail: auth.userEmail,
|
||||
action: AuditAction.DOCUMENT_DELETED,
|
||||
resourceType: AuditResourceType.DOCUMENT,
|
||||
resourceId: documentId,
|
||||
resourceName: accessCheck.document?.filename,
|
||||
description: `Deleted document "${accessCheck.document?.filename}" from knowledge base "${knowledgeBaseId}"`,
|
||||
metadata: {
|
||||
knowledgeBaseId,
|
||||
knowledgeBaseName: accessCheck.knowledgeBase?.name,
|
||||
fileName: accessCheck.document?.filename,
|
||||
fileSize: accessCheck.document?.fileSize,
|
||||
mimeType: accessCheck.document?.mimeType,
|
||||
},
|
||||
request: req,
|
||||
})
|
||||
|
||||
const kbWorkspaceId = accessCheck.knowledgeBase?.workspaceId ?? ''
|
||||
captureServerEvent(
|
||||
userId,
|
||||
'knowledge_base_document_deleted',
|
||||
{ knowledge_base_id: knowledgeBaseId, workspace_id: kbWorkspaceId },
|
||||
kbWorkspaceId ? { groups: { workspace: kbWorkspaceId } } : undefined
|
||||
)
|
||||
|
||||
return NextResponse.json({
|
||||
success: true,
|
||||
data: result,
|
||||
})
|
||||
} catch (error) {
|
||||
logger.error(`[${requestId}] Error deleting document`, error)
|
||||
return NextResponse.json({ error: 'Failed to delete document' }, { status: 500 })
|
||||
}
|
||||
}
|
||||
)
|
||||
@@ -0,0 +1,205 @@
|
||||
import { createLogger } from '@sim/logger'
|
||||
import { generateId } from '@sim/utils/id'
|
||||
import { type NextRequest, NextResponse } from 'next/server'
|
||||
import { saveDocumentTagDefinitionsContract } from '@/lib/api/contracts/knowledge'
|
||||
import { parseRequest } from '@/lib/api/server'
|
||||
import { getSession } from '@/lib/auth'
|
||||
import { withRouteHandler } from '@/lib/core/utils/with-route-handler'
|
||||
import { SUPPORTED_FIELD_TYPES } from '@/lib/knowledge/constants'
|
||||
import {
|
||||
cleanupUnusedTagDefinitions,
|
||||
createOrUpdateTagDefinitionsBulk,
|
||||
deleteAllTagDefinitions,
|
||||
getDocumentTagDefinitions,
|
||||
} from '@/lib/knowledge/tags/service'
|
||||
import type { BulkTagDefinitionsData } from '@/lib/knowledge/tags/types'
|
||||
import { checkDocumentAccess, checkDocumentWriteAccess } from '@/app/api/knowledge/utils'
|
||||
|
||||
export const dynamic = 'force-dynamic'
|
||||
|
||||
const logger = createLogger('DocumentTagDefinitionsAPI')
|
||||
|
||||
// GET /api/knowledge/[id]/documents/[documentId]/tag-definitions - Get tag definitions for a document
|
||||
export const GET = withRouteHandler(
|
||||
async (req: NextRequest, { params }: { params: Promise<{ id: string; documentId: string }> }) => {
|
||||
const requestId = generateId().slice(0, 8)
|
||||
const { id: knowledgeBaseId, documentId } = await params
|
||||
|
||||
try {
|
||||
logger.info(`[${requestId}] Getting tag definitions for document ${documentId}`)
|
||||
|
||||
const session = await getSession()
|
||||
if (!session?.user?.id) {
|
||||
return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })
|
||||
}
|
||||
|
||||
// Verify document exists and belongs to the knowledge base
|
||||
const accessCheck = await checkDocumentAccess(knowledgeBaseId, documentId, session.user.id)
|
||||
if (!accessCheck.hasAccess) {
|
||||
if (accessCheck.notFound) {
|
||||
logger.warn(
|
||||
`[${requestId}] ${accessCheck.reason}: KB=${knowledgeBaseId}, Doc=${documentId}`
|
||||
)
|
||||
return NextResponse.json({ error: accessCheck.reason }, { status: 404 })
|
||||
}
|
||||
logger.warn(
|
||||
`[${requestId}] User ${session.user.id} attempted unauthorized document access: ${accessCheck.reason}`
|
||||
)
|
||||
return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })
|
||||
}
|
||||
|
||||
const tagDefinitions = await getDocumentTagDefinitions(knowledgeBaseId)
|
||||
|
||||
logger.info(`[${requestId}] Retrieved ${tagDefinitions.length} tag definitions`)
|
||||
|
||||
return NextResponse.json({
|
||||
success: true,
|
||||
data: tagDefinitions,
|
||||
})
|
||||
} catch (error) {
|
||||
logger.error(`[${requestId}] Error getting tag definitions`, error)
|
||||
return NextResponse.json({ error: 'Failed to get tag definitions' }, { status: 500 })
|
||||
}
|
||||
}
|
||||
)
|
||||
|
||||
// POST /api/knowledge/[id]/documents/[documentId]/tag-definitions - Create/update tag definitions
|
||||
export const POST = withRouteHandler(
|
||||
async (req: NextRequest, context: { params: Promise<{ id: string; documentId: string }> }) => {
|
||||
const requestId = generateId().slice(0, 8)
|
||||
const { id: knowledgeBaseId, documentId } = await context.params
|
||||
|
||||
try {
|
||||
logger.info(`[${requestId}] Creating/updating tag definitions for document ${documentId}`)
|
||||
|
||||
const session = await getSession()
|
||||
if (!session?.user?.id) {
|
||||
return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })
|
||||
}
|
||||
|
||||
// Verify document exists and user has write access
|
||||
const accessCheck = await checkDocumentWriteAccess(
|
||||
knowledgeBaseId,
|
||||
documentId,
|
||||
session.user.id
|
||||
)
|
||||
if (!accessCheck.hasAccess) {
|
||||
if (accessCheck.notFound) {
|
||||
logger.warn(
|
||||
`[${requestId}] ${accessCheck.reason}: KB=${knowledgeBaseId}, Doc=${documentId}`
|
||||
)
|
||||
return NextResponse.json({ error: accessCheck.reason }, { status: 404 })
|
||||
}
|
||||
logger.warn(
|
||||
`[${requestId}] User ${session.user.id} attempted unauthorized document write access: ${accessCheck.reason}`
|
||||
)
|
||||
return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })
|
||||
}
|
||||
|
||||
const parsed = await parseRequest(saveDocumentTagDefinitionsContract, req, context)
|
||||
if (!parsed.success) return parsed.response
|
||||
|
||||
const validatedData = parsed.data.body
|
||||
|
||||
for (const def of validatedData.definitions) {
|
||||
/**
|
||||
* Defense-in-depth runtime check: the contract types `fieldType` as a plain
|
||||
* string because tightening to the field-type enum cascades into UI form
|
||||
* state types. Cast here to allow `includes` to accept the wider input.
|
||||
*/
|
||||
if (!(SUPPORTED_FIELD_TYPES as readonly string[]).includes(def.fieldType)) {
|
||||
return NextResponse.json(
|
||||
{ error: 'Invalid request data', details: `Unsupported field type: ${def.fieldType}` },
|
||||
{ status: 400 }
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
const bulkData: BulkTagDefinitionsData = {
|
||||
definitions: validatedData.definitions.map((def) => ({
|
||||
tagSlot: def.tagSlot,
|
||||
displayName: def.displayName,
|
||||
fieldType: def.fieldType,
|
||||
originalDisplayName: def._originalDisplayName,
|
||||
})),
|
||||
}
|
||||
|
||||
const result = await createOrUpdateTagDefinitionsBulk(knowledgeBaseId, bulkData, requestId)
|
||||
|
||||
return NextResponse.json({
|
||||
success: true,
|
||||
data: {
|
||||
created: result.created,
|
||||
updated: result.updated,
|
||||
errors: result.errors,
|
||||
},
|
||||
})
|
||||
} catch (error) {
|
||||
logger.error(`[${requestId}] Error creating/updating tag definitions`, error)
|
||||
return NextResponse.json(
|
||||
{ error: 'Failed to create/update tag definitions' },
|
||||
{ status: 500 }
|
||||
)
|
||||
}
|
||||
}
|
||||
)
|
||||
|
||||
// DELETE /api/knowledge/[id]/documents/[documentId]/tag-definitions - Delete all tag definitions for a document
|
||||
export const DELETE = withRouteHandler(
|
||||
async (req: NextRequest, { params }: { params: Promise<{ id: string; documentId: string }> }) => {
|
||||
const requestId = generateId().slice(0, 8)
|
||||
const { id: knowledgeBaseId, documentId } = await params
|
||||
const { searchParams } = new URL(req.url)
|
||||
const action = searchParams.get('action') // 'cleanup' or 'all'
|
||||
|
||||
try {
|
||||
const session = await getSession()
|
||||
if (!session?.user?.id) {
|
||||
return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })
|
||||
}
|
||||
|
||||
// Verify document exists and user has write access
|
||||
const accessCheck = await checkDocumentWriteAccess(
|
||||
knowledgeBaseId,
|
||||
documentId,
|
||||
session.user.id
|
||||
)
|
||||
if (!accessCheck.hasAccess) {
|
||||
if (accessCheck.notFound) {
|
||||
logger.warn(
|
||||
`[${requestId}] ${accessCheck.reason}: KB=${knowledgeBaseId}, Doc=${documentId}`
|
||||
)
|
||||
return NextResponse.json({ error: accessCheck.reason }, { status: 404 })
|
||||
}
|
||||
logger.warn(
|
||||
`[${requestId}] User ${session.user.id} attempted unauthorized document write access: ${accessCheck.reason}`
|
||||
)
|
||||
return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })
|
||||
}
|
||||
|
||||
if (action === 'cleanup') {
|
||||
// Just run cleanup
|
||||
logger.info(`[${requestId}] Running cleanup for KB ${knowledgeBaseId}`)
|
||||
const cleanedUpCount = await cleanupUnusedTagDefinitions(knowledgeBaseId, requestId)
|
||||
|
||||
return NextResponse.json({
|
||||
success: true,
|
||||
data: { cleanedUp: cleanedUpCount },
|
||||
})
|
||||
}
|
||||
// Delete all tag definitions (original behavior)
|
||||
logger.info(`[${requestId}] Deleting all tag definitions for KB ${knowledgeBaseId}`)
|
||||
|
||||
const deletedCount = await deleteAllTagDefinitions(knowledgeBaseId, requestId)
|
||||
|
||||
return NextResponse.json({
|
||||
success: true,
|
||||
message: 'Tag definitions deleted successfully',
|
||||
data: { deleted: deletedCount },
|
||||
})
|
||||
} catch (error) {
|
||||
logger.error(`[${requestId}] Error with tag definitions operation`, error)
|
||||
return NextResponse.json({ error: 'Failed to process tag definitions' }, { status: 500 })
|
||||
}
|
||||
}
|
||||
)
|
||||
Reference in New Issue
Block a user