Skip to content

Commit c4f024b

Browse files
committed
enabled graceful shutdowns
1 parent afea096 commit c4f024b

File tree

3 files changed

+42
-42
lines changed

3 files changed

+42
-42
lines changed

cos-to-sql/README.md

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -78,7 +78,8 @@ ibmcloud resource service-instance-create $SM_INSTANCE_NAME secrets-manager 7713
7878
7979
export SM_INSTANCE_ID=$(ibmcloud resource service-instance $SM_INSTANCE_NAME --location ${REGION} --output json | jq -r '.[0] | .id')
8080
export SM_INSTANCE_GUID=$(ibmcloud resource service-instance $SM_INSTANCE_NAME --location ${REGION} --output json | jq -r '.[0] | .guid')
81-
export SECRETS_MANAGER_URL=https://$SM_INSTANCE_GUID.${REGION}.secrets-manager.appdomain.cloud
81+
export SECRETS_MANAGER_URL=https://${SM_INSTANCE_GUID}.${REGION}.secrets-manager.appdomain.cloud
82+
export SECRETS_MANAGER_URL_PRIVATE=https://${SM_INSTANCE_GUID}.private.${REGION}.secrets-manager.appdomain.cloud
8283
```
8384

8485
* Create a S2S policy "Key Manager" between SM and the DB
@@ -116,7 +117,7 @@ ibmcloud code-engine app create \
116117
--env COS_REGION=${REGION} \
117118
--env COS_TRUSTED_PROFILE_NAME=${TRUSTED_PROFILE_FOR_COS_NAME} \
118119
--env SM_TRUSTED_PROFILE_NAME=${TRUSTED_PROFILE_FOR_SM_NAME} \
119-
--env SM_SERVICE_URL=${SECRETS_MANAGER_URL} \
120+
--env SM_SERVICE_URL=${SECRETS_MANAGER_URL_PRIVATE} \
120121
--env SM_PG_SECRET_ID=${SM_SECRET_FOR_PG_ID}
121122
```
122123

cos-to-sql/app.mjs

Lines changed: 12 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -71,6 +71,17 @@ app.use(favicon(path.join(__dirname, 'public', 'favicon.ico')))
7171
const router = express.Router();
7272
app.use("/", router);
7373

74+
75+
//
76+
// Default http endpoint, which prints the list of all users in the database
77+
router.get("/", async (req, res) => {
78+
console.log(`handling / for '${req.url}'`);
79+
const pgClient = await getPgClient(secretsManager, smPgSecretId);
80+
const allUsers = await listUsers(pgClient);
81+
res.writeHead(200, { "Content-Type": "application/json" });
82+
res.end(JSON.stringify({ users: allUsers.rows }));
83+
});
84+
7485
//
7586
// Readiness endpoint
7687
router.get("/readiness", (req, res) => {
@@ -177,15 +188,6 @@ router.get("/clear", async (req, res) => {
177188
return;
178189
});
179190

180-
//
181-
// Default http endpoint, which prints the list of all users in the database
182-
router.get("/", async (req, res) => {
183-
console.log(`handling / for '${req.url}'`);
184-
const pgClient = await getPgClient(secretsManager, smPgSecretId);
185-
const allUsers = await listUsers(pgClient);
186-
res.writeHead(200, { "Content-Type": "application/json" });
187-
res.end(JSON.stringify({ users: allUsers.rows }));
188-
});
189191

190192
// start server
191193
const port = process.env.PORT || 8080;
@@ -195,6 +197,7 @@ const server = app.listen(port, () => {
195197

196198
process.on("SIGTERM", async () => {
197199
console.info("SIGTERM signal received.");
200+
198201
await closeDBConnection();
199202

200203
server.close(() => {

cos-to-sql/utils/db.mjs

Lines changed: 27 additions & 31 deletions
Original file line numberDiff line numberDiff line change
@@ -17,42 +17,26 @@ function connectDb(connectionString, caCert) {
1717
};
1818

1919
// set up a new client using our config details
20-
let client = new Pool(postgreConfig);
20+
let pool = new Pool({ ...postgreConfig, max: 20, idleTimeoutMillis: 5000, connectionTimeoutMillis: 2000 });
2121

22-
client.connect((err) => {
23-
if (err) {
24-
console.error(`Failed to connect to postgreSQL host '${postgreConfig.host}'`, err);
25-
return reject(err);
26-
}
27-
28-
client.query(
29-
"CREATE TABLE IF NOT EXISTS users (firstname varchar(256) NOT NULL, lastname varchar(256) NOT NULL)",
30-
(err, result) => {
31-
if (err) {
32-
console.log(`Failed to create PostgreSQL table 'users'`, err);
33-
return reject(err);
34-
}
35-
console.log(
36-
`Established PostgreSQL client connection to '${postgreConfig.host}' - user table init: ${JSON.stringify(
37-
result
38-
)}`
39-
);
40-
return resolve(client);
22+
pool.query(
23+
"CREATE TABLE IF NOT EXISTS users (firstname varchar(256) NOT NULL, lastname varchar(256) NOT NULL)",
24+
(err, result) => {
25+
if (err) {
26+
console.log(`Failed to create PostgreSQL table 'users'`, err);
27+
return reject(err);
4128
}
42-
);
43-
});
29+
console.log(
30+
`Established PostgreSQL client connection to '${postgreConfig.host}' - user table init: ${JSON.stringify(
31+
result
32+
)}`
33+
);
34+
return resolve(pool);
35+
}
36+
);
4437
});
4538
}
4639

47-
export async function closeDBConnection() {
48-
if (_pgPool) {
49-
console.log("Draining PG pool.");
50-
await _pgPool.end();
51-
console.log("PG pool has drained.");
52-
}
53-
Promise.resolve();
54-
}
55-
5640
export async function getPgClient(secretsManager, secretId) {
5741
const fn = "getPgClient ";
5842
const startTime = Date.now();
@@ -81,6 +65,10 @@ export async function getPgClient(secretsManager, secretId) {
8165
const pgConnectionString = res.result.credentials.connection.postgres.composed[0];
8266
_pgPool = await connectDb(pgConnectionString, pgCaCert);
8367

68+
_pgPool.on("error", (err) => {
69+
console.log("Pool received an error event", err);
70+
});
71+
8472
console.log(`${fn} < done - duration ${Date.now() - startTime} ms`);
8573
return _pgPool;
8674
}
@@ -134,3 +122,11 @@ export function deleteUsers(client) {
134122
});
135123
});
136124
}
125+
126+
export async function closeDBConnection() {
127+
if (_pgPool) {
128+
console.log("Draining PG pool...");
129+
await _pgPool.end();
130+
console.log("PG pool has drained.");
131+
}
132+
}

0 commit comments

Comments
 (0)