Skip to content

Sync-in · Sovereign platform for file storage, sharing, synchronization, and collaboration.

4.6 KB
Raw Blame
import { type DrizzleMySqlConfig, DrizzleMySqlModule } from '@knaadh/nestjs-drizzle-mysql2'
import { BeforeApplicationShutdown, Global, Inject, Logger, Module, OnModuleInit } from '@nestjs/common'
import type { Connection, Pool } from 'mysql2'
import { setTimeout } from 'node:timers/promises'
import { configuration } from '../../configuration/config.environment.js'
import { INFRASTRUCTURE_CONNECTION_RETRY_DELAY, INFRASTRUCTURE_DEPENDENCY } from '../availability/availability.constants.js'
import { Availability } from '../availability/availability.service.js'
import { connectionErrorMessage, isRetryableConnectionError } from '../utils.js'
import { DB_SESSION_INIT_QUERIES, DB_TOKEN_PROVIDER } from './constants.js'
import { DatabaseLogger } from './database.logger.js'
import type { DBSchema } from './interfaces/database.interface.js'
import * as schema from './schema.js'

@Global()
@Module({
  imports: [
    DrizzleMySqlModule.registerAsync({
      tag: DB_TOKEN_PROVIDER,
      useFactory: (): DrizzleMySqlConfig => ({
        mysql: {
          connection: 'pool',
          config: configuration.mysql.url
        },
        config: {
          schema: { ...schema },
          mode: 'default',
          logger: configuration.mysql.logQueries ? new DatabaseLogger() : false
        }
      })
    })
  ]
})
export class DatabaseModule implements OnModuleInit, BeforeApplicationShutdown {
  private readonly logger = new Logger(DatabaseModule.name)
  private readonly pool: Pool
  private readonly shutdownController = new AbortController()
  private recoveryPromise?: Promise<void>
  private poolClosed = false

  constructor(
    @Inject(DB_TOKEN_PROVIDER) private readonly db: DBSchema,
    private readonly availability: Availability
  ) {
    this.pool = this.db.$client
    this.availability.register(INFRASTRUCTURE_DEPENDENCY.DATABASE)
  }

  async onModuleInit(): Promise<void> {
    this.pool.on('connection', (conn: Connection) => {
      conn.once('error', (error: unknown) => this.handleConnectionError(error))
      for (const query of DB_SESSION_INIT_QUERIES) {
        conn.query(query)
      }
    })

    await this.waitUntilAvailable()
  }

  async beforeApplicationShutdown(): Promise<void> {
    this.availability.setAvailable(INFRASTRUCTURE_DEPENDENCY.DATABASE, false)
    this.shutdownController.abort()
    await this.recoveryPromise
    await this.closePool()
  }

  private async waitUntilAvailable(isRecovery = false): Promise<void> {
    while (!this.shutdownController.signal.aborted) {
      try {
        await this.pool.promise().query('SELECT 1')
        if (this.shutdownController.signal.aborted) return
        this.availability.setAvailable(INFRASTRUCTURE_DEPENDENCY.DATABASE, true)
        this.logger.log(isRecovery ? 'Connection to MySQL server restored' : 'Connected to MySQL server')
        return
      } catch (error) {
        this.availability.setAvailable(INFRASTRUCTURE_DEPENDENCY.DATABASE, false)
        const message = `Unable to ${isRecovery ? 'reconnect to' : 'connect to'} MySQL server: ${connectionErrorMessage(error)}`
        if (!isRetryableConnectionError(error)) {
          if (!isRecovery) {
            await this.closePool()
            throw new Error(message)
          }
          this.logger.error(message)
          this.logger.error('MySQL connection cannot be retried without changing the configuration')
          return
        }
        this.logger.error(message)
        this.logger.warn(`Retrying connection to MySQL server in ${INFRASTRUCTURE_CONNECTION_RETRY_DELAY / 1000}s`)
        if (!(await this.waitRetryDelay())) return
      }
    }
  }

  private handleConnectionError(error: unknown): void {
    const wasAvailable = this.availability.isAvailable(INFRASTRUCTURE_DEPENDENCY.DATABASE)
    this.availability.setAvailable(INFRASTRUCTURE_DEPENDENCY.DATABASE, false)
    if (!wasAvailable || this.shutdownController.signal.aborted || this.recoveryPromise) return

    this.logger.error(`Connection to MySQL server lost: ${connectionErrorMessage(error)}`)
    this.recoveryPromise = this.recoverAvailability()
  }

  private async recoverAvailability(): Promise<void> {
    try {
      await this.waitUntilAvailable(true)
    } finally {
      this.recoveryPromise = undefined
    }
  }

  private async waitRetryDelay(): Promise<boolean> {
    try {
      await setTimeout(INFRASTRUCTURE_CONNECTION_RETRY_DELAY, undefined, { signal: this.shutdownController.signal })
      return true
    } catch (error) {
      if (error instanceof Error && error.name === 'AbortError') return false
      throw error
    }
  }

  private async closePool(): Promise<void> {
    if (!this.poolClosed) {
      this.poolClosed = true
      await this.pool.promise().end()
    }
  }
}