-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpoller.js
More file actions
398 lines (339 loc) · 11.1 KB
/
poller.js
File metadata and controls
398 lines (339 loc) · 11.1 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
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
// poller.js — GitHub API polling system for repositories without webhooks
// Handles rate limiting, error handling, and event detection
"use strict";
const https = require("https");
const http = require("http");
// ─── Rate Limiting ────────────────────────────────────────────────────────────
// Global rate limit tracking
const rateLimits = new Map();
/**
* Check if we're rate limited for a specific token
*/
function isRateLimited(tokenId) {
const limit = rateLimits.get(tokenId);
if (!limit) return false;
return Date.now() < limit.resetTime;
}
/**
* Get remaining requests for a token
*/
function getRemainingRequests(tokenId) {
const limit = rateLimits.get(tokenId);
return limit ? limit.remaining : 5000;
}
/**
* Update rate limit info from GitHub API response headers
*/
function updateRateLimit(tokenId, headers) {
const remaining = parseInt(headers["x-ratelimit-remaining"] || "5000", 10);
const reset = parseInt(headers["x-ratelimit-reset"] || "0", 10) * 1000; // Convert to ms
rateLimits.set(tokenId, { remaining, resetTime: reset });
// Log rate limit status
if (remaining < 100) {
console.warn(`[poller] Rate limit low for token ${tokenId}: ${remaining} remaining, resets at ${new Date(reset).toISOString()}`);
}
return { remaining, resetTime: reset };
}
// ─── HTTP Helpers ────────────────────────────────────────────────────────────
/**
* Make an HTTP request to GitHub API
*/
function githubRequest(method, path, token, body = null) {
return new Promise((resolve, reject) => {
const isHttps = !process.env.GITHUB_API_URL?.startsWith("http://");
const baseUrl = process.env.GITHUB_API_URL || "api.github.com";
const protocol = isHttps ? https : http;
const options = {
hostname: baseUrl.replace(/^https?:\/\//, ""),
port: isHttps ? 443 : 80,
path: `/repos${path}`,
method: method,
headers: {
"Accept": "application/vnd.github+json",
"Authorization": `Bearer ${token}`,
"X-GitHub-Api-Version": "2022-11-28",
"User-Agent": "GitBot-Discord/2.0",
},
};
if (body) {
options.headers["Content-Type"] = "application/json";
}
const req = protocol.request(options, (res) => {
let data = "";
res.on("data", chunk => data += chunk);
res.on("end", () => {
// Update rate limit info
updateRateLimit(token, res.headers);
if (res.statusCode >= 200 && res.statusCode < 300) {
try {
resolve(data ? JSON.parse(data) : null);
} catch {
resolve(data);
}
} else if (res.statusCode === 404) {
reject({ status: 404, message: "Repository not found or is private" });
} else if (res.statusCode === 403) {
reject({ status: 403, message: "Forbidden - possibly rate limited" });
} else if (res.statusCode === 401) {
reject({ status: 401, message: "Unauthorized - check your token" });
} else {
reject({ status: res.statusCode, message: data || "Unknown error" });
}
});
});
req.on("error", reject);
if (body) req.write(JSON.stringify(body));
req.end();
});
}
// ─── Polling Functions ────────────────────────────────────────────────────────
/**
* Get the latest commit SHA for a repository
*/
async function getLatestCommit(owner, name, token) {
try {
const data = await githubRequest("GET", `/${owner}/${name}/commits?per_page=1`, token);
if (data && data.length > 0) {
return data[0].sha;
}
return null;
} catch (err) {
throw err;
}
}
/**
* Get recent commits since a specific SHA
*/
async function getCommitsSince(owner, name, token, sinceSha) {
try {
// Get commits up to 30 to check for the SHA
const data = await githubRequest("GET", `/${owner}/${name}/commits?per_page=30`, token);
if (!data || data.length === 0) return [];
// Find commits after the known SHA
const commits = [];
let found = false;
for (const commit of data) {
if (commit.sha === sinceSha) {
found = true;
break;
}
commits.push(commit);
}
// If we didn't find the SHA, return the most recent ones (up to 5)
if (!found && data.length > 0) {
return data.slice(0, 5);
}
return commits;
} catch (err) {
throw err;
}
}
/**
* Get recent releases
*/
async function getRecentReleases(owner, name, token, beforeTag = null) {
try {
const data = await githubRequest("GET", `/${owner}/${name}/releases?per_page=5`, token);
if (!data || data.length === 0) return [];
if (!beforeTag) return data;
// Filter releases before the known one
return data.filter(r => r.tag_name !== beforeTag);
} catch (err) {
throw err;
}
}
/**
* Get recent pull requests
*/
async function getRecentPullRequests(owner, name, token) {
try {
const data = await githubRequest("GET", `/${owner}/${name}/pulls?state=all&per_page=10`, token);
return data || [];
} catch (err) {
throw err;
}
}
/**
* Get repository info
*/
async function getRepoInfo(owner, name, token) {
try {
return await githubRequest("GET", `/${owner}/${name}`, token);
} catch (err) {
throw err;
}
}
// ─── Poller Class ────────────────────────────────────────────────────────────
class GitHubPoller {
constructor(options = {}) {
this.interval = options.interval || 60000; // Default 1 minute
this.onEvent = options.onEvent || (() => {});
this.timer = null;
this.running = false;
}
/**
* Start polling
*/
start() {
if (this.running) return;
this.running = true;
this._poll();
this.timer = setInterval(() => this._poll(), this.interval);
console.log(`[poller] Started polling every ${this.interval / 1000}s`);
}
/**
* Stop polling
*/
stop() {
this.running = false;
if (this.timer) {
clearInterval(this.timer);
this.timer = null;
}
console.log("[poller] Stopped polling");
}
/**
* Set polling interval
*/
setInterval(ms) {
this.interval = ms;
if (this.running) {
this.stop();
this.start();
}
}
/**
* Poll all enabled repositories
*/
async _poll() {
const db = require("./database");
try {
const repos = db.getPollableRepositories();
if (repos.length === 0) {
return;
}
for (const repo of repos) {
await this._pollRepo(repo);
}
} catch (err) {
console.error("[poller] Polling error:", err.message);
}
}
/**
* Poll a single repository
*/
async _pollRepo(repo) {
const db = require("./database");
// Get token for this repo
let token = null;
if (repo.github_token_id) {
const tokenObj = db.getTokenById(repo.github_token_id);
token = tokenObj?.token;
}
// Fall back to default token
if (!token) {
const defaultToken = db.getDefaultToken();
token = defaultToken?.token;
}
if (!token) {
console.warn(`[poller] No token for ${repo.full_name}`);
return;
}
// Check rate limit
const tokenId = repo.github_token_id || db.getDefaultToken()?.id;
if (tokenId && isRateLimited(tokenId)) {
console.log(`[poller] Rate limited, skipping ${repo.full_name}`);
return;
}
try {
// Check for new commits
const latestSha = await getLatestCommit(repo.owner, repo.name, token);
if (!latestSha) {
return;
}
// First time seeing this repo
if (!repo.last_commit_sha) {
db.updateRepository(repo.id, {
last_commit_sha: latestSha,
last_polled_at: Date.now(),
error_message: null,
});
console.log(`[poller] Initialized polling for ${repo.full_name} at ${latestSha.slice(0, 7)}`);
return;
}
// Check if there are new commits
if (latestSha !== repo.last_commit_sha) {
const newCommits = await getCommitsSince(repo.owner, repo.name, token, repo.last_commit_sha);
if (newCommits.length > 0) {
console.log(`[poller] ${newCommits.length} new commit(s) for ${repo.full_name}`);
// Build a synthetic push event for each new commit (up to 5)
for (const commit of newCommits.slice(0, 5)) {
// Note: the GitHub Commits API doesn't return the branch name, so
// we can't determine the actual ref. We use the default branch name
// from the repo object if available, otherwise fall back to "main".
const defaultBranch = repo.default_branch || "main";
const payload = {
repository: {
full_name: repo.full_name,
html_url: `https://github.com/${repo.full_name}`,
owner: { login: repo.owner },
name: repo.name,
},
sender: {
login: commit.author?.login || commit.commit.author.name,
html_url: commit.author?.html_url || null,
},
commits: [commit],
ref: `refs/heads/${defaultBranch}`,
compare: `https://github.com/${repo.full_name}/compare/${repo.last_commit_sha}...${latestSha}`,
};
this.onEvent("push", payload, repo);
}
// Update last known SHA
db.updateRepository(repo.id, {
last_commit_sha: latestSha,
last_polled_at: Date.now(),
error_message: null,
});
}
} else {
// Just update polling time
db.updateRepository(repo.id, {
last_polled_at: Date.now(),
});
}
} catch (err) {
console.error(`[poller] Error polling ${repo.full_name}:`, err.message);
// Mark the repo with error
db.updateRepository(repo.id, {
error_message: err.message,
});
}
}
/**
* Manually trigger a poll for a specific repo
*/
async pollNow(repoFullName) {
const db = require("./database");
const repo = db.getRepositoryByFullName(repoFullName);
if (!repo) {
throw new Error(`Repository ${repoFullName} not found`);
}
if (!repo.poll_enabled) {
throw new Error(`Repository ${repoFullName} is not enabled for polling`);
}
await this._pollRepo(repo);
}
}
module.exports = {
GitHubPoller,
githubRequest,
isRateLimited,
getRemainingRequests,
updateRateLimit,
getLatestCommit,
getCommitsSince,
getRecentReleases,
getRecentPullRequests,
getRepoInfo,
};