Repository navigation
Expand file tree
/
Copy pathserver.js
More file actions
374 lines (329 loc) · 10.7 KB
/
Copy pathserver.js
File metadata and controls
374 lines (329 loc) · 10.7 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
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
#!/usr/bin/env node
const http = require('http');
const fs = require('fs');
const path = require('path');
const zlib = require('zlib');
const { loadEnvFile, resolveGithubToken } = require('./scripts/load-env');
loadEnvFile(__dirname);
const {
buildUnconfiguredGithubState,
fetchGithubState,
computeProfilesFingerprint,
buildContributorState,
resolveGithubRepository
} = require('./scripts/state-builder');
const { syncLocalGitRepo } = require('./scripts/git-sync');
const { resolveStaticPath } = require('./scripts/static-path');
const PORT = Number(process.env.PORT || 3008);
const ROOT = __dirname;
const PUBLIC_DIR = path.join(ROOT, 'public');
const POLL_INTERVAL_MS = 700;
const GITHUB_TOKEN = resolveGithubToken();
const AUTHENTICATED_GITHUB_SYNC_INTERVAL_MS = 30000;
const UNAUTHENTICATED_GITHUB_SYNC_INTERVAL_MS = 300000;
// Authenticated sync can poll quickly; unauthenticated REST calls are limited to 60 req/h.
const GITHUB_SYNC_INTERVAL_MS = Number(
process.env.GITHUB_SYNC_INTERVAL_MS ||
(GITHUB_TOKEN ? AUTHENTICATED_GITHUB_SYNC_INTERVAL_MS : UNAUTHENTICATED_GITHUB_SYNC_INTERVAL_MS)
);
const MANUAL_REFRESH_COOLDOWN_MS = 5000;
const clients = new Set();
let lastGoodContributors = [];
let lastFingerprint = '';
let githubState = buildUnconfiguredGithubState();
let currentState = buildState();
let currentStateJson = JSON.stringify(currentState);
let currentStateGzip = zlib.gzipSync(Buffer.from(currentStateJson));
let lastManualRefreshAt = 0;
let inFlightRefresh = null;
function setCurrentState(nextState) {
currentState = nextState;
currentStateJson = JSON.stringify(currentState);
currentStateGzip = zlib.gzipSync(Buffer.from(currentStateJson));
}
async function runFullRefresh() {
// Step 1: pull local repo so newly-merged profiles land on disk before fingerprint poll runs.
const gitResult = await syncLocalGitRepo({ root: ROOT });
// Hand-off to the file-watcher path: a successful ff merge changes profile mtimes,
// so trigger pollForChanges immediately instead of waiting up to 700ms for the next tick.
if (gitResult.ok && !gitResult.skipped && gitResult.pulled > 0) {
pollForChanges();
}
// Step 2: refresh GitHub REST metadata (commits/issues/PRs/etc.) regardless of git result.
let githubError = null;
try {
await refreshGithubSync();
} catch (error) {
githubError = error;
}
return {
git: gitResult,
github: githubError
? { ok: false, message: githubError.message, configured: githubState.configured }
: { ok: githubState.ok, message: githubState.message, configured: githubState.configured }
};
}
async function refreshGithubSync() {
if (inFlightRefresh) return inFlightRefresh;
inFlightRefresh = (async () => {
const repository = resolveGithubRepository(ROOT);
if (!repository) {
githubState = buildUnconfiguredGithubState();
setCurrentState(buildState());
broadcastRaw('state', currentStateJson);
broadcast('pulse', {
type: githubState.ok ? 'success' : 'error',
message: githubState.message,
generatedAt: currentState.generatedAt
});
return;
}
try {
githubState = await fetchGithubState({
repository,
token: GITHUB_TOKEN
});
} catch (error) {
githubState = {
...githubState,
configured: true,
ok: false,
repository,
events: [],
commits: githubState.commits || [],
issues: githubState.issues || [],
pullRequests: githubState.pullRequests || [],
message: error.message
};
}
setCurrentState(buildState());
broadcastRaw('state', currentStateJson);
broadcast('pulse', {
type: githubState.ok ? 'success' : 'error',
message: githubState.message,
generatedAt: currentState.generatedAt
});
})();
try {
await inFlightRefresh;
} finally {
inFlightRefresh = null;
}
}
function buildState() {
const state = buildContributorState({
githubState,
fallbackContributors: lastGoodContributors
});
if (state.ok) {
lastGoodContributors = state.contributors;
}
return state;
}
function sendSseRaw(res, event, serializedPayload) {
res.write(`event: ${event}\ndata: ${serializedPayload}\n\n`);
}
function broadcastRaw(event, serializedPayload) {
if (!clients.size) return;
const frame = `event: ${event}\ndata: ${serializedPayload}\n\n`;
for (const res of clients) {
res.write(frame);
}
}
function broadcast(event, payload) {
if (!clients.size) return;
broadcastRaw(event, JSON.stringify(payload));
}
function isCompressible(filePath) {
const ext = path.extname(filePath).toLowerCase();
return ext === '.html' || ext === '.css' || ext === '.js' || ext === '.mjs' || ext === '.json' || ext === '.svg';
}
function acceptsGzip(req) {
return /\bgzip\b/i.test(String(req.headers['accept-encoding'] || ''));
}
function safeStaticPath(urlPath) {
return resolveStaticPath(urlPath, PUBLIC_DIR);
}
function contentType(filePath) {
const ext = path.extname(filePath).toLowerCase();
return {
'.html': 'text/html; charset=utf-8',
'.css': 'text/css; charset=utf-8',
'.js': 'application/javascript; charset=utf-8',
'.json': 'application/json; charset=utf-8',
'.svg': 'image/svg+xml; charset=utf-8',
'.png': 'image/png',
'.jpg': 'image/jpeg',
'.jpeg': 'image/jpeg',
'.ico': 'image/x-icon'
}[ext] || 'application/octet-stream';
}
function handleRequest(req, res) {
const url = new URL(req.url, `http://${req.headers.host || 'localhost'}`);
if (url.pathname === '/api/contributors') {
if (acceptsGzip(req)) {
res.writeHead(200, {
'Content-Type': 'application/json; charset=utf-8',
'Content-Encoding': 'gzip',
'Vary': 'Accept-Encoding',
'Cache-Control': 'no-cache'
});
res.end(currentStateGzip);
} else {
res.writeHead(200, {
'Content-Type': 'application/json; charset=utf-8',
'Vary': 'Accept-Encoding',
'Cache-Control': 'no-cache'
});
res.end(currentStateJson);
}
return;
}
if (url.pathname === '/api/refresh' && req.method === 'POST') {
const now = Date.now();
const sinceLast = now - lastManualRefreshAt;
if (sinceLast < MANUAL_REFRESH_COOLDOWN_MS) {
res.writeHead(429, {
'Content-Type': 'application/json; charset=utf-8',
'Retry-After': Math.ceil((MANUAL_REFRESH_COOLDOWN_MS - sinceLast) / 1000)
});
res.end(JSON.stringify({
ok: false,
message: '刷新太频繁,稍后再试',
retryInMs: MANUAL_REFRESH_COOLDOWN_MS - sinceLast
}));
return;
}
lastManualRefreshAt = now;
runFullRefresh()
.then((result) => {
res.writeHead(200, { 'Content-Type': 'application/json; charset=utf-8' });
res.end(JSON.stringify({
ok: true,
generatedAt: currentState.generatedAt,
git: result.git,
github: result.github
}));
})
.catch((error) => {
res.writeHead(500, { 'Content-Type': 'application/json; charset=utf-8' });
res.end(JSON.stringify({ ok: false, message: error.message }));
});
return;
}
if (url.pathname === '/events') {
res.writeHead(200, {
'Content-Type': 'text/event-stream; charset=utf-8',
'Cache-Control': 'no-cache',
'Connection': 'keep-alive',
'Access-Control-Allow-Origin': '*'
});
res.write('retry: 1000\n\n');
sendSseRaw(res, 'state', currentStateJson);
clients.add(res);
req.on('close', () => {
clients.delete(res);
});
return;
}
const filePath = safeStaticPath(url.pathname);
if (!filePath) {
res.writeHead(403, { 'Content-Type': 'text/plain; charset=utf-8' });
res.end('Forbidden');
return;
}
fs.stat(filePath, (statErr, stat) => {
if (statErr || !stat.isFile()) {
res.writeHead(404, { 'Content-Type': 'text/plain; charset=utf-8' });
res.end('Not found');
return;
}
const isVendor = url.pathname.startsWith('/vendor/');
const etag = `W/"${stat.size}-${Math.trunc(stat.mtimeMs)}"`;
const cacheControl = isVendor ? 'public, max-age=31536000, immutable' : 'no-cache';
if (req.headers['if-none-match'] === etag) {
res.writeHead(304, {
'ETag': etag,
'Cache-Control': cacheControl
});
res.end();
return;
}
fs.readFile(filePath, (error, data) => {
if (error) {
res.writeHead(404, { 'Content-Type': 'text/plain; charset=utf-8' });
res.end('Not found');
return;
}
const headers = {
'Content-Type': contentType(filePath),
'ETag': etag,
'Cache-Control': cacheControl
};
if (isCompressible(filePath) && data.length >= 1024 && acceptsGzip(req)) {
zlib.gzip(data, (gzipErr, compressed) => {
if (gzipErr) {
res.writeHead(200, headers);
res.end(data);
return;
}
res.writeHead(200, {
...headers,
'Content-Encoding': 'gzip',
'Vary': 'Accept-Encoding'
});
res.end(compressed);
});
return;
}
res.writeHead(200, headers);
res.end(data);
});
});
}
function pollForChanges() {
try {
const nextFingerprint = computeProfilesFingerprint();
if (nextFingerprint !== lastFingerprint) {
lastFingerprint = nextFingerprint;
setCurrentState(buildState());
broadcastRaw('state', currentStateJson);
broadcast('pulse', {
type: currentState.ok ? 'success' : 'error',
message: currentState.message,
generatedAt: currentState.generatedAt
});
}
} catch (error) {
const payload = {
ok: false,
generatedAt: new Date().toISOString(),
count: lastGoodContributors.length,
contributors: lastGoodContributors,
errors: [`服务读取数据失败: ${error.message}`],
warnings: [],
github: githubState,
message: '服务读取数据失败,页面暂时保留上一次有效结果'
};
setCurrentState(payload);
broadcastRaw('state', currentStateJson);
}
}
lastFingerprint = computeProfilesFingerprint();
const server = http.createServer(handleRequest);
server.listen(PORT, () => {
console.log('');
console.log('Open Source Pulse Wall is running');
console.log(`Local: http://localhost:${PORT}`);
console.log(`API: http://localhost:${PORT}/api/contributors`);
console.log('');
console.log('Edit or add files in data/profiles or data/cheers and the page will update automatically.');
console.log('Press Ctrl+C to stop.');
console.log('');
});
refreshGithubSync();
setInterval(pollForChanges, POLL_INTERVAL_MS);
setInterval(refreshGithubSync, GITHUB_SYNC_INTERVAL_MS);
setInterval(() => {
broadcast('heartbeat', { at: new Date().toISOString(), clients: clients.size });
}, 15000);