|
| 1 | +import 'dart:io'; |
| 2 | + |
| 3 | +import 'package:dart_frog/dart_frog.dart'; |
| 4 | +import 'package:ht_api/src/config/environment_config.dart'; |
| 5 | +import 'package:ht_api/src/rbac/permission_service.dart'; |
| 6 | +import 'package:ht_api/src/services/auth_service.dart'; |
| 7 | +import 'package:ht_api/src/services/auth_token_service.dart'; |
| 8 | +import 'package:ht_api/src/services/dashboard_summary_service.dart'; |
| 9 | +import 'package:ht_api/src/services/database_seeding_service.dart'; |
| 10 | +import 'package:ht_api/src/services/default_user_preference_limit_service.dart'; |
| 11 | +import 'package:ht_api/src/services/jwt_auth_token_service.dart'; |
| 12 | +import 'package:ht_api/src/services/token_blacklist_service.dart'; |
| 13 | +import 'package:ht_api/src/services/user_preference_limit_service.dart'; |
| 14 | +import 'package:ht_api/src/services/verification_code_storage_service.dart'; |
| 15 | +import 'package:ht_data_client/ht_data_client.dart'; |
| 16 | +import 'package:ht_data_postgres/ht_data_postgres.dart'; |
| 17 | +import 'package:ht_data_repository/ht_data_repository.dart'; |
| 18 | +import 'package:ht_email_inmemory/ht_email_inmemory.dart'; |
| 19 | +import 'package:ht_email_repository/ht_email_repository.dart'; |
| 20 | +import 'package:ht_shared/ht_shared.dart'; |
| 21 | +import 'package:logging/logging.dart'; |
| 22 | +import 'package:postgres/postgres.dart'; |
| 23 | +import 'package:uuid/uuid.dart'; |
| 24 | + |
| 25 | +/// Global logger instance. |
| 26 | +final _log = Logger('ht_api'); |
| 27 | + |
| 28 | +/// Global PostgreSQL connection instance. |
| 29 | +late final Connection _connection; |
| 30 | + |
| 31 | +/// Creates a data repository for a given type [T]. |
| 32 | +/// |
| 33 | +/// This helper function centralizes the creation of repositories, |
| 34 | +/// ensuring they all use the same database connection and logger. |
| 35 | +HtDataRepository<T> _createRepository<T>({ |
| 36 | + required String tableName, |
| 37 | + required FromJson<T> fromJson, |
| 38 | + required ToJson<T> toJson, |
| 39 | +}) { |
| 40 | + return HtDataRepository<T>( |
| 41 | + dataClient: HtDataPostgresClient<T>( |
| 42 | + connection: _connection, |
| 43 | + tableName: tableName, |
| 44 | + fromJson: fromJson, |
| 45 | + toJson: toJson, |
| 46 | + log: _log, |
| 47 | + ), |
| 48 | + ); |
| 49 | +} |
| 50 | + |
| 51 | +/// The main entry point for the server. |
| 52 | +/// |
| 53 | +/// This function is responsible for: |
| 54 | +/// 1. Setting up the global logger. |
| 55 | +/// 2. Establishing the PostgreSQL database connection. |
| 56 | +/// 3. Providing these dependencies to the Dart Frog handler. |
| 57 | +/// 4. Gracefully closing the database connection on server shutdown. |
| 58 | +Future<HttpServer> run(Handler handler, InternetAddress ip, int port) async { |
| 59 | + // 1. Setup Logger |
| 60 | + Logger.root.level = Level.ALL; |
| 61 | + Logger.root.onRecord.listen((record) { |
| 62 | + // ignore: avoid_print |
| 63 | + print( |
| 64 | + '${record.level.name}: ${record.time}: ' |
| 65 | + '${record.loggerName}: ${record.message}', |
| 66 | + ); |
| 67 | + }); |
| 68 | + |
| 69 | + // 2. Establish Database Connection |
| 70 | + _log.info('Connecting to PostgreSQL database...'); |
| 71 | + final dbUri = Uri.parse(EnvironmentConfig.databaseUrl); |
| 72 | + String? username; |
| 73 | + String? password; |
| 74 | + if (dbUri.userInfo.isNotEmpty) { |
| 75 | + final parts = dbUri.userInfo.split(':'); |
| 76 | + username = Uri.decodeComponent(parts.first); |
| 77 | + if (parts.length > 1) { |
| 78 | + password = Uri.decodeComponent(parts.last); |
| 79 | + } |
| 80 | + } |
| 81 | + |
| 82 | + _connection = await Connection.open( |
| 83 | + Endpoint( |
| 84 | + host: dbUri.host, |
| 85 | + port: dbUri.port, |
| 86 | + database: dbUri.path.substring(1), // Remove leading '/' |
| 87 | + username: username, |
| 88 | + password: password, |
| 89 | + ), |
| 90 | + // Using `require` is a more secure default. For local development against |
| 91 | + // a non-SSL database, this may need to be changed to `SslMode.disable`. |
| 92 | + settings: const ConnectionSettings(sslMode: SslMode.require), |
| 93 | + ); |
| 94 | + _log.info('PostgreSQL database connection established.'); |
| 95 | + |
| 96 | + // 3. Initialize and run database seeding |
| 97 | + // This runs on every startup. The operations are idempotent (`IF NOT EXISTS`, |
| 98 | + // `ON CONFLICT DO NOTHING`), so it's safe to run every time. This ensures |
| 99 | + // the database is always in a valid state, especially for first-time setup |
| 100 | + // in any environment. |
| 101 | + final seedingService = DatabaseSeedingService( |
| 102 | + connection: _connection, |
| 103 | + log: _log, |
| 104 | + ); |
| 105 | + await seedingService.createTables(); |
| 106 | + await seedingService.seedGlobalFixtureData(); |
| 107 | + await seedingService.seedInitialAdminAndConfig(); |
| 108 | + |
| 109 | + // 4. Initialize Repositories |
| 110 | + final headlineRepository = _createRepository<Headline>( |
| 111 | + tableName: 'headlines', |
| 112 | + fromJson: Headline.fromJson, |
| 113 | + toJson: (h) => h.toJson(), |
| 114 | + ); |
| 115 | + final categoryRepository = _createRepository<Category>( |
| 116 | + tableName: 'categories', |
| 117 | + fromJson: Category.fromJson, |
| 118 | + toJson: (c) => c.toJson(), |
| 119 | + ); |
| 120 | + final sourceRepository = _createRepository<Source>( |
| 121 | + tableName: 'sources', |
| 122 | + fromJson: Source.fromJson, |
| 123 | + toJson: (s) => s.toJson(), |
| 124 | + ); |
| 125 | + final countryRepository = _createRepository<Country>( |
| 126 | + tableName: 'countries', |
| 127 | + fromJson: Country.fromJson, |
| 128 | + toJson: (c) => c.toJson(), |
| 129 | + ); |
| 130 | + final userRepository = _createRepository<User>( |
| 131 | + tableName: 'users', |
| 132 | + fromJson: User.fromJson, |
| 133 | + toJson: (u) => u.toJson(), |
| 134 | + ); |
| 135 | + final userAppSettingsRepository = _createRepository<UserAppSettings>( |
| 136 | + tableName: 'user_app_settings', |
| 137 | + fromJson: UserAppSettings.fromJson, |
| 138 | + toJson: (s) => s.toJson(), |
| 139 | + ); |
| 140 | + final userContentPreferencesRepository = |
| 141 | + _createRepository<UserContentPreferences>( |
| 142 | + tableName: 'user_content_preferences', |
| 143 | + fromJson: UserContentPreferences.fromJson, |
| 144 | + toJson: (p) => p.toJson(), |
| 145 | + ); |
| 146 | + final appConfigRepository = _createRepository<AppConfig>( |
| 147 | + tableName: 'app_config', |
| 148 | + fromJson: AppConfig.fromJson, |
| 149 | + toJson: (c) => c.toJson(), |
| 150 | + ); |
| 151 | + |
| 152 | + // 5. Initialize Services |
| 153 | + const uuid = Uuid(); |
| 154 | + const emailRepository = HtEmailRepository( |
| 155 | + emailClient: HtEmailInMemoryClient(), |
| 156 | + ); |
| 157 | + final tokenBlacklistService = InMemoryTokenBlacklistService(); |
| 158 | + final authTokenService = JwtAuthTokenService( |
| 159 | + userRepository: userRepository, |
| 160 | + blacklistService: tokenBlacklistService, |
| 161 | + uuidGenerator: uuid, |
| 162 | + ); |
| 163 | + final verificationCodeStorageService = |
| 164 | + InMemoryVerificationCodeStorageService(); |
| 165 | + final authService = AuthService( |
| 166 | + userRepository: userRepository, |
| 167 | + authTokenService: authTokenService, |
| 168 | + verificationCodeStorageService: verificationCodeStorageService, |
| 169 | + emailRepository: emailRepository, |
| 170 | + userAppSettingsRepository: userAppSettingsRepository, |
| 171 | + userContentPreferencesRepository: userContentPreferencesRepository, |
| 172 | + uuidGenerator: uuid, |
| 173 | + ); |
| 174 | + final dashboardSummaryService = DashboardSummaryService( |
| 175 | + headlineRepository: headlineRepository, |
| 176 | + categoryRepository: categoryRepository, |
| 177 | + sourceRepository: sourceRepository, |
| 178 | + ); |
| 179 | + const permissionService = PermissionService(); |
| 180 | + final userPreferenceLimitService = DefaultUserPreferenceLimitService( |
| 181 | + appConfigRepository: appConfigRepository, |
| 182 | + ); |
| 183 | + |
| 184 | + // 6. Create the main handler with all dependencies provided |
| 185 | + final finalHandler = handler |
| 186 | + // Foundational utilities |
| 187 | + .use(provider<Uuid>((_) => uuid)) |
| 188 | + // Repositories |
| 189 | + .use(provider<HtDataRepository<Headline>>((_) => headlineRepository)) |
| 190 | + .use(provider<HtDataRepository<Category>>((_) => categoryRepository)) |
| 191 | + .use(provider<HtDataRepository<Source>>((_) => sourceRepository)) |
| 192 | + .use(provider<HtDataRepository<Country>>((_) => countryRepository)) |
| 193 | + .use(provider<HtDataRepository<User>>((_) => userRepository)) |
| 194 | + .use( |
| 195 | + provider<HtDataRepository<UserAppSettings>>( |
| 196 | + (_) => userAppSettingsRepository, |
| 197 | + ), |
| 198 | + ) |
| 199 | + .use( |
| 200 | + provider<HtDataRepository<UserContentPreferences>>( |
| 201 | + (_) => userContentPreferencesRepository, |
| 202 | + ), |
| 203 | + ) |
| 204 | + .use(provider<HtDataRepository<AppConfig>>((_) => appConfigRepository)) |
| 205 | + .use(provider<HtEmailRepository>((_) => emailRepository)) |
| 206 | + // Services |
| 207 | + .use(provider<TokenBlacklistService>((_) => tokenBlacklistService)) |
| 208 | + .use(provider<AuthTokenService>((_) => authTokenService)) |
| 209 | + .use( |
| 210 | + provider<VerificationCodeStorageService>( |
| 211 | + (_) => verificationCodeStorageService, |
| 212 | + ), |
| 213 | + ) |
| 214 | + .use(provider<AuthService>((_) => authService)) |
| 215 | + .use(provider<DashboardSummaryService>((_) => dashboardSummaryService)) |
| 216 | + .use(provider<PermissionService>((_) => permissionService)) |
| 217 | + .use( |
| 218 | + provider<UserPreferenceLimitService>((_) => userPreferenceLimitService), |
| 219 | + ); |
| 220 | + |
| 221 | + // 7. Start the server |
| 222 | + final server = await serve(finalHandler, ip, port); |
| 223 | + _log.info('Server listening on port ${server.port}'); |
| 224 | + |
| 225 | + // 8. Handle graceful shutdown |
| 226 | + ProcessSignal.sigint.watch().listen((_) async { |
| 227 | + _log.info('Received SIGINT. Shutting down...'); |
| 228 | + await _connection.close(); |
| 229 | + _log.info('Database connection closed.'); |
| 230 | + await server.close(force: true); |
| 231 | + _log.info('Server shut down.'); |
| 232 | + exit(0); |
| 233 | + }); |
| 234 | + |
| 235 | + return server; |
| 236 | +} |
0 commit comments