-
Notifications
You must be signed in to change notification settings - Fork 0
/
query.ts
147 lines (125 loc) · 5 KB
/
query.ts
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
// MIT License
//
// Copyright (c) 2023 Tobi
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
//
// Slightly modified version from: https://github.com/tobilg/serverless-duckdb
import DuckDB, { DuckDbError, TableData } from 'duckdb';
import bunyan from 'bunyan';
import { getLogLevel } from './utils/logger';
import { metricScope, MetricsLogger, Unit } from 'aws-embedded-metrics';
import { renderResults } from './utils/resultsFormatter';
// Instantiate logger
const logger = bunyan.createLogger({
name: 'duckdb-lambda-logger',
level: getLogLevel()
});
// Instantiate DuckDB
const duckDB = new DuckDB.Database(':memory:', { allow_unsigned_extensions: 'true' });
// Create connection
const connection = duckDB.connect();
// Store initialization
let isInitialized = false;
// Promisify query method
async function query(sql: string): Promise<TableData> {
return new Promise((resolve, reject) => {
connection.all(sql, (err: DuckDbError | null, res: TableData) => {
if (err) reject(err);
resolve(res);
});
});
}
// SIGTERM Handler
process.on('SIGTERM', async () => {
console.debug('[runtime] SIGTERM received');
process.exit(0);
});
// todo: figure out types for event and context
export const handler = metricScope((metrics: MetricsLogger) => async (event: any, context: any) => {
// Setup logger
const requestLogger = logger.child({ requestId: context.awsRequestId });
requestLogger.debug({ event, context });
// Setup metrics
metrics.putDimensions({ Service: 'QueryService' });
metrics.setProperty('RequestId', context.awsRequestId);
const sql = event.query;
if (!sql) {
throw 'Missing query property in request body!';
}
// Check if DuckDB has been initalized
if (!isInitialized) {
const initialSetupStartTimestamp = new Date().getTime();
// Load httpsfs
await query(`SET home_directory='/tmp';`);
// Hint: INSTALL httpfs; is no longer needed, as it's now in the static build starting from layer version 6
await query(`LOAD httpfs;`);
// Whether or not the global http metadata is used to cache HTTP metadata, see https://github.com/duckdb/duckdb/pull/5405
await query(`SET enable_http_metadata_cache=true;`);
// Whether or not object cache is used to cache e.g. Parquet metadata
await query(`SET enable_object_cache=true;`);
requestLogger.debug({ message: 'Initial setup done!' });
metrics.putMetric('InitialSetupDuration', new Date().getTime() - initialSetupStartTimestamp, Unit.Milliseconds);
const awsSetupStartTimestamp = new Date().getTime();
// Set AWS credentials
// See https://docs.aws.amazon.com/lambda/latest/dg/configuration-envvars.html#configuration-envvars-runtime
// await query(`SET s3_region='${process.env.AWS_REGION}';`);
// await query(`SET s3_access_key_id='${process.env.AWS_ACCESS_KEY_ID}';`);
// await query(`SET s3_secret_access_key='${process.env.AWS_SECRET_ACCESS_KEY}';`);
// await query(`SET s3_session_token='${process.env.AWS_SESSION_TOKEN}';`);
requestLogger.debug({ message: 'AWS setup done!' });
metrics.putMetric('AWSSetupDuration', new Date().getTime() - awsSetupStartTimestamp, Unit.Milliseconds);
// Store initialization
isInitialized = true;
}
// Track query start timestamp
const queryStartTimestamp = new Date().getTime();
try {
// Run query
const queryResult = await query(sql);
const queryTimeMs = new Date().getTime() - queryStartTimestamp;
metrics.putMetric('QueryDuration', queryTimeMs, Unit.Milliseconds);
return {
statusCode: 200,
body: renderResults(
{
timeMs: queryTimeMs,
count: queryResult.length,
result: queryResult,
error: null
},
sql
)
};
} catch (err: any) {
requestLogger.error(err);
return {
statusCode: 400,
body: renderResults(
{
timeMs: new Date().getTime() - queryStartTimestamp,
count: null,
result: null,
error: err.message
},
sql
)
};
}
});