forked from aws-samples/amazon-rds-init-cdk
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathindex.js
More file actions
125 lines (106 loc) · 3.36 KB
/
index.js
File metadata and controls
125 lines (106 loc) · 3.36 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: MIT-0
const mysql = require('mysql2')
const AWS = require('aws-sdk')
const fs = require('fs')
const path = require('path')
require('dotenv').config();
const DB_CONNECT_RETRY_MAX_ATTEMPTS = Number.parseInt(process.env.DB_CONNECT_RETRY_MAX_ATTEMPTS || '24', 10)
const DB_CONNECT_RETRY_DELAY_MS = Number.parseInt(process.env.DB_CONNECT_RETRY_DELAY_MS || '5000', 10)
// the env AWS_ENDPOINT_URL is automatically injected and available
const endpoint = process.env.AWS_ENDPOINT_URL;
const url = new URL(endpoint);
const hostname = url.hostname;
// configure the secretsmanager to connect to the running LocalStack instance
const secrets = new AWS.SecretsManager({
endpoint: endpoint,
accessKeyId: 'test',
secretAccessKey: 'test',
region: 'us-east-1',
})
exports.handler = async (e) => {
let connection
try {
const { config } = e.params
connection = await createConnectionWithRetry(config.credsSecretName)
const sqlScript = fs.readFileSync(path.join(__dirname, 'script.sql')).toString()
const res = await query(connection, sqlScript)
return {
status: 'OK',
results: res
}
} catch (err) {
return {
status: 'ERROR',
err,
message: err.message
}
} finally {
if (connection) {
await closeConnection(connection)
}
}
}
function query (connection, sql) {
return new Promise((resolve, reject) => {
connection.query(sql, (error, res) => {
if (error) return reject(error)
return resolve(res)
})
})
}
async function createConnectionWithRetry (connectionConfig) {
let lastError
for (let attempt = 1; attempt <= DB_CONNECT_RETRY_MAX_ATTEMPTS; attempt += 1) {
const { password, username, dbname, port } = await getSecretValue(connectionConfig)
const connection = mysql.createConnection({
host: hostname,
user: username,
database: dbname,
port,
password,
multipleStatements: true
})
try {
await connect(connection)
return connection
} catch (error) {
connection.destroy()
lastError = error
if (!shouldRetryConnectionError(error) || attempt === DB_CONNECT_RETRY_MAX_ATTEMPTS) {
break
}
const retryInSeconds = DB_CONNECT_RETRY_DELAY_MS / 1000
console.log(`Database connection attempt ${attempt}/${DB_CONNECT_RETRY_MAX_ATTEMPTS} failed (port=${port}) with '${error.code || error.message}'. Retrying in ${retryInSeconds}s...`)
await sleep(DB_CONNECT_RETRY_DELAY_MS)
}
}
throw lastError
}
function connect (connection) {
return new Promise((resolve, reject) => {
connection.connect((error) => {
if (error) return reject(error)
return resolve()
})
})
}
function shouldRetryConnectionError (error) {
return ['ECONNREFUSED', 'ETIMEDOUT', 'EHOSTUNREACH', 'ENOTFOUND', 'PROTOCOL_CONNECTION_LOST'].includes(error?.code)
}
function sleep (delayMs) {
return new Promise((resolve) => setTimeout(resolve, delayMs))
}
function closeConnection (connection) {
return new Promise((resolve) => {
connection.end(() => resolve())
})
}
function getSecretValue (secretId) {
return new Promise((resolve, reject) => {
secrets.getSecretValue({ SecretId: secretId }, (err, data) => {
if (err) return reject(err)
return resolve(JSON.parse(data.SecretString))
})
})
}