@@ -6,8 +6,36 @@ import { CONNECTION_NAME } from './enums';
66import { PostgresConnectionCredentialsOptions } from 'typeorm/driver/postgres/PostgresConnectionCredentialsOptions' ;
77import { PostgresConnectionOptions } from 'typeorm/driver/postgres/PostgresConnectionOptions.js' ;
88import { Container as tteContainer } from '../typeorm-typedi-extensions' ;
9+ import { UpgradeLogger } from '../lib/logger/UpgradeLogger' ;
910
10- const replicaHosts = ( env . db . host_replica ? JSON . parse ( env . db . host_replica ) : [ ] ) as string [ ] ;
11+ const log = new UpgradeLogger ( ) ;
12+
13+ export const parseReplicaHosts = ( hostReplica ?: string | null ) : string [ ] => {
14+ if ( ! hostReplica ) {
15+ return [ ] ;
16+ }
17+
18+ try {
19+ const parsedHosts = JSON . parse ( hostReplica ) as unknown ;
20+ if ( Array . isArray ( parsedHosts ) && parsedHosts . every ( ( host ) => typeof host === 'string' ) ) {
21+ return parsedHosts ;
22+ }
23+
24+ log . error ( {
25+ message : 'Invalid read replica host list format — continuing without replica hosts' ,
26+ error : new Error ( 'host_replica must be a JSON string array' ) ,
27+ } ) ;
28+ return [ ] ;
29+ } catch ( error ) {
30+ log . error ( {
31+ message : 'Invalid read replica host configuration — continuing without replica hosts' ,
32+ error,
33+ } ) ;
34+ return [ ] ;
35+ }
36+ } ;
37+
38+ const replicaHosts = parseReplicaHosts ( env . db . host_replica ) ;
1139
1240const masterHost : PostgresConnectionCredentialsOptions = {
1341 host : env . db . host ,
@@ -71,7 +99,12 @@ export const typeormLoader: MicroframeworkLoader = async (settings: Microframewo
7199
72100 // register the data source instance in the typeorm-typeDI-extensions
73101 tteContainer . setDataSource ( CONNECTION_NAME . REPLICA , exportDataSourceInstance ) ;
74- await Promise . all ( [ appDataSourceInstance . initialize ( ) , exportDataSourceInstance . initialize ( ) ] ) ;
102+ await appDataSourceInstance . initialize ( ) ;
103+
104+ // Fire-and-forget replica init so a slow/unreachable replica doesn't block app startup.
105+ void exportDataSourceInstance . initialize ( ) . catch ( ( replicaErr ) => {
106+ log . error ( { message : 'Read replica connection failed — continuing without replica' , error : replicaErr } ) ;
107+ } ) ;
75108
76109 if ( ! env . db . synchronize && ! env . isECS ) {
77110 await appDataSourceInstance . runMigrations ( ) ;
@@ -86,8 +119,8 @@ export const typeormLoader: MicroframeworkLoader = async (settings: Microframewo
86119 } ) ;
87120 }
88121 } catch ( err ) {
89- // TODO: use logger to log the error
90122 const error = err as any ;
123+ log . error ( { message : 'Database connection failed' , error } ) ;
91124 if ( error . code === 'ECONNREFUSED' ) {
92125 error . type = SERVER_ERROR . DB_UNREACHABLE ;
93126 throw error ;
0 commit comments