From cadd9f3c7bc448c944eab008f9b50155a9012035 Mon Sep 17 00:00:00 2001 From: vrtnd Date: Wed, 4 Sep 2024 12:40:57 +0300 Subject: [PATCH] close idle connection --- src/handlers/runAllAdapters.ts | 2 ++ src/handlers/runAllAdaptersHistorical.ts | 2 ++ src/utils/wrappa/postgres/write.ts | 21 +++++++++++++++++++++ 3 files changed, 25 insertions(+) diff --git a/src/handlers/runAllAdapters.ts b/src/handlers/runAllAdapters.ts index a74da907..8a31b51e 100644 --- a/src/handlers/runAllAdapters.ts +++ b/src/handlers/runAllAdapters.ts @@ -3,6 +3,7 @@ import bridgeNetworks from "../data/bridgeNetworkData"; import { LambdaClient, InvokeCommand } from "@aws-sdk/client-lambda"; import { sql } from "../utils/db"; import { store } from "../utils/s3"; +import { closeIdleConnections } from "../utils/wrappa/postgres/write"; const lambdaClient = new LambdaClient({}); @@ -24,6 +25,7 @@ async function invokeLambda(functionName: string, event: any) { } export default wrapScheduledLambda(async (event) => { + await closeIdleConnections(); const lastRecordedBlocks = await sql`SELECT jsonb_object_agg(bridge_id::text, subresult) as result FROM ( SELECT bridge_id, jsonb_build_object('startBlock', MIN(tx_block), 'endBlock', MAX(tx_block)) as subresult diff --git a/src/handlers/runAllAdaptersHistorical.ts b/src/handlers/runAllAdaptersHistorical.ts index 8e31f76b..7c9fcaf9 100644 --- a/src/handlers/runAllAdaptersHistorical.ts +++ b/src/handlers/runAllAdaptersHistorical.ts @@ -1,6 +1,7 @@ import { wrapScheduledLambda } from "../utils/wrap"; import bridgeNetworks from "../data/bridgeNetworkData"; import { LambdaClient, InvokeCommand } from "@aws-sdk/client-lambda"; +import { closeIdleConnections } from "../utils/wrappa/postgres/write"; const lambdaClient = new LambdaClient({}); @@ -22,6 +23,7 @@ async function invokeLambda(functionName: string, event: any) { } const handler = async (_event: any) => { + await closeIdleConnections(); const now = Math.floor(Date.now() / 1000); const oneDayAgo = now - 86400; const halfDayAgo = now - 43200; diff --git a/src/utils/wrappa/postgres/write.ts b/src/utils/wrappa/postgres/write.ts index 9823f97e..7b70635d 100644 --- a/src/utils/wrappa/postgres/write.ts +++ b/src/utils/wrappa/postgres/write.ts @@ -274,3 +274,24 @@ export const insertErrorRow = async (params: { } } }; + +export const closeIdleConnections = async (idleTimeMinutes = 3) => { + try { + const result = await sql` + WITH closed AS ( + SELECT pg_terminate_backend(pid) + FROM pg_stat_activity + WHERE state = 'idle' + AND state_change < NOW() - INTERVAL '${idleTimeMinutes} minutes' + AND pid <> pg_backend_pid() + ) + SELECT COUNT(*) as closed_count FROM closed; + `; + + const closedCount = parseInt(result[0].closed_count); + console.log(`${closedCount} idle connection(s) closed successfully. (Idle time: ${idleTimeMinutes} minutes)`); + return closedCount; + } catch (error) { + console.error(`Error closing idle connections (Idle time: ${idleTimeMinutes} minutes):`, error); + } +};