Skip to content

Instantly share code, notes, and snippets.

@krzysztof-miemiec
Created July 15, 2020 21:44
Show Gist options
  • Save krzysztof-miemiec/0a54ccba47a89f405e8fcc40cca619b9 to your computer and use it in GitHub Desktop.
Save krzysztof-miemiec/0a54ccba47a89f405e8fcc40cca619b9 to your computer and use it in GitHub Desktop.
Sample DatabaseService which supports credential rotation
import { Connection, EntitySchema, getConnectionManager } from 'typeorm';
import { Observable, Subscription } from 'rxjs';
import { distinctUntilChanged, first, map, skip } from 'rxjs/operators';
import { Injectable, OnApplicationShutdown, OnModuleDestroy, OnModuleInit } from '@nestjs/common';
import { PostgresConnectionOptions } from 'typeorm/driver/postgres/PostgresConnectionOptions';
import { ConfigurationEntity } from '../configuration/infractructure/entity/configuration.entity';
import { OfferEntity } from '../offer/infrastructure/entity/offer.entity';
import { UserEntity } from '../status/infrastructure/entity/user.entity';
import { DatabaseLogger } from '../shared/logger/database.logger';
import { LoggerService } from '../shared/logger/logger.service';
import { isEqual } from 'lodash';
import { ObjectType } from 'typeorm/common/ObjectType';
import { Config } from 'src/config/config.interface';
import { ConfigService } from '../config/config.service';
import { isLocalEnv, isTestEnv } from '../config/environment';
import { v4 as uuid } from 'uuid';
export const getDatabaseConnectionOptions = (config: Config): PostgresConnectionOptions => {
const { host, port, database, username, password } = config.postgres;
return {
// Connection Data
host,
port,
database,
username,
password,
// Postgres Configuration
type: 'postgres' as const,
uuidExtension: 'pgcrypto' as const,
// ORM Configuration
logging: isLocalEnv(),
synchronize: isLocalEnv(),
migrationsRun: !isLocalEnv(),
migrationsTableName: 'migrations',
migrations: [
isTestEnv()
? 'src/shared/infrastructure/migrations/*.ts'
: 'dist/shared/infrastructure/migrations/*.js',
],
entities: [
ConfigurationEntity,
OfferEntity,
UserEntity,
],
};
};
const meta = { context: 'DatabaseService' };
const connectionTimeout = 3 * 60 * 1000;
@Injectable()
export class DatabaseService implements OnModuleInit, OnModuleDestroy, OnApplicationShutdown {
private options$: Observable<PostgresConnectionOptions>;
private subscription: Subscription;
private logger = new DatabaseLogger({
tag: 'Postgres',
logger: this.loggerService,
});
constructor(
private configService: ConfigService,
private loggerService: LoggerService,
) {
}
get connection(): Connection {
const manager = getConnectionManager();
return manager.connections[0];
}
private get manager() {
return getConnectionManager();
}
private static async closeConnections(connections: Connection[]) {
await Promise.all(connections.map(async connection => {
if (connection.isConnected) {
await connection.close();
}
}));
return connections;
}
removeOldConnections(newConnection: Connection) {
const manager = this.manager;
const removedConnections = [
...manager.connections.splice(0, this.getConnectionIndex(newConnection)),
...manager.connections.splice(1, manager.connections.length - 1),
];
if (removedConnections.length) {
new Promise(resolve => setTimeout(resolve, connectionTimeout))
.then(() => DatabaseService.closeConnections(removedConnections))
.then(connections => this.loggerService.info(
`Closed old database connection(s): ${connections.map(c => c.name).join(', ')}`,
{ meta },
))
.catch(err => this.loggerService.error(
err.message || err,
err.stack,
{ meta },
));
}
}
getRepository<Entity>(target: ObjectType<Entity> | EntitySchema<Entity> | string) {
return this.connection.getRepository(target);
}
async createConnection(options: PostgresConnectionOptions) {
const name = uuid();
this.loggerService.info(
`Creating new database connection '${name}': ${options.username}@${options.host}/${options.database}`,
{ meta },
);
return this.manager.create({
...options,
name,
logger: this.logger,
});
}
async onModuleInit() {
this.options$ = this.configService.configStream().pipe(
map(getDatabaseConnectionOptions),
distinctUntilChanged(isEqual),
);
this.subscription = this.options$.pipe(skip(1)).subscribe(async options => {
const manager = this.manager;
const newConnection = await this.createConnection({
...options,
// Don't run migrations again when creating connection after credential change
migrationsRun: false,
});
const newConnectionIndex = this.getConnectionIndex(newConnection);
try {
await newConnection.connect();
this.removeOldConnections(newConnection);
} catch (error) {
manager.connections.splice(newConnectionIndex, 1);
this.loggerService.error(error.message, error.stack, { meta });
}
});
const options = await this.options$.pipe(first()).toPromise();
const connection = await this.createConnection(options);
await connection.connect();
}
async onModuleDestroy() {
await this.cleanup();
}
async onApplicationShutdown() {
await this.cleanup();
}
private getConnectionIndex(connection: Connection) {
return this.manager.connections.indexOf(connection);
}
private async cleanup() {
if (this.subscription) {
this.subscription.unsubscribe();
this.subscription = undefined;
}
const { connections } = getConnectionManager();
await DatabaseService.closeConnections(connections.splice(0, connections.length));
}
}
@krzysztof-miemiec
Copy link
Author

Thanks @shaunek!
I'm no longer working with Nest and TypeORM, but I'm thinking that you could maintain your own connection list in DatabaseService for cleanup purposes. I hope that TypeORM internally removes these connections, since the array is made internal.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment