Skip to content

Instantly share code, notes, and snippets.

@krzysztof-miemiec
Created July 15, 2020 21:44
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • 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));
}
}
@shaunek
Copy link

shaunek commented Oct 11, 2021

This POC was really helpful to my team as we needed similar functionality in our application. Just a note that as of typeorm version 0.2.35 some of the key code here will no longer work. The bit that doesn't work is related to the fact that typeorm's ConnectionManager (from getConnectionManager()) no longer publicly exposes the list of connections in the same way, and so the list of connections (ie this.manager.connections) can no longer be manipulated in the same way. From 0.2.35 on there is no way to "remove" a connection from the connection list, which is somewhat problematic.

@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