-
Notifications
You must be signed in to change notification settings - Fork 47
Expand file tree
/
Copy pathdiscord.ts
More file actions
518 lines (455 loc) · 14.1 KB
/
discord.ts
File metadata and controls
518 lines (455 loc) · 14.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
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
import * as pulumi from '@pulumi/pulumi';
import { ROLES, type Role, buildRoleLookup } from './config/roles';
import { MEMBERS } from './config/users';
import type { RoleId } from './config/roleIds';
const config = new pulumi.Config('discord');
// Discord integration is optional - only enabled if botToken and guildId are configured
const DISCORD_BOT_TOKEN = config.getSecret('botToken');
const DISCORD_GUILD_ID = config.get('guildId');
const DISCORD_ENABLED = DISCORD_BOT_TOKEN !== undefined && DISCORD_GUILD_ID !== undefined;
if (!DISCORD_ENABLED) {
pulumi.log.info('Discord integration disabled: botToken or guildId not configured');
}
const DISCORD_API_BASE = 'https://discord.com/api/v10';
interface DiscordApiError {
code: number;
message: string;
}
interface DiscordRateLimitResponse {
message: string;
retry_after: number;
global: boolean;
}
function sleep(ms: number): Promise<void> {
return new Promise((resolve) => setTimeout(resolve, ms));
}
async function discordFetch<T>(
token: string,
endpoint: string,
options: RequestInit = {},
maxRetries = 5
): Promise<T> {
let lastError: Error | undefined;
for (let attempt = 0; attempt <= maxRetries; attempt++) {
const response = await fetch(`${DISCORD_API_BASE}${endpoint}`, {
...options,
headers: {
Authorization: `Bot ${token}`,
'Content-Type': 'application/json',
...options.headers,
},
});
if (response.status === 429) {
const body = (await response.json()) as DiscordRateLimitResponse;
const retryAfterMs = Math.ceil(body.retry_after * 1000) + Math.random() * 250;
lastError = new Error(
`Discord API rate limited on ${endpoint} (retry_after=${body.retry_after}s, global=${body.global})`
);
if (attempt < maxRetries) {
await sleep(retryAfterMs);
continue;
}
throw lastError;
}
if (!response.ok) {
const error = (await response.json()) as DiscordApiError;
throw new Error(`Discord API error: ${error.message} (code: ${error.code})`);
}
// Handle 204 No Content
if (response.status === 204) {
return undefined as T;
}
return response.json() as Promise<T>;
}
throw (
lastError ?? new Error(`Discord API request to ${endpoint} failed after ${maxRetries} retries`)
);
}
// Discord API response types
interface DiscordRoleApiResponse {
id: string;
name: string;
position: number;
permissions: string;
managed: boolean;
}
interface DiscordGuildMemberApiResponse {
roles: string[];
}
// Discord Role Dynamic Provider
interface DiscordRoleInputs {
guildId: string;
roleName: string;
token: string;
}
interface DiscordRoleOutputs extends DiscordRoleInputs {
roleId: string;
}
const discordRoleProvider: pulumi.dynamic.ResourceProvider = {
async create(
inputs: DiscordRoleInputs
): Promise<pulumi.dynamic.CreateResult<DiscordRoleOutputs>> {
const role = await discordFetch<DiscordRoleApiResponse>(
inputs.token,
`/guilds/${inputs.guildId}/roles`,
{
method: 'POST',
body: JSON.stringify({
name: inputs.roleName,
permissions: '0', // No special permissions - roles are for organization only
mentionable: false,
hoist: false,
}),
}
);
return {
id: role.id,
outs: {
...inputs,
roleId: role.id,
},
};
},
async read(
id: string,
props: DiscordRoleOutputs
): Promise<pulumi.dynamic.ReadResult<DiscordRoleOutputs>> {
try {
const roles = await discordFetch<DiscordRoleApiResponse[]>(
props.token,
`/guilds/${props.guildId}/roles`
);
const role = roles.find((r) => r.id === id);
if (!role) {
// Role was deleted externally
throw new Error(`Role ${id} not found`);
}
return {
id,
props: {
...props,
roleName: role.name,
roleId: role.id,
},
};
} catch (error) {
throw new Error(`Failed to read role ${id}: ${error}`);
}
},
async update(
id: string,
_olds: DiscordRoleOutputs,
news: DiscordRoleInputs
): Promise<pulumi.dynamic.UpdateResult<DiscordRoleOutputs>> {
await discordFetch<DiscordRoleApiResponse>(news.token, `/guilds/${news.guildId}/roles/${id}`, {
method: 'PATCH',
body: JSON.stringify({
name: news.roleName,
}),
});
return {
outs: {
...news,
roleId: id,
},
};
},
async delete(id: string, props: DiscordRoleOutputs): Promise<void> {
try {
await discordFetch<void>(props.token, `/guilds/${props.guildId}/roles/${id}`, {
method: 'DELETE',
});
} catch (error) {
// Ignore errors if role is already deleted
console.warn(`Failed to delete role ${id}: ${error}`);
}
},
};
class DiscordRole extends pulumi.dynamic.Resource {
public readonly roleId!: pulumi.Output<string>;
public readonly roleName!: pulumi.Output<string>;
public readonly guildId!: pulumi.Output<string>;
constructor(
name: string,
args: {
guildId: pulumi.Input<string>;
roleName: pulumi.Input<string>;
token: pulumi.Input<string>;
},
opts?: pulumi.CustomResourceOptions
) {
super(
discordRoleProvider,
name,
{
roleId: undefined,
...args,
},
opts
);
}
}
// Discord Member Role Sync Dynamic Provider
// This provider reconciles a user's roles to match exactly what's defined in config
// It adds missing roles AND removes extra roles (only for roles we manage)
interface DiscordMemberRoleSyncInputs {
guildId: string;
userId: string;
/** Role IDs that this user SHOULD have (managed roles only) */
expectedRoleIds: string[];
/** All role IDs that we manage (to know which ones to potentially remove) */
managedRoleIds: string[];
token: string;
}
interface DiscordMemberRoleSyncOutputs extends DiscordMemberRoleSyncInputs {
/** Roles that were added during last sync */
addedRoles: string[];
/** Roles that were removed during last sync */
removedRoles: string[];
/** True if the member was not found on the Discord server */
memberNotFound: boolean;
}
async function syncMemberRoles(
inputs: DiscordMemberRoleSyncInputs
): Promise<{ addedRoles: string[]; removedRoles: string[]; memberNotFound: boolean }> {
// Get the user's current roles
let member: DiscordGuildMemberApiResponse;
try {
member = await discordFetch<DiscordGuildMemberApiResponse>(
inputs.token,
`/guilds/${inputs.guildId}/members/${inputs.userId}`
);
} catch (error) {
// If the member isn't on the server, skip gracefully
if (error instanceof Error && error.message.includes('code: 10007')) {
console.warn(
`Discord member ${inputs.userId} not found on server - skipping role sync. ` +
`They may have left the server or the Discord ID may be incorrect.`
);
return { addedRoles: [], removedRoles: [], memberNotFound: true };
}
throw error;
}
const currentRoles = new Set(member.roles);
const expectedRoles = new Set(inputs.expectedRoleIds);
const managedRoles = new Set(inputs.managedRoleIds);
const addedRoles: string[] = [];
const removedRoles: string[] = [];
// Add missing roles
for (const roleId of Array.from(expectedRoles)) {
if (!currentRoles.has(roleId)) {
await discordFetch<void>(
inputs.token,
`/guilds/${inputs.guildId}/members/${inputs.userId}/roles/${roleId}`,
{ method: 'PUT' }
);
addedRoles.push(roleId);
}
}
// Remove roles that the user has but shouldn't (only managed roles)
for (const roleId of Array.from(currentRoles)) {
if (managedRoles.has(roleId) && !expectedRoles.has(roleId)) {
await discordFetch<void>(
inputs.token,
`/guilds/${inputs.guildId}/members/${inputs.userId}/roles/${roleId}`,
{ method: 'DELETE' }
);
removedRoles.push(roleId);
}
}
return { addedRoles, removedRoles, memberNotFound: false };
}
const discordMemberRoleSyncProvider: pulumi.dynamic.ResourceProvider = {
async create(
inputs: DiscordMemberRoleSyncInputs
): Promise<pulumi.dynamic.CreateResult<DiscordMemberRoleSyncOutputs>> {
const { addedRoles, removedRoles, memberNotFound } = await syncMemberRoles(inputs);
return {
id: inputs.userId,
outs: {
...inputs,
addedRoles,
removedRoles,
memberNotFound,
},
};
},
async read(
id: string,
props: DiscordMemberRoleSyncOutputs
): Promise<pulumi.dynamic.ReadResult<DiscordMemberRoleSyncOutputs>> {
let member: DiscordGuildMemberApiResponse;
try {
member = await discordFetch<DiscordGuildMemberApiResponse>(
props.token,
`/guilds/${props.guildId}/members/${props.userId}`
);
} catch (error) {
// If the member isn't on the server, return state indicating they're not found
if (error instanceof Error && error.message.includes('code: 10007')) {
return {
id,
props: {
...props,
addedRoles: [],
removedRoles: [],
memberNotFound: true,
},
};
}
throw new Error(`Failed to read member roles for ${id}: ${error}`);
}
const currentRoles = new Set(member.roles);
const expectedRoles = new Set(props.expectedRoleIds);
const managedRoles = new Set(props.managedRoleIds);
// Check if roles are in sync (only considering managed roles)
const outOfSync =
Array.from(expectedRoles).some((r) => !currentRoles.has(r)) ||
Array.from(currentRoles).some((r) => managedRoles.has(r) && !expectedRoles.has(r));
if (outOfSync) {
// Return current state but note it needs update
return {
id,
props: {
...props,
addedRoles: [],
removedRoles: [],
memberNotFound: false,
},
};
}
return { id, props: { ...props, memberNotFound: false } };
},
async update(
id: string,
_olds: DiscordMemberRoleSyncOutputs,
news: DiscordMemberRoleSyncInputs
): Promise<pulumi.dynamic.UpdateResult<DiscordMemberRoleSyncOutputs>> {
const { addedRoles, removedRoles, memberNotFound } = await syncMemberRoles(news);
return {
outs: {
...news,
addedRoles,
removedRoles,
memberNotFound,
},
};
},
async delete(id: string, props: DiscordMemberRoleSyncOutputs): Promise<void> {
// When a user is removed from config, remove all their managed roles
for (const roleId of props.expectedRoleIds) {
try {
await discordFetch<void>(
props.token,
`/guilds/${props.guildId}/members/${props.userId}/roles/${roleId}`,
{ method: 'DELETE' }
);
} catch (error) {
console.warn(`Failed to remove role ${roleId} from user ${id}: ${error}`);
}
}
},
};
class DiscordMemberRoleSync extends pulumi.dynamic.Resource {
public readonly addedRoles!: pulumi.Output<string[]>;
public readonly removedRoles!: pulumi.Output<string[]>;
public readonly memberNotFound!: pulumi.Output<boolean>;
constructor(
name: string,
args: {
guildId: pulumi.Input<string>;
userId: pulumi.Input<string>;
expectedRoleIds: pulumi.Input<pulumi.Input<string>[]>;
managedRoleIds: pulumi.Input<pulumi.Input<string>[]>;
token: pulumi.Input<string>;
},
opts?: pulumi.CustomResourceOptions
) {
super(
discordMemberRoleSyncProvider,
name,
{
addedRoles: undefined,
removedRoles: undefined,
memberNotFound: undefined,
...args,
},
opts
);
}
}
const roleLookup = buildRoleLookup();
// Discord roles keyed by Discord role name
const roles: Record<string, DiscordRole> = {};
/**
* Expand a set of role IDs to include all implied Discord roles.
* This traverses:
* 1. GitHub parent relationships (e.g., GO_SDK -> SDK_MAINTAINERS)
* 2. discordImplies relationships (e.g., SDK_MAINTAINERS -> MAINTAINERS)
*/
function expandDiscordRoles(roleIds: readonly RoleId[]): Set<RoleId> {
const expanded = new Set<RoleId>();
const toProcess = [...roleIds];
while (toProcess.length > 0) {
const roleId = toProcess.pop()!;
if (expanded.has(roleId)) continue;
expanded.add(roleId);
const role = roleLookup.get(roleId);
if (!role) continue;
// Follow GitHub parent relationship
if (role.github?.parent) {
toProcess.push(role.github.parent);
}
// Follow discordImplies relationships
if (role.discordImplies) {
toProcess.push(...role.discordImplies);
}
}
return expanded;
}
// Only create Discord resources if Discord is enabled
if (DISCORD_ENABLED) {
// These are guaranteed to be defined when DISCORD_ENABLED is true
const guildId = DISCORD_GUILD_ID!;
const botToken = DISCORD_BOT_TOKEN!;
// Create Discord roles for roles that have Discord config
ROLES.forEach((role: Role) => {
if (!role.discord) return;
roles[role.discord.role] = new DiscordRole(`discord-role-${role.id}`, {
guildId,
roleName: role.discord.role,
token: botToken,
});
});
// Collect all managed role IDs (roles that have Discord config)
const allManagedRoleIds = ROLES.filter((r) => r.discord).map(
(r) => roles[r.discord!.role].roleId
);
// Sync roles for each member
MEMBERS.forEach((member) => {
if (!member.discord) return;
// Expand roles to include parents and implied roles
const expandedRoleIds = expandDiscordRoles(member.memberOf);
// Get the Discord role IDs this member should have
const expectedRoleIds = Array.from(expandedRoleIds)
.map((roleId: RoleId) => {
const role = roleLookup.get(roleId);
if (!role?.discord) return null;
return roles[role.discord.role].roleId;
})
.filter((id): id is pulumi.Output<string> => id !== null);
// Create a sync resource for this member
new DiscordMemberRoleSync(
`discord-member-sync-${member.discord}`,
{
guildId,
userId: member.discord!,
expectedRoleIds,
managedRoleIds: allManagedRoleIds,
token: botToken,
},
{ dependsOn: Object.values(roles) }
);
});
}
export { roles as discordRoles };