/
athenaExpress.js
237 lines (213 loc) · 5.58 KB
/
athenaExpress.js
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
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
"use strict";
const COST_PER_MB = 0.000004768, //Based on $5/TB
BYTES_IN_MB = 1048576,
COST_FOR_10MB = COST_PER_MB * 10;
const readline = require("readline"),
csv = require("csvtojson");
module.exports = class AthenaExpress {
constructor(init) {
validateConstructor(init);
this.config = {
athena: new init.aws.Athena({ apiVersion: "2017-05-18" }),
s3: new init.aws.S3({ apiVersion: "2006-03-01" }),
s3Bucket:
init.s3 ||
`s3://athena-express-${init.aws.config.credentials.accessKeyId
.substring(0, 10)
.toLowerCase()}-${new Date().getFullYear()}`,
db: init.db || "default",
retry: Number(init.retry) || 200,
formatJson: init.formatJson === false ? false : true,
getStats: init.getStats,
ignoreEmpty: init.ignoreEmpty === false ? false : true
};
}
async query(query) {
const config = this.config;
let results = {};
if (!config)
throw new TypeError("Config object not present in the constructor");
if (!query) throw new TypeError("SQL query is missing");
try {
const queryExecutionId = await startQueryExecution(query, config);
const queryStatus = await checkIfExecutionCompleted(
queryExecutionId,
config
);
const s3Output =
queryStatus.QueryExecution.ResultConfiguration
.OutputLocation,
statementType = queryStatus.QueryExecution.StatementType;
results.Items = await getQueryResultsFromS3({
s3Output,
statementType,
config
});
if (config.getStats) {
const dataInMb = Math.round(
queryStatus.QueryExecution.Statistics.DataScannedInBytes /
BYTES_IN_MB
);
results.DataScannedInMB = dataInMb;
results.QueryCostInUSD =
dataInMb > 10 ? dataInMb * COST_PER_MB : COST_FOR_10MB;
results.EngineExecutionTimeInMillis =
queryStatus.QueryExecution.Statistics.EngineExecutionTimeInMillis;
results.Count = results.Items.length;
}
return results;
} catch (error) {
throw new Error(error);
}
}
};
function startQueryExecution(query, config) {
const QueryString = query.sql || query;
const params = {
QueryString,
ResultConfiguration: {
OutputLocation: config.s3Bucket
},
QueryExecutionContext: {
Database: query.db || config.db
}
};
return new Promise(function(resolve, reject) {
const startQueryExecutionRecursively = async function() {
try {
let data = await config.athena
.startQueryExecution(params)
.promise();
resolve(data.QueryExecutionId);
} catch (err) {
isCommonAthenaError(err.code)
? setTimeout(() => {
startQueryExecutionRecursively();
}, 2000)
: reject(err);
}
};
startQueryExecutionRecursively();
});
}
function checkIfExecutionCompleted(QueryExecutionId, config) {
let retry = config.retry;
return new Promise(function(resolve, reject) {
const keepCheckingRecursively = async function() {
try {
let data = await config.athena
.getQueryExecution({ QueryExecutionId })
.promise();
if (data.QueryExecution.Status.State === "SUCCEEDED") {
retry = config.retry;
resolve(data);
} else if (data.QueryExecution.Status.State === "FAILED") {
reject(data.QueryExecution.Status.StateChangeReason);
} else {
setTimeout(() => {
keepCheckingRecursively();
}, retry);
}
} catch (err) {
if (isCommonAthenaError(err.code)) {
retry = 2000;
setTimeout(() => {
keepCheckingRecursively();
}, retry);
} else reject(err);
}
};
keepCheckingRecursively();
});
}
function getQueryResultsFromS3(params) {
const s3Params = {
Bucket: params.s3Output.split("/")[2],
Key: params.s3Output
.split("/")
.slice(3)
.join("/")
},
input = params.config.s3.getObject(s3Params).createReadStream();
if (params.config.formatJson) {
return params.statementType === "UTILITY" ||
params.statementType === "DDL"
? cleanUpNonDML(input)
: cleanUpDML(input, params.config.ignoreEmpty);
} else {
return getRawResultsFromS3(input);
}
}
function getRawResultsFromS3(input) {
let rawJson = [];
return new Promise(function(resolve, reject) {
readline
.createInterface({ input })
.on("line", line => {
rawJson.push(line.trim());
})
.on("close", function() {
resolve(rawJson);
});
});
}
function cleanUpDML(input, ignoreEmpty) {
let cleanJson = [];
return new Promise(function(resolve, reject) {
input.pipe(
csv({ ignoreEmpty })
.on("data", data => {
cleanJson.push(JSON.parse(data.toString("utf8")));
})
.on("finish", function() {
resolve(cleanJson);
})
);
});
}
function cleanUpNonDML(input) {
let cleanJson = [];
return new Promise(function(resolve, reject) {
readline
.createInterface({ input })
.on("line", line => {
switch (true) {
case line.indexOf("\t") > 0:
line = line.split("\t");
cleanJson.push({
[line[0].trim()]: line[1].trim()
});
break;
default:
if (line.trim().length) {
cleanJson.push({
row: line.trim()
});
}
}
})
.on("close", function() {
resolve(cleanJson);
});
});
}
function validateConstructor(init) {
if (!init)
throw new TypeError("Config object not present in the constructor");
try {
let aws = init.s3 ? init.s3 : init.aws.config.credentials.accessKeyId;
let athena = new init.aws.Athena({ apiVersion: "2017-05-18" });
} catch (e) {
throw new TypeError(
"AWS object not present or incorrect in the constructor"
);
}
}
function isCommonAthenaError(err) {
return err === "TooManyRequestsException" ||
err === "ThrottlingException" ||
err === "NetworkingError" ||
err === "UnknownEndpoint"
? true
: false;
}