-
Notifications
You must be signed in to change notification settings - Fork 28
319 lines (283 loc) · 13.4 KB
/
Copy pathauto-assign.yml
File metadata and controls
319 lines (283 loc) · 13.4 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
name: Auto Assign & Unassign (Org-wide Limit)
on:
issue_comment:
types: [created]
env:
MAX_OPEN_ASSIGNMENTS: 6
jobs:
handle-comment:
runs-on: ubuntu-latest
timeout-minutes: 15
permissions:
issues: write
pull-requests: write
steps:
- name: Handle /assign or /unassign
uses: actions/github-script@v7
with:
# ORG_ACCESS_TOKEN must have the following scopes:
# - repo (or public_repo if using public repos only)
# - org:read (to enumerate organization repos)
github-token: ${{ secrets.ORG_ACCESS_TOKEN }}
script: |
/**
* Auto-assign workflow for organization-wide issue assignment limits
*
* Features:
* - Self-assignment only: Users comment /assign to assign themselves
* - Organization-wide limit: Enforces MAX_OPEN_ASSIGNMENTS across all org repos
* - Race condition mitigation: Re-checks assignment count before final assignment
*
* Required GitHub Token Permissions (ORG_ACCESS_TOKEN):
* - repo (or public_repo for public repos only)
* - org:read (to enumerate organization repositories)
*
* Configuration:
* - MAX_OPEN_ASSIGNMENTS: Maximum open issues per user (default: 2)
*
* Commands:
* - /assign: Self-assign an issue (if under limit)
* - /unassign: Remove self-assignment from an issue
*
* Limitations:
* - Small race condition window exists between checks and assignment
* - Only self-assignment supported (cannot assign others)
* - Requires archived repos to be properly marked in GitHub
*/
const comment = context.payload.comment;
const body = (comment.body || "").trim();
const user = comment.user.login;
const association = context.payload.comment.author_association;
const issue = context.payload.issue || context.payload.pull_request;
const issueNumber = issue.number;
const { owner, repo } = context.repo;
// Default assignment limit is 2 if not configured
const maxAssignments = parseInt(process.env.MAX_OPEN_ASSIGNMENTS || '2');
// New contributors get only 1 assignment
let userMaxAssignments = maxAssignments;
if (association === 'FIRST_TIME_CONTRIBUTOR' || association === 'FIRST_TIMER') {
userMaxAssignments = 1;
console.log(`User ${user} is a first-time contributor, limiting to 1 assignment`);
}
// Ignore bots only
if (comment.user.type === "Bot") {
console.log("Ignoring bot");
return;
}
const isAssign = body.startsWith("/assign");
const isUnassign = body.startsWith("/unassign");
if (!isAssign && !isUnassign) {
console.log("Not an /assign or /unassign command");
return;
}
// After checking isAssign
if (isAssign && body.trim() !== "/assign") {
await github.rest.issues.createComment({
owner,
repo,
issue_number: issueNumber,
body: `❌ @${user} This workflow only supports self-assignment. Use \`/assign\` without specifying a username.`,
});
return;
}
if (isUnassign) {
const currentAssignees = issue.assignees.map(a => a.login);
if (!currentAssignees.includes(user)) {
console.log(`${user} is not assigned, skipping unassign`);
return;
}
try {
await github.rest.issues.removeAssignees({
owner,
repo,
issue_number: issueNumber,
assignees: [user],
});
await github.rest.issues.createComment({
owner,
repo,
issue_number: issueNumber,
body: `✅ Unassigned @${user} successfully.`,
});
console.log(`Unassigned ${user} from #${issueNumber}`);
} catch (error) {
console.error(`Error unassigning user ${user} from issue #${issueNumber}:`, error);
// Attempt to create a fallback comment about the failure
try {
await github.rest.issues.createComment({
owner,
repo,
issue_number: issueNumber,
body: `❌ Failed to unassign @${user}. Please try again or contact a maintainer.`,
});
} catch (commentError) {
console.error(`Failed to create error comment for user ${user} on issue #${issueNumber}:`, commentError);
}
}
return;
}
// For /assign
const currentAssignees = issue.assignees.map(a => a.login);
if (currentAssignees.includes(user)) {
console.log(`${user} is already assigned, skipping.`);
return;
}
if (currentAssignees.length > 0) {
console.log("Issue already assigned to someone else, skipping.");
return;
}
console.log(`Checking org-wide assignments for ${user}...`);
let totalAssigned = 0;
let activeRepos = [];
try {
// Fetch all repos for the org
const repos = await github.paginate(github.rest.repos.listForOrg, {
org: owner,
type: "all",
per_page: 100,
max_items: 500, // Limit to first 500 repos to avoid excessive API calls
});
// Filter out archived repositories
activeRepos = repos.filter(r => !r.archived);
for (const r of activeRepos) {
// Exit early once limit is detected
if (totalAssigned >= userMaxAssignments) break;
try {
const assignedIssues = await github.paginate(
github.rest.issues.listForRepo,
{
owner,
repo: r.name,
state: "open",
assignee: user,
per_page: 100,
max_items: 500, // Limit to first 500 repos to avoid excessive API calls
}
);
totalAssigned += assignedIssues.length;
} catch (repoError) {
console.warn(`Skipping ${r.name}: ${repoError.message}`);
// Continue with other repos
}
}
// With many repos in the org, we could hit GitHub API rate limits.
const rateLimit = await github.rest.rateLimit.get();
console.log(`Remaining rate limit: ${rateLimit.data.rate.remaining}`);
} catch (error) {
console.error("Error fetching org-wide assignments:", error);
// Notify the user that the org-wide check failed
try {
await github.rest.issues.createComment({
owner,
repo,
issue_number: issueNumber,
body: `❌ **Org-wide assignment check failed**\n\n` +
`Could not verify how many issues @${user} currently has assigned across the organization.\n\n` +
`**Error:** ${error.message || 'Unknown error'}\n\n` +
`Please contact a maintainer or try again later.`,
});
} catch (commentError) {
console.error(`Failed to post error comment for user ${user} on issue #${issueNumber}:`, commentError);
}
// Mark the workflow run as failed
throw new Error(`Assignment failed for ${user} on issue #${issueNumber}: ${error.message || error}`);
}
console.log(`${user} currently has ${totalAssigned} open issues assigned across ${owner}`);
// KNOWN RACE CONDITION: There is a time window between calculating totalAssigned
// above and actually adding the assignee below where another workflow run (triggered
// by a different /assign comment) can assign the same user to a different issue.
// This distributed execution limitation means the limit can be transiently exceeded.
//
// Mitigation options:
// 1. Accept small transient violations - simplest approach, limit is eventually
// enforced and violations are rare/temporary in practice.
// 2. Use a centralized locking service (e.g., Redis, DynamoDB) to serialize
// assignment decisions across workflow runs.
// 3. Implement retry/backoff: re-check totalAssigned immediately before addAssignees,
// and if another assignment snuck in, abort and notify the user.
// 4. Use GitHub's assignment as a "lock" - assign first, then check and unassign
// if over limit (but this creates noise in notifications).
//
// Current implementation: Option 1 (accept transient violations for simplicity).
if (totalAssigned >= userMaxAssignments) {
const message = `⚠️ @${user} already has ${totalAssigned} open assignments across the org. Please finish or unassign before taking new ones.`;
await github.rest.issues.createComment({
owner,
repo,
issue_number: issueNumber,
body: message,
});
console.log("Limit reached, skipping assignment");
return;
}
// Re-verify the count immediately before assignment
try {
let reCheckCount = 0;
for (const r of activeRepos) {
// Exit early once limit is detected
if (totalAssigned >= userMaxAssignments) break;
try {
const assignedIssues = await github.paginate(
github.rest.issues.listForRepo,
{
owner,
repo: r.name,
state: "open",
assignee: user,
per_page: 100,
max_items: 500, // Limit to first 500 repos to avoid excessive API calls
}
);
reCheckCount += assignedIssues.length;
} catch (repoError) {
console.warn(`Skipping ${r.name} during re-check: ${repoError.message}`);
}
}
if (reCheckCount >= userMaxAssignments) {
const message = `⚠️ @${user}, another issue was assigned to you while processing this request. You now have ${reCheckCount} open assignments. Please finish or unassign before taking new ones.`;
await github.rest.issues.createComment({
owner,
repo,
issue_number: issueNumber,
body: message,
});
console.log("Limit reached after re-check, aborting assignment");
return;
}
} catch (error) {
console.error("Error during assignment re-check:", error);
// Continue with assignment since we already passed the first check
}
try {
await github.rest.issues.addAssignees({
owner,
repo,
issue_number: issueNumber,
assignees: [user],
});
await github.rest.issues.createComment({
owner,
repo,
issue_number: issueNumber,
body: `✅ Assigned @${user} successfully.`,
});
console.log(`Assigned ${user} to #${issueNumber}`);
} catch (error) {
console.error(`Error assigning user ${user} to issue #${issueNumber}:`, error);
// Attempt to create a failure comment to inform the user
try {
await github.rest.issues.createComment({
owner,
repo,
issue_number: issueNumber,
body: `❌ **Assignment failed**\n\n` +
`Could not assign @${user} to this issue.\n\n` +
`**Error:** ${error.message || 'Unknown error'}\n\n` +
`Please try again or contact a maintainer.`,
});
} catch (commentError) {
console.error(`Failed to post error comment for user ${user} on issue #${issueNumber}:`, commentError);
// Fall back to marking the workflow as failed if we can't even comment
throw new Error(`Assignment failed and unable to notify user: ${error.message || error}`);
}
}