Skip to content

Commit b5dba82

Browse files
authored
improvement(db): reduce connection saturation and egress hotspots (#4594)
* improvement(db): reduce connection saturation and egress hotspots * fix(vfs): preserve native content type in copilot SQL projection * fix(vfs): guard jsonb_array_elements against non-array contentBlocks
1 parent 104949b commit b5dba82

5 files changed

Lines changed: 32 additions & 13 deletions

File tree

apps/realtime/src/database/operations.ts

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -30,7 +30,7 @@ const socketDb = drizzle(
3030
prepare: false,
3131
idle_timeout: 10,
3232
connect_timeout: 20,
33-
max: 30,
33+
max: 15,
3434
onnotice: () => {},
3535
}),
3636
{ schema }

apps/sim/app/api/mcp/servers/[id]/refresh/route.ts

Lines changed: 2 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@ import { db } from '@sim/db'
22
import { mcpServers, workflow, workflowBlocks } from '@sim/db/schema'
33
import { createLogger } from '@sim/logger'
44
import { toError } from '@sim/utils/errors'
5-
import { and, eq, isNull } from 'drizzle-orm'
5+
import { and, eq, inArray, isNull } from 'drizzle-orm'
66
import type { NextRequest } from 'next/server'
77
import { mcpServerIdParamsSchema } from '@/lib/api/contracts/mcp'
88
import { validationErrorResponse } from '@/lib/api/server'
@@ -77,13 +77,11 @@ async function syncToolSchemasToWorkflows(
7777
subBlocks: workflowBlocks.subBlocks,
7878
})
7979
.from(workflowBlocks)
80-
.where(eq(workflowBlocks.type, 'agent'))
80+
.where(and(eq(workflowBlocks.type, 'agent'), inArray(workflowBlocks.workflowId, workflowIds)))
8181

8282
const updatedWorkflowIds = new Set<string>()
8383

8484
for (const block of agentBlocks) {
85-
if (!workflowIds.includes(block.workflowId)) continue
86-
8785
const subBlocks = block.subBlocks as Record<string, unknown> | null
8886
if (!subBlocks) continue
8987

apps/sim/app/api/mcp/tools/stored/route.ts

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@ import { db } from '@sim/db'
22
import { workflow, workflowBlocks } from '@sim/db/schema'
33
import { createLogger } from '@sim/logger'
44
import { toError } from '@sim/utils/errors'
5-
import { eq } from 'drizzle-orm'
5+
import { and, eq, inArray } from 'drizzle-orm'
66
import type { NextRequest } from 'next/server'
77
import { withRouteHandler } from '@/lib/core/utils/with-route-handler'
88
import { withMcpAuth } from '@/lib/mcp/middleware'
@@ -33,13 +33,13 @@ export const GET = withRouteHandler(
3333
const agentBlocks = await db
3434
.select({ workflowId: workflowBlocks.workflowId, subBlocks: workflowBlocks.subBlocks })
3535
.from(workflowBlocks)
36-
.where(eq(workflowBlocks.type, 'agent'))
36+
.where(
37+
and(eq(workflowBlocks.type, 'agent'), inArray(workflowBlocks.workflowId, workflowIds))
38+
)
3739

3840
const storedTools: StoredMcpTool[] = []
3941

4042
for (const block of agentBlocks) {
41-
if (!workflowMap.has(block.workflowId)) continue
42-
4343
const subBlocks = block.subBlocks as Record<string, unknown> | null
4444
if (!subBlocks) continue
4545

apps/sim/lib/copilot/vfs/workspace-vfs.ts

Lines changed: 24 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -17,7 +17,7 @@ import {
1717
} from '@sim/db/schema'
1818
import { createLogger } from '@sim/logger'
1919
import { toError } from '@sim/utils/errors'
20-
import { and, desc, eq, isNotNull, isNull, ne } from 'drizzle-orm'
20+
import { and, desc, eq, isNotNull, isNull, ne, sql } from 'drizzle-orm'
2121
import { listApiKeys } from '@/lib/api-key/service'
2222
import { buildWorkspaceMd, type WorkspaceMdData } from '@/lib/copilot/chat/workspace-context'
2323
import { extractDocumentStyle } from '@/lib/copilot/vfs/document-style'
@@ -1157,7 +1157,27 @@ export class WorkspaceVFS {
11571157
.select({
11581158
id: copilotChats.id,
11591159
title: copilotChats.title,
1160-
messages: copilotChats.messages,
1160+
messageCount: sql<number>`COALESCE(jsonb_array_length(${copilotChats.messages}), 0)`,
1161+
messages: sql<unknown[]>`COALESCE((
1162+
SELECT jsonb_agg(
1163+
jsonb_build_object(
1164+
'role', m->>'role',
1165+
'content', m->'content',
1166+
'contentBlocks', COALESCE((
1167+
SELECT jsonb_agg(jsonb_build_object('type', 'text', 'content', b->'content'))
1168+
FROM jsonb_array_elements(
1169+
CASE WHEN jsonb_typeof(m->'contentBlocks') = 'array'
1170+
THEN m->'contentBlocks'
1171+
ELSE '[]'::jsonb
1172+
END
1173+
) AS b
1174+
WHERE b->>'type' = 'text'
1175+
), '[]'::jsonb)
1176+
)
1177+
)
1178+
FROM jsonb_array_elements(${copilotChats.messages}) AS m
1179+
WHERE m->>'role' IN ('user', 'assistant')
1180+
), '[]'::jsonb)`,
11611181
createdAt: copilotChats.createdAt,
11621182
updatedAt: copilotChats.updatedAt,
11631183
})
@@ -1177,13 +1197,14 @@ export class WorkspaceVFS {
11771197
const safeName = sanitizeName(title)
11781198
const prefix = `tasks/${safeName}/`
11791199
const messages = Array.isArray(task.messages) ? task.messages : []
1200+
const messageCount = Number(task.messageCount) || 0
11801201

11811202
this.files.set(
11821203
`${prefix}session.md`,
11831204
serializeTaskSession({
11841205
id: task.id,
11851206
title,
1186-
messageCount: messages.length,
1207+
messageCount,
11871208
createdAt: task.createdAt,
11881209
updatedAt: task.updatedAt,
11891210
})

packages/db/db.ts

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -11,7 +11,7 @@ const postgresClient = postgres(connectionString, {
1111
prepare: false,
1212
idle_timeout: 20,
1313
connect_timeout: 30,
14-
max: 30,
14+
max: 15,
1515
onnotice: () => {},
1616
})
1717

0 commit comments

Comments
 (0)