-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathserver.ts
More file actions
237 lines (202 loc) · 7.12 KB
/
Copy pathserver.ts
File metadata and controls
237 lines (202 loc) · 7.12 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
/**
* Server Startup (Modular Architecture)
* Handles server initialization with modular structure
*/
import { type Server as HttpServer } from 'http';
import { type Express } from 'express';
import { createApp, initializeRoutes, setupErrorHandlers } from './app.js';
import { getEnv } from './shared/config/env.js';
import { createLogger } from './shared/logs/logger.js';
import { initializeDatabaseAsync } from './shared/config/db.js';
import { GitHubClient } from './shared/utils/github-client.js';
import { closeRedisClient, getRedisClient } from './shared/utils/redis-client.js';
import { createResponseCache } from './shared/utils/response-cache.js';
import { scheduleStatsCleanup } from './shared/utils/stats-cleanup.js';
import { getBadgeCacheService, getBadgeCacheServiceSync } from './services/badge-cache.service.js';
import type { ICacheService } from './services/base.service.js';
const logger = createLogger({ module: 'server' });
let activeApp: Express | null = null;
let activeServer: HttpServer | null = null;
let shutdownPromise: Promise<void> | null = null;
let stopStatsCleanup: (() => void) | null = null;
// Shared bounded cache for API responses. Capacity + TTL configured in
// `createResponseCache`; TTL matches env.CACHE_DURATION set below.
const cache = createResponseCache(getEnv().CACHE_DURATION);
function createRedisHealthCacheService(): ICacheService {
return {
async get<T>(key: string): Promise<T | null> {
const client = await getRedisClient();
const value = await client.get(key);
if (value === null) {
return null;
}
try {
return JSON.parse(value) as T;
} catch {
return value as T;
}
},
async set<T>(key: string, value: T, ttl?: number): Promise<void> {
const client = await getRedisClient();
const serializedValue = typeof value === 'string' ? value : JSON.stringify(value);
if (ttl && ttl > 0) {
await client.setEx(key, ttl, serializedValue);
return;
}
await client.set(key, serializedValue);
},
async del(key: string): Promise<void> {
const client = await getRedisClient();
await client.del(key);
},
async exists(key: string): Promise<boolean> {
const client = await getRedisClient();
return (await client.exists(key)) > 0;
},
async flush(): Promise<void> {
const client = await getRedisClient();
await client.flushDb();
},
};
}
/**
* Initialize external services
*/
async function initializeServices(): Promise<{ cacheService?: ICacheService }> {
const env = getEnv();
// Initialize Database
try {
await initializeDatabaseAsync();
logger.info('Database initialized', {
provider: env.DATABASE_PROVIDER,
});
} catch (error) {
logger.error('Database initialization failed', error as Error, {
provider: env.DATABASE_PROVIDER,
});
throw error;
}
// Initialize Redis (optional)
let cacheService: ICacheService | undefined;
try {
await getRedisClient();
cacheService = createRedisHealthCacheService();
logger.info('Redis cache initialized');
} catch (error) {
logger.warn('Redis not available - using in-memory cache');
}
// Initialize badge cache singleton so per-request writers (setUserBadgeSVG /
// setProjectBadgeSVG) actually reach Redis. Without this call the sync
// accessor stays null and every badge lookup falls through to the DB.
try {
const badgeCache = await getBadgeCacheService();
if (badgeCache.isReady()) {
logger.info('Badge cache initialized');
}
} catch (error) {
logger.warn('Badge cache not available', {
error: error instanceof Error ? error.message : String(error),
});
}
return { cacheService };
}
/**
* Start the server
*/
export async function startServer(): Promise<Express> {
if (activeApp && activeServer?.listening) {
return activeApp;
}
const env = getEnv();
// Initialize services
const { cacheService } = await initializeServices();
// Create GitHub client
const githubClient = new GitHubClient(env.GITHUB_TOKEN);
// Create Express app
const app = createApp();
// Initialize routes with dependencies
initializeRoutes(app, githubClient, cache, env.CACHE_DURATION, cacheService);
// Setup error handlers
setupErrorHandlers(app);
// Start listening
const port = env.PORT;
const host = env.HOST;
const server = app.listen(port, host, () => {
logger.info(`Server started on port ${port}`, {
port,
host,
environment: env.APP_ENV,
nodeEnv: process.env.NODE_ENV
});
});
activeApp = app;
activeServer = server;
// Schedule background prune of stats_requests. `.unref()` inside so we
// don't block shutdown; explicit stop on stopServer() keeps tests clean.
if (!stopStatsCleanup) {
stopStatsCleanup = scheduleStatsCleanup({
retentionDays: env.STATS_REQUESTS_RETENTION_DAYS,
intervalHours: env.STATS_REQUESTS_CLEANUP_INTERVAL_HOURS,
});
}
server.on('error', (error: NodeJS.ErrnoException) => {
logger.error('HTTP server failed to listen', error, {
port,
host,
code: error.code,
});
process.exit(1);
});
return app;
}
export async function stopServer(): Promise<void> {
if (shutdownPromise) {
return shutdownPromise;
}
shutdownPromise = (async () => {
if (stopStatsCleanup) {
stopStatsCleanup();
stopStatsCleanup = null;
}
if (activeServer) {
await new Promise<void>((resolve, reject) => {
activeServer?.close((error) => {
if (error) {
reject(error);
return;
}
resolve();
});
});
logger.info('HTTP server stopped');
}
try {
await getBadgeCacheServiceSync()?.disconnect();
} catch (error) {
logger.warn('Failed to close badge cache cleanly', {
error: error instanceof Error ? error.message : String(error),
});
}
try {
await closeRedisClient();
} catch (error) {
logger.warn('Failed to close Redis client cleanly', {
error: error instanceof Error ? error.message : String(error),
});
}
activeServer = null;
activeApp = null;
})();
try {
await shutdownPromise;
} finally {
shutdownPromise = null;
}
}
// Start server if this file is run directly
if (import.meta.url === `file://${process.argv[1]}`) {
startServer().catch((error) => {
logger.error('Failed to start server', error as Error);
process.exit(1);
});
}