Skip to content

Commit f8f886e

Browse files
committed
fix(integrations): stream neo4j records under the cap, keep mysql preferred tls as documented, tune truncation hints
1 parent 6a97c70 commit f8f886e

8 files changed

Lines changed: 122 additions & 128 deletions

File tree

‎apps/sim/lib/internal/mongodb/operations.ts‎

Lines changed: 10 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -36,7 +36,8 @@ export class MongodbOperationInputError extends Error {}
3636
*/
3737
async function readCappedDocuments(
3838
cursor: AsyncIterable<Document>,
39-
describe: (count: number) => string
39+
describe: (count: number) => string,
40+
paginationHint: string
4041
) {
4142
const budget = createResultRowsBudget()
4243
const documents: Document[] = []
@@ -50,10 +51,7 @@ async function readCappedDocuments(
5051
}
5152
const message = describe(documents.length)
5253
if (!truncated) return { message, documents }
53-
const truncationReason = resultTruncationReason(
54-
documents.length,
55-
'Narrow the filter or page with $skip and $limit to read the rest.'
56-
)
54+
const truncationReason = resultTruncationReason(documents.length, paginationHint)
5755
return {
5856
message: `${message} ${truncationReason}`,
5957
documents,
@@ -107,7 +105,11 @@ export function executeMongodbQuery(input: MongodbQueryInput, signal?: AbortSign
107105
}
108106

109107
cursor = cursor.limit(input.limit || 100)
110-
const result = await readCappedDocuments(cursor, (count) => `Found ${count} documents`)
108+
const result = await readCappedDocuments(
109+
cursor,
110+
(count) => `Found ${count} documents`,
111+
'Narrow the filter, or page with $skip and $limit in an aggregation pipeline.'
112+
)
111113
signal?.throwIfAborted()
112114
return { ...result, documentCount: result.documents.length }
113115
})
@@ -126,7 +128,8 @@ export function executeMongodbAggregation(input: MongodbExecuteInput, signal?: A
126128
return withMongodbClient(input, signal, async (client) => {
127129
const result = await readCappedDocuments(
128130
client.db(input.database).collection(collectionName).aggregate(pipeline, { signal }),
129-
(count) => `Aggregation completed, returned ${count} documents`
131+
(count) => `Aggregation completed, returned ${count} documents`,
132+
'Page with $skip and $limit stages to read the rest.'
130133
)
131134
signal?.throwIfAborted()
132135
return { ...result, documentCount: result.documents.length }

‎apps/sim/lib/internal/mysql/client.test.ts‎

Lines changed: 0 additions & 33 deletions
Original file line numberDiff line numberDiff line change
@@ -85,39 +85,6 @@ describe('MySQL client', () => {
8585
expect(socket.setNoDelay).toHaveBeenCalledWith(true)
8686
})
8787

88-
it('connects unencrypted for ssl=preferred when the server does not offer TLS', async () => {
89-
const connection = { end: vi.fn(), destroy: vi.fn() }
90-
mockCreateConnection
91-
.mockRejectedValueOnce(
92-
Object.assign(new Error('Server does not support secure connection'), {
93-
code: 'HANDSHAKE_NO_SSL_SUPPORT',
94-
})
95-
)
96-
.mockResolvedValueOnce(connection)
97-
98-
await expect(createMysqlConnection({ ...CONNECTION_CONFIG, ssl: 'preferred' })).resolves.toBe(
99-
connection
100-
)
101-
expect(mockCreateConnection).toHaveBeenCalledTimes(2)
102-
expect(mockCreateConnection.mock.calls[1][0].ssl).toBeUndefined()
103-
})
104-
105-
it.each(['required', 'disabled'] as const)(
106-
'does not retry ssl=%s after a handshake failure',
107-
async (ssl) => {
108-
mockCreateConnection.mockRejectedValueOnce(
109-
Object.assign(new Error('Server does not support secure connection'), {
110-
code: 'HANDSHAKE_NO_SSL_SUPPORT',
111-
})
112-
)
113-
114-
await expect(createMysqlConnection({ ...CONNECTION_CONFIG, ssl })).rejects.toThrow(
115-
'Server does not support secure connection'
116-
)
117-
expect(mockCreateConnection).toHaveBeenCalledTimes(1)
118-
}
119-
)
120-
12188
it.each([
12289
new Map([['key', 'value']]),
12390
new Set(['value']),

‎apps/sim/lib/internal/mysql/client.ts‎

Lines changed: 1 addition & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,4 @@
11
import net from 'node:net'
2-
import { isRecordLike } from '@sim/utils/object'
32
import mysql from 'mysql2/promise'
43
import { validateDatabaseHost } from '@/lib/core/security/input-validation.server'
54

@@ -41,15 +40,6 @@ function assertMysqlExecuteValues(
4140
}
4241
}
4342

44-
function isNoSslSupportError(error: unknown): boolean {
45-
return isRecordLike(error) && error.code === 'HANDSHAKE_NO_SSL_SUPPORT'
46-
}
47-
48-
/**
49-
* Connects with the requested TLS mode. mysql2 has no "prefer" mode (with `ssl` set it refuses a
50-
* server without TLS), so `preferred` retries unencrypted only when the server does not offer
51-
* TLS, matching MySQL's own `ssl-mode=PREFERRED`.
52-
*/
5343
export async function createMysqlConnection(
5444
config: MysqlConnectionConfig,
5545
signal?: AbortSignal
@@ -87,11 +77,7 @@ export async function createMysqlConnection(
8777
}
8878

8979
try {
90-
const connection = await mysql.createConnection(connectionConfig).catch((error: unknown) => {
91-
if (config.ssl !== 'preferred' || !isNoSslSupportError(error)) throw error
92-
signal?.throwIfAborted()
93-
return mysql.createConnection({ ...connectionConfig, ssl: undefined })
94-
})
80+
const connection = await mysql.createConnection(connectionConfig)
9581
signal?.throwIfAborted()
9682
return connection
9783
} catch (error) {

‎apps/sim/lib/internal/mysql/schema.ts‎

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -4,8 +4,7 @@ import { z } from 'zod'
44
const sslModeSchema = z.enum(['disabled', 'required', 'preferred']).default('preferred')
55
/**
66
* TLS mode for a MySQL connection: `required` encrypts and verifies the server certificate,
7-
* `preferred` encrypts without verifying it when the server offers TLS and connects unencrypted
8-
* when it does not, and `disabled` connects without TLS.
7+
* `preferred` encrypts without verifying it, and `disabled` connects without TLS.
98
*/
109
export type MysqlSslMode = z.output<typeof sslModeSchema>
1110

‎apps/sim/lib/internal/neo4j/operations.test.ts‎

Lines changed: 37 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -24,7 +24,8 @@ const INPUT = {
2424
parameters: {},
2525
}
2626

27-
function queryResult() {
27+
/** A driver `Result` streaming `count` records, recording whether the rest was discarded. */
28+
function streamingResult(count: number) {
2829
const updates = {
2930
nodesCreated: 0,
3031
nodesDeleted: 0,
@@ -38,19 +39,32 @@ function queryResult() {
3839
constraintsAdded: 0,
3940
constraintsRemoved: 0,
4041
}
42+
const summary = {
43+
resultAvailableAfter: { toNumber: () => 2 },
44+
resultConsumedAfter: { toNumber: () => 3 },
45+
counters: { updates: () => updates },
46+
}
47+
const state = { pulled: 0, discarded: false }
48+
const record = { keys: ['name'], get: () => 'Ada' }
4149
return {
42-
records: [{ keys: ['name'], get: vi.fn().mockReturnValue('Ada') }],
43-
summary: {
44-
resultAvailableAfter: { toNumber: () => 2 },
45-
resultConsumedAfter: { toNumber: () => 3 },
46-
counters: { updates: () => updates },
47-
},
50+
state,
51+
[Symbol.asyncIterator]: () => ({
52+
next: async () => {
53+
if (state.pulled >= count) return { done: true, value: summary }
54+
state.pulled++
55+
return { done: false, value: record }
56+
},
57+
return: async () => {
58+
state.discarded = true
59+
return { done: true, value: summary }
60+
},
61+
}),
4862
}
4963
}
5064

5165
describe('Neo4j operations', () => {
5266
beforeEach(() => {
53-
mocks.run.mockResolvedValue(queryResult())
67+
mocks.run.mockImplementation(() => streamingResult(1))
5468
mocks.sessionClose.mockResolvedValue(undefined)
5569
mocks.driverClose.mockResolvedValue(undefined)
5670
mocks.createDriver.mockResolvedValue({
@@ -59,6 +73,21 @@ describe('Neo4j operations', () => {
5973
})
6074
})
6175

76+
it('stops pulling records at the ceiling and keeps the summary', async () => {
77+
const result = streamingResult(20_000)
78+
mocks.run.mockReturnValue(result)
79+
80+
const response = await executeNeo4jQuery(INPUT)
81+
82+
expect(result.state).toEqual({ pulled: 10_001, discarded: true })
83+
expect(response).toMatchObject({
84+
recordCount: 10_000,
85+
truncated: true,
86+
summary: { resultAvailableAfter: 2 },
87+
})
88+
expect(mocks.sessionClose).toHaveBeenCalled()
89+
})
90+
6291
it('rejects invalid Cypher before opening a driver', async () => {
6392
await expect(executeNeo4jQuery({ ...INPUT, cypherQuery: ' ' })).rejects.toBeInstanceOf(
6493
Neo4jOperationInputError

‎apps/sim/lib/internal/neo4j/operations.ts‎

Lines changed: 65 additions & 60 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
import { createLogger } from '@sim/logger'
2-
import type { QueryResult, Session } from 'neo4j-driver'
2+
import type { Record as Neo4jRecord, Result, ResultSummary, Session } from 'neo4j-driver'
33
import type {
44
Neo4jCreateRequest,
55
Neo4jDeleteRequest,
@@ -12,7 +12,7 @@ import type {
1212
import { createNeo4jDriver } from '@/lib/internal/neo4j/client'
1313
import { convertNeo4jValue } from '@/lib/internal/neo4j/values'
1414
import {
15-
capResultRows,
15+
createResultRowsBudget,
1616
resultTruncationReason,
1717
} from '@/lib/internal/tool-operations/response-limits'
1818
import type { Neo4jNodeSchema, Neo4jRelationshipSchema } from '@/tools/neo4j/types'
@@ -47,21 +47,42 @@ function bindSessionAbort(session: Session, signal?: AbortSignal): () => void {
4747
return () => signal.removeEventListener('abort', abort)
4848
}
4949

50-
function projectRecords(result: QueryResult): Array<Record<string, unknown>> {
51-
return result.records.map((record) => {
52-
const projected: Record<string, unknown> = {}
53-
for (const key of record.keys) {
54-
if (typeof key === 'string') projected[key] = convertNeo4jValue(record.get(key))
50+
function projectRecord(record: Neo4jRecord): Record<string, unknown> {
51+
const projected: Record<string, unknown> = {}
52+
for (const key of record.keys) {
53+
if (typeof key === 'string') projected[key] = convertNeo4jValue(record.get(key))
54+
}
55+
return projected
56+
}
57+
58+
/**
59+
* Streams records until the response budget is spent. Returning the iterator early discards the
60+
* rest on the server (the statement still completes, so the summary counters stay accurate)
61+
* instead of buffering every record in memory.
62+
*/
63+
async function readCappedRecords(result: Result) {
64+
const budget = createResultRowsBudget()
65+
const records: Array<Record<string, unknown>> = []
66+
const iterator = result[Symbol.asyncIterator]()
67+
let next = await iterator.next()
68+
while (!next.done) {
69+
const projected = projectRecord(next.value)
70+
if (!budget.admit(projected)) {
71+
const rest = await iterator.return?.()
72+
if (!rest?.done) throw new Error('Neo4j result ended without a summary')
73+
return { records, summary: rest.value, truncated: true }
5574
}
56-
return projected
57-
})
75+
records.push(projected)
76+
next = await iterator.next()
77+
}
78+
return { records, summary: next.value, truncated: false }
5879
}
5980

60-
function projectSummary(result: QueryResult) {
61-
const updates = result.summary.counters.updates()
81+
function projectSummary(summary: ResultSummary) {
82+
const updates = summary.counters.updates()
6283
return {
63-
resultAvailableAfter: result.summary.resultAvailableAfter.toNumber(),
64-
resultConsumedAfter: result.summary.resultConsumedAfter.toNumber(),
84+
resultAvailableAfter: summary.resultAvailableAfter.toNumber(),
85+
resultConsumedAfter: summary.resultConsumedAfter.toNumber(),
6586
counters: {
6687
nodesCreated: updates.nodesCreated,
6788
nodesDeleted: updates.nodesDeleted,
@@ -78,58 +99,42 @@ function projectSummary(result: QueryResult) {
7899
}
79100
}
80101

81-
function statementResponse(kind: StatementKind, result: QueryResult) {
82-
const { rows: records, truncated } = capResultRows(projectRecords(result))
83-
const summary = projectSummary(result)
84-
const truncation = truncated
85-
? {
86-
truncated: true,
87-
truncationReason: resultTruncationReason(
88-
records.length,
89-
'Page with SKIP and LIMIT to read the rest.'
90-
),
91-
}
102+
function statementResponse(
103+
kind: StatementKind,
104+
read: Awaited<ReturnType<typeof readCappedRecords>>
105+
) {
106+
const { records } = read
107+
const summary = projectSummary(read.summary)
108+
const truncationReason = read.truncated
109+
? resultTruncationReason(
110+
records.length,
111+
kind === 'query'
112+
? 'Page with SKIP and LIMIT to read the rest.'
113+
: 'A write statement still ran in full; page a read with SKIP and LIMIT to read the rest.'
114+
)
92115
: undefined
93-
const withTruncation = (message: string) =>
94-
truncation ? `${message} ${truncation.truncationReason}` : message
116+
const withRecords = (message: string) => ({
117+
message: truncationReason ? `${message} ${truncationReason}` : message,
118+
records,
119+
recordCount: records.length,
120+
summary,
121+
...(truncationReason && { truncated: true, truncationReason }),
122+
})
95123
switch (kind) {
96124
case 'query':
97-
return {
98-
message: withTruncation(`Found ${records.length} records`),
99-
records,
100-
recordCount: records.length,
101-
summary,
102-
...truncation,
103-
}
125+
return withRecords(`Found ${records.length} records`)
104126
case 'execute':
105-
return {
106-
message: withTruncation(`Query executed successfully, returned ${records.length} records`),
107-
records,
108-
recordCount: records.length,
109-
summary,
110-
...truncation,
111-
}
127+
return withRecords(`Query executed successfully, returned ${records.length} records`)
112128
case 'create':
113-
return {
114-
message: `Created ${summary.counters.nodesCreated} nodes and ${summary.counters.relationshipsCreated} relationships`,
115-
records,
116-
recordCount: records.length,
117-
summary,
118-
}
129+
return withRecords(
130+
`Created ${summary.counters.nodesCreated} nodes and ${summary.counters.relationshipsCreated} relationships`
131+
)
119132
case 'update':
120-
return {
121-
message: `Updated ${summary.counters.propertiesSet} properties`,
122-
records,
123-
recordCount: records.length,
124-
summary,
125-
}
133+
return withRecords(`Updated ${summary.counters.propertiesSet} properties`)
126134
case 'merge':
127-
return {
128-
message: `Merge completed: ${summary.counters.nodesCreated} nodes created, ${summary.counters.relationshipsCreated} relationships created`,
129-
records,
130-
recordCount: records.length,
131-
summary,
132-
}
135+
return withRecords(
136+
`Merge completed: ${summary.counters.nodesCreated} nodes created, ${summary.counters.relationshipsCreated} relationships created`
137+
)
133138
case 'delete':
134139
return {
135140
message: `Deleted ${summary.counters.nodesDeleted} nodes and ${summary.counters.relationshipsDeleted} relationships`,
@@ -145,9 +150,9 @@ async function executeStatement(input: StatementInput, kind: StatementKind, sign
145150
const session = driver.session({ database: input.database })
146151
const unbindAbort = bindSessionAbort(session, signal)
147152
try {
148-
const result = await session.run(input.cypherQuery, input.parameters ?? {})
153+
const read = await readCappedRecords(session.run(input.cypherQuery, input.parameters ?? {}))
149154
signal?.throwIfAborted()
150-
return statementResponse(kind, result)
155+
return statementResponse(kind, read)
151156
} finally {
152157
unbindAbort()
153158
await session.close().catch(() => undefined)

‎apps/sim/lib/internal/postgresql/queries.ts‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -83,7 +83,7 @@ export async function queryPostgres(
8383
return capStatementRows(
8484
result,
8585
result.count ?? result.length ?? 0,
86-
'Page with LIMIT and OFFSET to read the rest.'
86+
'A write statement still ran in full; page a SELECT with LIMIT and OFFSET to read the rest.'
8787
)
8888
}
8989

0 commit comments

Comments
 (0)