T-200: edits made in the worktree
This commit is contained in:
parent
872debd9c6
commit
e720c879df
4 changed files with 158 additions and 179 deletions
|
|
@ -30,7 +30,8 @@ export const RESEARCH_COPILOT_PG_LOCK_TIMEOUT_MS = 2_000;
|
|||
|
||||
const POSTGRES_URL_PREFIX_RE = /^postgres(?:ql)?:\/\//i;
|
||||
const SCHEMA_IDENT_RE = /^[a-z_][a-z0-9_]*$/;
|
||||
const SQLSTATE_RE = /^[0-9A-Z]{5}$/;
|
||||
const PORT_DIGITS_RE = /^\d+$/;
|
||||
const FINDING_REPLAY_SQLSTATE = '23505';
|
||||
|
||||
function hasControlChar(value: string): boolean {
|
||||
for (let i = 0; i < value.length; i += 1) {
|
||||
|
|
@ -127,131 +128,38 @@ export interface OpenResearchCopilotExecutorOptions {
|
|||
readonly env?: Readonly<Record<string, string | undefined>>;
|
||||
}
|
||||
|
||||
interface NormalizedPoolSetup {
|
||||
readonly poolConfig: PoolConfig;
|
||||
readonly secretNeedles: readonly string[];
|
||||
}
|
||||
|
||||
function addRawAndDecodedNeedle(needles: Set<string>, raw: string): void {
|
||||
if (raw.length === 0) {
|
||||
return;
|
||||
}
|
||||
needles.add(raw);
|
||||
try {
|
||||
const decoded = decodeURIComponent(raw);
|
||||
if (decoded.length > 0) {
|
||||
needles.add(decoded);
|
||||
}
|
||||
} catch {
|
||||
// Malformed percent-encoding: raw needle is already registered.
|
||||
}
|
||||
}
|
||||
|
||||
function collectSecretNeedles(rawUrl: string, parsed: URL): readonly string[] {
|
||||
const needles = new Set<string>();
|
||||
if (rawUrl.length > 0) {
|
||||
needles.add(rawUrl);
|
||||
}
|
||||
if (parsed.href.length > 0) {
|
||||
needles.add(parsed.href);
|
||||
}
|
||||
addRawAndDecodedNeedle(needles, parsed.password);
|
||||
for (const [key, value] of parsed.searchParams.entries()) {
|
||||
if (key.toLowerCase() === 'password' && value.length > 0) {
|
||||
needles.add(value);
|
||||
}
|
||||
}
|
||||
if (parsed.search.length > 1) {
|
||||
const pairs = parsed.search.slice(1).split('&');
|
||||
for (let i = 0; i < pairs.length; i += 1) {
|
||||
const pair = pairs[i] as string;
|
||||
const eqIdx = pair.indexOf('=');
|
||||
if (eqIdx <= 0) {
|
||||
continue;
|
||||
}
|
||||
const rawKey = pair.slice(0, eqIdx);
|
||||
let decodedKey = rawKey;
|
||||
try {
|
||||
decodedKey = decodeURIComponent(rawKey);
|
||||
} catch {
|
||||
// Keep rawKey if percent-decoding fails.
|
||||
}
|
||||
if (decodedKey.toLowerCase() === 'password') {
|
||||
addRawAndDecodedNeedle(needles, pair.slice(eqIdx + 1));
|
||||
}
|
||||
}
|
||||
}
|
||||
return Array.from(needles);
|
||||
}
|
||||
|
||||
function containsAnyNeedle(text: string, needles: readonly string[]): boolean {
|
||||
for (let i = 0; i < needles.length; i += 1) {
|
||||
if (text.includes(needles[i] as string)) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
function isErrorSafeToSurface(
|
||||
error: unknown,
|
||||
needles: readonly string[],
|
||||
visited: Set<unknown> = new Set(),
|
||||
depth = 0
|
||||
): error is Error {
|
||||
if (!(error instanceof Error) || depth > 8) {
|
||||
return false;
|
||||
}
|
||||
if (visited.has(error)) {
|
||||
return true;
|
||||
}
|
||||
visited.add(error);
|
||||
|
||||
try {
|
||||
if (typeof error.message !== 'string' || containsAnyNeedle(error.message, needles)) {
|
||||
return false;
|
||||
}
|
||||
if (typeof error.stack === 'string' && containsAnyNeedle(error.stack, needles)) {
|
||||
return false;
|
||||
}
|
||||
const record = error as unknown as Record<string, unknown>;
|
||||
for (const field of ['detail', 'hint', 'where', 'internalQuery', 'routine']) {
|
||||
const value = record[field];
|
||||
if (typeof value === 'string' && containsAnyNeedle(value, needles)) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
if (record.cause !== undefined && !isErrorSafeToSurface(record.cause, needles, visited, depth + 1)) {
|
||||
return false;
|
||||
}
|
||||
if (error instanceof AggregateError || 'errors' in error) {
|
||||
const nested = record.errors;
|
||||
if (nested !== undefined) {
|
||||
if (!Array.isArray(nested)) {
|
||||
return false;
|
||||
}
|
||||
for (let i = 0; i < nested.length; i += 1) {
|
||||
if (!isErrorSafeToSurface(nested[i], needles, visited, depth + 1)) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
return true;
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
function extractSqlState(error: unknown): string | undefined {
|
||||
function extractFindingReplaySqlState(error: unknown): '23505' | undefined {
|
||||
if (typeof error !== 'object' || error === null) {
|
||||
return undefined;
|
||||
}
|
||||
const code = (error as { readonly code?: unknown }).code;
|
||||
if (typeof code === 'string' && SQLSTATE_RE.test(code)) {
|
||||
return code;
|
||||
return code === FINDING_REPLAY_SQLSTATE ? FINDING_REPLAY_SQLSTATE : undefined;
|
||||
}
|
||||
|
||||
function getLastExactQueryParam(parsed: URL, name: string): string | undefined {
|
||||
let value: string | undefined;
|
||||
for (const [key, entry] of parsed.searchParams.entries()) {
|
||||
if (key === name) {
|
||||
value = entry;
|
||||
}
|
||||
}
|
||||
return value;
|
||||
}
|
||||
|
||||
function assertValidPort(rawPort: string): void {
|
||||
if (!PORT_DIGITS_RE.test(rawPort)) {
|
||||
throw new ResearchCopilotExecutorError(
|
||||
'INVALID_CONFIG',
|
||||
'Invalid PostgreSQL configuration: URL port must be an integer between 1 and 65535.'
|
||||
);
|
||||
}
|
||||
const portNum = Number(rawPort);
|
||||
if (!Number.isInteger(portNum) || portNum < 1 || portNum > 65535) {
|
||||
throw new ResearchCopilotExecutorError(
|
||||
'INVALID_CONFIG',
|
||||
'Invalid PostgreSQL configuration: URL port must be an integer between 1 and 65535.'
|
||||
);
|
||||
}
|
||||
return undefined;
|
||||
}
|
||||
|
||||
function parsePostgresUrlStrict(raw: string): { readonly url: URL; readonly usedDummyHost: boolean } {
|
||||
|
|
@ -352,7 +260,7 @@ function normalizePgOptions(
|
|||
function parseAndNormalizePoolConfig(
|
||||
config: ResearchCopilotExecutorConfig,
|
||||
env: Readonly<Record<string, string | undefined>>
|
||||
): NormalizedPoolSetup {
|
||||
): PoolConfig {
|
||||
if (typeof config !== 'object' || config === null) {
|
||||
throw new ResearchCopilotExecutorError(
|
||||
'INVALID_CONFIG',
|
||||
|
|
@ -376,6 +284,7 @@ function parseAndNormalizePoolConfig(
|
|||
|
||||
const { url: parsed, usedDummyHost } = parsePostgresUrlStrict(config.postgresUrl);
|
||||
|
||||
let decodedHostname = '';
|
||||
try {
|
||||
if (parsed.username.length > 0) {
|
||||
decodeURIComponent(parsed.username);
|
||||
|
|
@ -384,7 +293,7 @@ function parseAndNormalizePoolConfig(
|
|||
decodeURIComponent(parsed.password);
|
||||
}
|
||||
if (!usedDummyHost && parsed.hostname.length > 0) {
|
||||
decodeURIComponent(parsed.hostname);
|
||||
decodedHostname = decodeURIComponent(parsed.hostname).trim();
|
||||
}
|
||||
} catch {
|
||||
throw new ResearchCopilotExecutorError(
|
||||
|
|
@ -393,26 +302,28 @@ function parseAndNormalizePoolConfig(
|
|||
);
|
||||
}
|
||||
|
||||
// Match pg-connection-string precedence: query ?port=... takes precedence over authority port.
|
||||
const queryPort = getLastExactQueryParam(parsed, 'port');
|
||||
const effectivePort = queryPort && queryPort.length > 0 ? queryPort : parsed.port;
|
||||
if (effectivePort.length > 0) {
|
||||
assertValidPort(effectivePort);
|
||||
}
|
||||
if (parsed.port.length > 0) {
|
||||
const portNum = Number(parsed.port);
|
||||
if (!Number.isInteger(portNum) || portNum < 1 || portNum > 65535) {
|
||||
throw new ResearchCopilotExecutorError(
|
||||
'INVALID_CONFIG',
|
||||
'Invalid PostgreSQL configuration: URL port must be an integer between 1 and 65535.'
|
||||
);
|
||||
}
|
||||
assertValidPort(parsed.port);
|
||||
}
|
||||
|
||||
const queryHost = parsed.searchParams.get('host')?.trim() ?? '';
|
||||
const queryHostAddr = parsed.searchParams.get('hostaddr')?.trim() ?? '';
|
||||
const effectiveHostname = usedDummyHost ? '' : parsed.hostname.trim();
|
||||
if (effectiveHostname.length === 0 && queryHost.length === 0 && queryHostAddr.length === 0) {
|
||||
// Match pg-connection-string precedence: query ?host=... takes precedence over authority host.
|
||||
// pg does not resolve hostaddr as a fallback host.
|
||||
const queryHost = getLastExactQueryParam(parsed, 'host')?.trim() ?? '';
|
||||
const effectiveHost = queryHost.length > 0 ? queryHost : decodedHostname;
|
||||
if (effectiveHost.length === 0) {
|
||||
throw new ResearchCopilotExecutorError(
|
||||
'INVALID_CONFIG',
|
||||
'Invalid PostgreSQL configuration: URL must specify a host or Unix socket host parameter.'
|
||||
);
|
||||
}
|
||||
|
||||
// Match pg-connection-string: pg reads the database strictly from the URL pathname (never ?dbname=).
|
||||
let decodedDatabase = '';
|
||||
try {
|
||||
decodedDatabase =
|
||||
|
|
@ -423,16 +334,13 @@ function parseAndNormalizePoolConfig(
|
|||
'Invalid PostgreSQL configuration: URL database name contains invalid percent-encoding.'
|
||||
);
|
||||
}
|
||||
const queryDbName = parsed.searchParams.get('dbname')?.trim() ?? '';
|
||||
if (decodedDatabase.length === 0 && queryDbName.length === 0) {
|
||||
if (decodedDatabase.length === 0) {
|
||||
throw new ResearchCopilotExecutorError(
|
||||
'INVALID_CONFIG',
|
||||
'Invalid PostgreSQL configuration: URL must specify a non-empty database name.'
|
||||
'Invalid PostgreSQL configuration: URL must specify a non-empty database name in the path.'
|
||||
);
|
||||
}
|
||||
|
||||
const secretNeedles = collectSecretNeedles(config.postgresUrl, parsed);
|
||||
|
||||
const urlOptions: string[] = [];
|
||||
const keysToDelete: string[] = [];
|
||||
for (const [key, value] of parsed.searchParams.entries()) {
|
||||
|
|
@ -455,7 +363,7 @@ function parseAndNormalizePoolConfig(
|
|||
normalizedConnectionString = normalizedConnectionString.replace('@___DUMMY_HOST___/', '@/');
|
||||
}
|
||||
|
||||
const poolConfig: PoolConfig = {
|
||||
return {
|
||||
connectionString: normalizedConnectionString,
|
||||
options: normalizedOptions,
|
||||
max: RESEARCH_COPILOT_PG_POOL_MAX,
|
||||
|
|
@ -464,8 +372,6 @@ function parseAndNormalizePoolConfig(
|
|||
query_timeout: RESEARCH_COPILOT_PG_QUERY_TIMEOUT_MS,
|
||||
lock_timeout: RESEARCH_COPILOT_PG_LOCK_TIMEOUT_MS,
|
||||
};
|
||||
|
||||
return { poolConfig, secretNeedles };
|
||||
}
|
||||
|
||||
/**
|
||||
|
|
@ -477,7 +383,7 @@ export async function openResearchCopilotExecutor(
|
|||
options?: OpenResearchCopilotExecutorOptions
|
||||
): Promise<ManagedResearchCopilotExecutor> {
|
||||
const env = options?.env ?? process.env;
|
||||
const { poolConfig, secretNeedles } = parseAndNormalizePoolConfig(config, env);
|
||||
const poolConfig = parseAndNormalizePoolConfig(config, env);
|
||||
|
||||
const createPool =
|
||||
options?.createPool ?? ((cfg: PoolConfig): ResearchCopilotPoolLike => new Pool(cfg));
|
||||
|
|
@ -492,16 +398,14 @@ export async function openResearchCopilotExecutor(
|
|||
);
|
||||
}
|
||||
|
||||
const handleIdlePoolError = (error: Error): void => {
|
||||
const handleIdlePoolError = (_error: Error): void => {
|
||||
if (options?.onPoolError === undefined) {
|
||||
return;
|
||||
}
|
||||
const safeError = isErrorSafeToSurface(error, secretNeedles)
|
||||
? error
|
||||
: new ResearchCopilotExecutorError(
|
||||
'POOL_ERROR',
|
||||
'PostgreSQL research copilot pool encountered an idle client error.'
|
||||
);
|
||||
const safeError = new ResearchCopilotExecutorError(
|
||||
'POOL_ERROR',
|
||||
'PostgreSQL research copilot pool encountered an idle client error.'
|
||||
);
|
||||
try {
|
||||
options.onPoolError(safeError);
|
||||
} catch {
|
||||
|
|
@ -543,14 +447,11 @@ export async function openResearchCopilotExecutor(
|
|||
const result = await pool.query(text, params === undefined ? undefined : [...params]);
|
||||
return { rows: result.rows as readonly Row[] };
|
||||
} catch (error) {
|
||||
if (isErrorSafeToSurface(error, secretNeedles)) {
|
||||
throw error;
|
||||
}
|
||||
const sqlState = extractSqlState(error);
|
||||
if (sqlState !== undefined) {
|
||||
const replaySqlState = extractFindingReplaySqlState(error);
|
||||
if (replaySqlState !== undefined) {
|
||||
const sanitized = new Error('PostgreSQL research copilot query failed.');
|
||||
Object.defineProperty(sanitized, 'code', {
|
||||
value: sqlState,
|
||||
value: replaySqlState,
|
||||
enumerable: true,
|
||||
configurable: true,
|
||||
});
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue