@onivoro/server-aws-redshift 24.13.0 → 24.14.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/jest.config.ts ADDED
@@ -0,0 +1,11 @@
1
+ /* eslint-disable */
2
+ export default {
3
+ displayName: 'lib-server-aws-redshift',
4
+ preset: '../../../jest.preset.js',
5
+ testEnvironment: 'node',
6
+ transform: {
7
+ '^.+\\.[tj]s$': ['ts-jest', { tsconfig: '<rootDir>/tsconfig.spec.json' }],
8
+ },
9
+ moduleFileExtensions: ['ts', 'js', 'html'],
10
+ coverageDirectory: '../../../coverage/libs/server/aws-redshift',
11
+ };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@onivoro/server-aws-redshift",
3
- "version": "24.13.0",
3
+ "version": "24.14.0",
4
4
  "type": "commonjs",
5
5
  "main": "./index.js",
6
6
  "types": "./index.d.ts",
@@ -9,8 +9,8 @@
9
9
  "url": "https://github.com/onivoro/monorepo.git"
10
10
  },
11
11
  "dependencies": {
12
- "@onivoro/server-aws-credential-providers": "24.13.0",
13
- "@onivoro/server-common": "24.13.0",
12
+ "@onivoro/server-aws-credential-providers": "24.14.0",
13
+ "@onivoro/server-common": "24.14.0",
14
14
  "tslib": "^2.3.0"
15
15
  },
16
16
  "peerDependencies": {
@@ -18,11 +18,5 @@
18
18
  "@aws-sdk/client-redshift-data": "~3.782.0",
19
19
  "@aws-sdk/client-redshift-serverless": "~3.782.0",
20
20
  "@nestjs/common": "~10.4.6"
21
- },
22
- "files": [
23
- "**/*.js",
24
- "**/*.d.ts",
25
- "**/*.js.map",
26
- "README.md"
27
- ]
21
+ }
28
22
  }
package/project.json ADDED
@@ -0,0 +1,33 @@
1
+ {
2
+ "name": "lib-server-aws-redshift",
3
+ "$schema": "../../../node_modules/nx/schemas/project-schema.json",
4
+ "sourceRoot": "libs/server/aws-redshift/src",
5
+ "projectType": "library",
6
+ "targets": {
7
+ "build": {
8
+ "executor": "@nx/js:tsc",
9
+ "outputs": ["{options.outputPath}"],
10
+ "options": {
11
+ "outputPath": "dist/libs/server/aws-redshift",
12
+ "main": "libs/server/aws-redshift/src/index.ts",
13
+ "tsConfig": "libs/server/aws-redshift/tsconfig.lib.json",
14
+ "assets": [
15
+ "libs/server/aws-redshift/README.md",
16
+ "libs/server/aws-redshift/package.json"
17
+ ],
18
+ "declaration": true,
19
+ "updateBuildableProjectPackageJsonDependencies": true,
20
+ "rootDir": "libs/server/aws-redshift/src"
21
+ }
22
+ },
23
+ "publish": {
24
+ "executor": "@nx/js:npm",
25
+ "outputs": [],
26
+ "dependsOn": ["build"],
27
+ "options": {
28
+ "packageRoot": "dist/libs/server/aws-redshift"
29
+ }
30
+ }
31
+ },
32
+ "tags": []
33
+ }
package/src/index.ts ADDED
@@ -0,0 +1,5 @@
1
+ export * from './lib/classes/server-aws-redshift-config.class';
2
+
3
+ export * from './lib/services/redshift.service';
4
+
5
+ export * from './lib/server-aws-redshift.module';
@@ -0,0 +1,4 @@
1
+ export class ServerAwsRedshiftDataConfig {
2
+ AWS_PROFILE?: string;
3
+ AWS_REGION: string;
4
+ }
@@ -0,0 +1,56 @@
1
+ import { Module } from '@nestjs/common';
2
+ import { moduleFactory } from '@onivoro/server-common';
3
+ import { RedshiftDataClient, RedshiftDataClientConfig } from '@aws-sdk/client-redshift-data';
4
+ import { RedshiftDataService } from './services/redshift.service';
5
+ import { ServerAwsRedshiftDataConfig } from './classes/server-aws-redshift-config.class';
6
+ import { RedshiftServerlessClient } from '@aws-sdk/client-redshift-serverless';
7
+ import { RedshiftClient } from '@aws-sdk/client-redshift';
8
+ import { AwsCredentials, ServerAwsCredentialProvidersModule } from '@onivoro/server-aws-credential-providers';
9
+
10
+ let redshiftClient: RedshiftClient | null = null;
11
+ let redshiftDataClient: RedshiftDataClient | null = null;
12
+ let redshiftServerlessClient: RedshiftServerlessClient | null = null;
13
+
14
+
15
+ @Module({})
16
+ export class ServerAwsRedshiftDataModule {
17
+ static configure(config: ServerAwsRedshiftDataConfig) {
18
+ return moduleFactory({
19
+ module: ServerAwsRedshiftDataModule,
20
+ imports: [ServerAwsCredentialProvidersModule.configure(config)],
21
+ providers: [
22
+ {
23
+ provide: RedshiftDataClient,
24
+ useFactory: (credentials: AwsCredentials) => redshiftDataClient
25
+ ? redshiftDataClient
26
+ : redshiftDataClient = new RedshiftDataClient(from(config, credentials)),
27
+ inject: [AwsCredentials]
28
+ },
29
+ {
30
+ provide: RedshiftServerlessClient,
31
+ useFactory: (credentials: AwsCredentials) => redshiftServerlessClient
32
+ ? redshiftServerlessClient
33
+ : redshiftServerlessClient = new RedshiftServerlessClient(from(config, credentials)),
34
+ inject: [AwsCredentials]
35
+ },
36
+ {
37
+ provide: RedshiftClient,
38
+ useFactory: (credentials: AwsCredentials) => redshiftClient
39
+ ? redshiftClient
40
+ : redshiftClient = new RedshiftClient(from(config, credentials)),
41
+ inject: [AwsCredentials]
42
+ },
43
+ { provide: ServerAwsRedshiftDataConfig, useValue: config },
44
+ RedshiftDataService
45
+ ]
46
+ })
47
+ }
48
+ }
49
+
50
+ function from(config: ServerAwsRedshiftDataConfig, credentials: AwsCredentials): RedshiftDataClientConfig {
51
+ return {
52
+ region: config.AWS_REGION,
53
+ logger: console,
54
+ credentials
55
+ };
56
+ }
@@ -0,0 +1,293 @@
1
+ import { Injectable } from '@nestjs/common';
2
+ import { DescribeStatementCommand, ExecuteStatementCommand, GetStatementResultCommand, RedshiftDataClient } from "@aws-sdk/client-redshift-data";
3
+ import { GetWorkgroupCommand, GetWorkgroupCommandInput, RedshiftServerlessClient } from '@aws-sdk/client-redshift-serverless';
4
+ import { randomUUID } from 'crypto';
5
+
6
+ @Injectable()
7
+ export class RedshiftDataService {
8
+ constructor(
9
+ private redshiftDataClient: RedshiftDataClient,
10
+ private redshiftServerlessClient: RedshiftServerlessClient,
11
+ ) { }
12
+
13
+ async waitForStatement(statementId: string, maxAttempts = 10, delay = 1000) {
14
+ let attempts = 0;
15
+
16
+ while (attempts < maxAttempts) {
17
+ const describeStatementCommand = new DescribeStatementCommand({
18
+ Id: statementId
19
+ });
20
+
21
+ const status = await this.redshiftDataClient.send(describeStatementCommand);
22
+
23
+ if (status.Status === 'FINISHED') {
24
+ return status.ResultRows;
25
+ }
26
+
27
+ if (status.Status === 'FAILED') {
28
+ throw new Error(`SQL statement failed: ${status.Error}`);
29
+ }
30
+
31
+ attempts++;
32
+ await new Promise(resolve => setTimeout(resolve, delay));
33
+ }
34
+
35
+ throw new Error('Timeout waiting for SQL statement to complete');
36
+ }
37
+
38
+ async verifyEndpointAccess(workgroupName: string) {
39
+ const workgroupResponse = await this.redshiftServerlessClient.send(
40
+ new GetWorkgroupCommand({ workgroupName })
41
+ );
42
+
43
+ if (!workgroupResponse?.workgroup?.endpoint?.address) {
44
+ console.error(`Could not retrieve endpoint for workgroupName "${workgroupName}"`);
45
+
46
+ return;
47
+ }
48
+
49
+ return workgroupResponse;
50
+ }
51
+
52
+ async addIamUserToDatabaseGroup(_: { database: string, workgroupName: string, user: string, group: string }) {
53
+ try {
54
+ const groupResult = await this.redshiftDataClient.send(new ExecuteStatementCommand({
55
+ Database: _.database,
56
+ Sql: `ALTER GROUP ${_.group} ADD USER "${_.user}";`,
57
+ WorkgroupName: _.workgroupName
58
+ }));
59
+
60
+ await this.waitForStatement(groupResult.Id!);
61
+
62
+ console.log(`Added user "${_.user}" to group "${_.group}`);
63
+ } catch (error: any) {
64
+ console.warn({ detail: `Warning adding ${_.user} to group:`, error });
65
+ }
66
+ }
67
+
68
+ async createDatabaseUser(_: { database: string, workgroupName: string, user: string }): Promise<string> {
69
+ try {
70
+
71
+ const checkResult = await this.redshiftDataClient.send(new ExecuteStatementCommand({
72
+ Database: _.database,
73
+ Sql: `SELECT u.usename as username FROM pg_user u;`,
74
+ WorkgroupName: _.workgroupName
75
+ }));
76
+
77
+ await this.waitForStatement(checkResult.Id!);
78
+
79
+ const describeCommand = new DescribeStatementCommand({ Id: checkResult.Id });
80
+ const checkStatus = await this.redshiftDataClient.send(describeCommand);
81
+
82
+ if (!checkStatus.ResultRows) {
83
+ const placeholderPassword = `IAM_${randomUUID().replace(/-/g, '_')}`;
84
+
85
+ const createUserCommand = new ExecuteStatementCommand({
86
+ Database: _.database,
87
+ Sql: `CREATE USER ${_.user} PASSWORD '${placeholderPassword}';`,
88
+ WorkgroupName: _.workgroupName
89
+ });
90
+
91
+ const createResult = await this.redshiftDataClient.send(createUserCommand);
92
+
93
+ await this.waitForStatement(createResult.Id!);
94
+
95
+ console.log(`Created user: ${_.user}`);
96
+
97
+ return placeholderPassword;
98
+ } else {
99
+ console.log(`User "${_.user} already exists`);
100
+
101
+ return '';
102
+ }
103
+
104
+ } catch (error: any) {
105
+ console.warn({ detail: `Warning creating user ${_.user}`, error });
106
+ throw error;
107
+ }
108
+ }
109
+
110
+ async grantUsageOnSchema(_: { database: string, workgroupName: string, schema: string, group: string }) {
111
+
112
+ try {
113
+ const setupStatements = [
114
+ `GRANT USAGE ON SCHEMA ${_.schema} TO GROUP ${_.group};`,
115
+ `GRANT SELECT ON ALL TABLES IN SCHEMA ${_.schema} TO GROUP ${_.group};`,
116
+ `ALTER DEFAULT PRIVILEGES IN SCHEMA ${_.schema} GRANT SELECT ON TABLES TO GROUP ${_.group};`,
117
+ ];
118
+
119
+ for (const Sql of setupStatements) {
120
+ const executeStatementCommand = new ExecuteStatementCommand({
121
+ Database: _.database,
122
+ Sql,
123
+ WorkgroupName: _.workgroupName
124
+ });
125
+
126
+ try {
127
+ const result = await this.redshiftDataClient.send(executeStatementCommand);
128
+ await this.waitForStatement(result.Id!);
129
+ } catch (error: any) {
130
+ console.warn({ Sql, error });
131
+ }
132
+ }
133
+
134
+ } catch (error) {
135
+ console.error({ error });
136
+ throw error;
137
+ }
138
+ }
139
+
140
+ async createDbGroupFromIamGroupIfNotExists(_: { iamGroup: string, database: string, workgroupName: string }): Promise<any> {
141
+
142
+ try {
143
+ const checkResult = await this.redshiftDataClient.send(new ExecuteStatementCommand({
144
+ Database: _.database,
145
+ Sql: `SELECT 1 FROM pg_group WHERE groname = '${_.iamGroup}';`,
146
+ WorkgroupName: _.workgroupName
147
+ }));
148
+
149
+ await this.waitForStatement(checkResult.Id!);
150
+
151
+ const describeCommand = new DescribeStatementCommand({ Id: checkResult.Id });
152
+ const checkStatus = await this.redshiftDataClient.send(describeCommand);
153
+
154
+ if (!checkStatus.ResultRows) {
155
+ const createGroupCommand = new ExecuteStatementCommand({
156
+ Database: _.database,
157
+ Sql: `CREATE GROUP ${_.iamGroup};`,
158
+ WorkgroupName: _.workgroupName
159
+ });
160
+
161
+ const createResult = await this.redshiftDataClient.send(createGroupCommand);
162
+ await this.waitForStatement(createResult.Id!);
163
+ console.log(`Created "${_.iamGroup}" group`);
164
+ } else {
165
+ console.log(`"${_.iamGroup}" group already exists`);
166
+ }
167
+ } catch (error: any) {
168
+ console.error({ error });
169
+ throw error;
170
+ }
171
+ }
172
+
173
+ async queryV1(_: { database: string, workgroupName: string }, Sql: string) {
174
+ const result = await this.redshiftDataClient.send(new ExecuteStatementCommand({
175
+ Database: _.database,
176
+ Sql,
177
+ WorkgroupName: _.workgroupName
178
+ }));
179
+
180
+ return await this.waitForStatement(result.Id!);
181
+ }
182
+
183
+
184
+ async query(_: { database: string, workgroupName: string }, Sql: string) {
185
+ try {
186
+ const executeCommand = new ExecuteStatementCommand({
187
+ Database: _.database,
188
+ Sql,
189
+ WorkgroupName: _.workgroupName,
190
+ });
191
+
192
+ const { Id } = await this.redshiftDataClient.send(executeCommand);
193
+
194
+ if (!Id) {
195
+ throw new Error("Failed to get statement ID");
196
+ }
197
+
198
+ let status = "";
199
+
200
+ do {
201
+ const describeCommand = new DescribeStatementCommand({ Id });
202
+ const { Status, Error: err } = await this.redshiftDataClient.send(describeCommand);
203
+ status = Status || "";
204
+
205
+ if (status === "FAILED") {
206
+ throw new Error(err);
207
+ }
208
+
209
+ if (status !== "FINISHED") {
210
+ await new Promise(resolve => setTimeout(resolve, 1000));
211
+ }
212
+ } while (status !== "FINISHED");
213
+
214
+ try {
215
+ const getResultsCommand = new GetStatementResultCommand({ Id });
216
+ const results = await this.redshiftDataClient.send(getResultsCommand);
217
+
218
+ const records = results.Records || [];
219
+ return records.map(record => {
220
+ return record.map(field => field.stringValue || field.longValue || field.doubleValue);
221
+ });
222
+ } catch (error) {
223
+ return [];
224
+ }
225
+ } catch (error) {
226
+ console.error({ detail: "Error executing query:", error });
227
+ throw error;
228
+ }
229
+ }
230
+
231
+ async getAssociatedIAmRolesByWorkgroup(_: { database: string, workgroupName: string }) {
232
+ try {
233
+ const query = `
234
+ SELECT
235
+ g.groname as role_name,
236
+ u.usename as member_name,
237
+ g.grosysid as role_id,
238
+ g.groowner as owner_id,
239
+ CASE WHEN pg_has_role(u.usename, g.groname, 'MEMBER') THEN true ELSE false END as is_member
240
+ FROM pg_group g
241
+ LEFT JOIN pg_user u ON u.usesysid = ANY(g.grolist)
242
+ WHERE EXISTS (
243
+ SELECT 1
244
+ FROM svv_redshift_databases d
245
+ WHERE d.database_name = current_database()
246
+ AND d.workgroup_name = $1
247
+ )
248
+ ORDER BY g.groname, u.usename;
249
+ `;
250
+
251
+ return await this.query(_, query)
252
+ } catch (error) {
253
+ if (error instanceof Error) {
254
+ console.error(`Error getting workgroup roles: ${error.message}`);
255
+ throw error;
256
+ }
257
+ throw new Error('An unknown error occurred');
258
+ }
259
+ }
260
+
261
+ private async upsert<TValue>(_: { database: string, workgroupName: string }, value: TValue, tableQualifiers: { schema: string, table: string }) {
262
+ const { table, schema } = tableQualifiers;
263
+ // TODO: dynamically build out the select/insert clauses dynamically
264
+ // try {
265
+ // const upsertQuery = `
266
+ // WITH ${table}_x AS (SELECT '${value.user_id}' as user_id, '${value.profile_id}' as profile_id, '${value.email}' as email, '${value.date}' as date, '${value.weight}' as weight, '${value.source}' as source, '${value.created_at}' as created_at)
267
+ // UPDATE ${schema}.${table}
268
+ // SET
269
+ // patient = a.patient,
270
+ // data = a.data
271
+ // FROM ${table}_x AS a
272
+ // WHERE ${schema}.${table}.id = a.id;
273
+
274
+ // INSERT INTO ${schema}.${table} (
275
+ // id,
276
+ // patient,
277
+ // data
278
+ // )
279
+ // SELECT
280
+ // a.id,
281
+ // a.patient,
282
+ // a.data
283
+ // FROM ${table}_x AS a
284
+ // LEFT JOIN ${schema}.${table} AS b
285
+ // ON a.id = b.id
286
+ // WHERE b.id IS NULL;`;
287
+
288
+ // return await this.query(_, upsertQuery);
289
+ // } catch (error: any) {
290
+ // console.error({ error, detail: `"${schema}.${table}" upsert failed` });
291
+ // }
292
+ }
293
+ }
package/tsconfig.json ADDED
@@ -0,0 +1,16 @@
1
+ {
2
+ "extends": "../../../tsconfig.server.json",
3
+ "compilerOptions": {
4
+ "outDir": "../../../dist/out-tsc"
5
+ },
6
+ "files": [],
7
+ "include": [],
8
+ "references": [
9
+ {
10
+ "path": "./tsconfig.lib.json"
11
+ },
12
+ {
13
+ "path": "./tsconfig.spec.json"
14
+ }
15
+ ]
16
+ }
@@ -0,0 +1,10 @@
1
+ {
2
+ "extends": "./tsconfig.json",
3
+ "compilerOptions": {
4
+ "rootDir": "./src",
5
+ "outDir": "../../dist/libs/server/aws-redshift",
6
+ "declaration": true
7
+ },
8
+ "exclude": ["jest.config.ts", "**/*.spec.ts", "**/*.test.ts"],
9
+ "include": ["src/**/*.ts"]
10
+ }
@@ -0,0 +1,21 @@
1
+ {
2
+ "extends": "./tsconfig.json",
3
+ "compilerOptions": {
4
+ "types": [
5
+ "jest",
6
+ "node"
7
+ ]
8
+ },
9
+ "include": [
10
+ "jest.config.ts",
11
+ "**/*.test.ts",
12
+ "**/*.spec.ts",
13
+ "**/*.test.tsx",
14
+ "**/*.spec.tsx",
15
+ "**/*.test.js",
16
+ "**/*.spec.js",
17
+ "**/*.test.jsx",
18
+ "**/*.spec.jsx",
19
+ "**/*.d.ts"
20
+ ]
21
+ }