forked from rust-lang/triagebot
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathzulip.rs
More file actions
1669 lines (1525 loc) · 57.6 KB
/
zulip.rs
File metadata and controls
1669 lines (1525 loc) · 57.6 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
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
pub mod api;
pub mod client;
mod commands;
use crate::db::notifications::{
self, Identifier, add_metadata, delete_ping, move_indices, record_ping,
};
use crate::db::review_prefs::{
ReviewPreferences, RotationMode, get_review_prefs, get_review_prefs_batch,
upsert_repo_review_prefs, upsert_team_review_prefs, upsert_user_review_prefs,
};
use crate::db::users::DbUser;
use crate::github;
use crate::github::queries::user_comments_in_org::UserComment;
use crate::github::queries::user_prs::PullRequestState;
use crate::github::queries::user_prs::UserPullRequest;
use crate::handlers::Context;
use crate::handlers::docs_update::docs_update;
use crate::handlers::pr_tracking::{ReviewerWorkqueue, get_assigned_prs};
use crate::handlers::project_goals::{self, ping_project_goals_owners};
use crate::interactions::ErrorComment;
use crate::utils::pluralize;
use crate::zulip::api::{MessageApiResponse, Recipient};
use crate::zulip::client::ZulipClient;
use crate::zulip::commands::{
BackportChannelArgs, BackportVerbArgs, ChatCommand, LookupCmd, PingGoalsArgs, StreamCommand,
WorkqueueCmd, WorkqueueLimit, parse_cli,
};
use anyhow::{Context as _, format_err};
use axum::Json;
use axum::extract::State;
use axum::extract::rejection::JsonRejection;
use axum::response::IntoResponse;
use chrono::{DateTime, Duration, Utc};
use commands::BackportArgs;
use itertools::Itertools;
use rust_team_data::v1::{TeamKind, TeamMember};
use secrecy::{ExposeSecret, SecretString};
use std::cmp::{Ordering, Reverse};
use std::collections::{HashMap, HashSet};
use std::fmt::Write as _;
use std::sync::Arc;
use subtle::ConstantTimeEq;
use tracing::log;
fn get_text_backport_approved(
channel: &BackportChannelArgs,
verb: &BackportVerbArgs,
zulip_link: &str,
) -> String {
format!(
"{channel} backport {verb} as per compiler team [on Zulip]({zulip_link}). A backport PR will be authored by the release team at the end of the current development cycle. Backport labels are handled by them."
)
}
fn get_text_backport_declined(
channel: &BackportChannelArgs,
verb: &BackportVerbArgs,
zulip_link: &str,
) -> String {
format!("{channel} backport {verb} as per compiler team [on Zulip]({zulip_link}).")
}
#[derive(Debug, serde::Deserialize)]
pub struct Request {
/// Markdown body of the sent message.
data: String,
/// Metadata about this request.
message: Message,
/// Authentication token. The same for all Zulip messages.
token: SecretString,
}
#[derive(Clone, Debug, serde::Deserialize)]
struct Message {
sender_id: u64,
/// A unique ID for the set of users receiving the message (either a
/// stream or group of users). Useful primarily for hashing.
#[allow(unused)]
recipient_id: u64,
sender_full_name: String,
sender_email: String,
/// The ID of the stream.
///
/// `None` if it is a private message.
stream_id: Option<u64>,
/// The topic of the incoming message. Not the stream name.
///
/// Not currently set for private messages (though Zulip may change this in
/// the future if it adds topics to private messages).
subject: Option<String>,
/// The type of the message: stream or private.
#[allow(unused)]
#[serde(rename = "type")]
type_: String,
}
impl Message {
/// Creates a `Recipient` that will be addressed to the sender of this message.
fn sender_to_recipient(&self) -> Recipient<'_> {
match self.stream_id {
Some(id) => Recipient::Stream {
id,
topic: self
.subject
.as_ref()
.expect("stream messages should have a topic"),
},
None => Recipient::Private {
id: self.sender_id,
email: &self.sender_email,
},
}
}
}
#[derive(serde::Serialize, serde::Deserialize)]
struct Response {
content: String,
}
/// Top-level handler for Zulip webhooks.
///
/// Returns a JSON response or a 400 with an error message.
pub async fn webhook(
State(ctx): State<Arc<Context>>,
req: Result<Json<Request>, JsonRejection>,
) -> axum::response::Response {
let Json(req) = match req {
Ok(req) => req,
Err(rejection) => {
tracing::error!(?rejection);
return Json(Response {
content: ErrorComment::markdown(
"unable to handle this Zulip request: invalid JSON input",
)
.expect("creating a error message without fail"),
})
.into_response();
}
};
tracing::info!(?req);
let response = process_zulip_request(ctx, req).await;
tracing::info!(?response);
match response {
Ok(None) => Json(ResponseNotRequired {
response_not_required: true,
})
.into_response(),
Ok(Some(content)) => Json(Response { content }).into_response(),
Err(err) => {
// We are mixing network errors and "logic" error (like clap errors)
// so don't return a 500. Long term we should decouple those.
// Reply with a 200 and reply only with outermost error
Json(Response {
content: err.to_string(),
})
.into_response()
}
}
}
pub fn get_token_from_env() -> Result<SecretString, anyhow::Error> {
#[expect(clippy::bind_instead_of_map, reason = "`.map_err` is suggested, but we don't really map the error")]
// ZULIP_WEBHOOK_SECRET is preferred, ZULIP_TOKEN is kept for retrocompatibility but will be deprecated
std::env::var("ZULIP_WEBHOOK_SECRET")
.or_else(|_| std::env::var("ZULIP_TOKEN"))
.or_else(|_| {
log::error!(
"Cannot communicate with Zulip: neither ZULIP_WEBHOOK_SECRET or ZULIP_TOKEN are set."
);
Err(anyhow::anyhow!("Cannot communicate with Zulip."))
})
.map(|v| v.into())
}
/// Processes a Zulip webhook.
///
/// Returns a string of the response, or None if no response is needed.
async fn process_zulip_request(ctx: Arc<Context>, req: Request) -> anyhow::Result<Option<String>> {
let expected_token = get_token_from_env()?;
if !bool::from(
req.token
.expose_secret()
.as_bytes()
.ct_eq(expected_token.expose_secret().as_bytes()),
) {
anyhow::bail!("Invalid authorization.");
}
// Zulip commands are only available to users in the team database
let gh_id = match ctx.team.zulip_to_github_id(req.message.sender_id).await {
Ok(Some(gh_id)) => gh_id,
Ok(None) => {
return Err(anyhow::anyhow!(
"Unknown Zulip user. Please add `zulip-id = {}` to your file in \
[rust-lang/team](https://github.com/rust-lang/team).",
req.message.sender_id
));
}
Err(e) => anyhow::bail!("Failed to query team API: {e:?}"),
};
handle_command(ctx, gh_id, &req.data, &req.message).await
}
async fn handle_command<'a>(
ctx: Arc<Context>,
mut gh_id: u64,
message: &'a str,
message_data: &'a Message,
) -> anyhow::Result<Option<String>> {
log::trace!("handling zulip message {:?}", message);
// Missing stream means that this is a direct message
if message_data.stream_id.is_none() {
let mut words: Vec<&str> = message.split_whitespace().collect();
// Parse impersonation
let mut impersonated = false;
#[expect(clippy::get_first, reason = "for symmetry with `get(1)`")]
if let Some(&"as") = words.get(0) {
if let Some(username) = words.get(1) {
let impersonated_gh_id = ctx
.team
.get_gh_id_from_username(username)
.await
.context("getting ID of github user")?
.context("Can only authorize for other GitHub users.")?;
// Impersonate => change actual gh_id
if impersonated_gh_id != gh_id {
impersonated = true;
gh_id = impersonated_gh_id;
}
// Skip the first two arguments for the rest of CLI parsing
words = words[2..].to_vec();
} else {
return Err(anyhow::anyhow!(
"Failed to parse command; expected `as <username> <command...>`."
));
}
}
let cmd = parse_cli::<ChatCommand, _>(words.into_iter())?;
let impersonation_mode = get_cmd_impersonation_mode(&cmd);
if impersonated && matches!(impersonation_mode, ImpersonationMode::Disabled) {
return Err(anyhow::anyhow!(
"This command cannot be used with impersonation. Remove the `as <user>` prefix."
));
}
tracing::info!("command parsed to {cmd:?} (impersonated: {impersonated})");
let output = match &cmd {
ChatCommand::Acknowledge { identifier } => {
acknowledge(&ctx, gh_id, identifier.into()).await
}
ChatCommand::Add { url, description } => {
add_notification(&ctx, gh_id, url, &description.join(" ")).await
}
ChatCommand::Move { from, to } => move_notification(&ctx, gh_id, *from, *to).await,
ChatCommand::Meta { index, description } => {
add_meta_notification(&ctx, gh_id, *index, &description.join(" ")).await
}
ChatCommand::Whoami => whoami_cmd(&ctx, gh_id).await,
ChatCommand::Lookup(cmd) => lookup_cmd(&ctx, cmd).await,
ChatCommand::Work(cmd) => workqueue_commands(&ctx, gh_id, cmd).await,
ChatCommand::PingGoals(args) => {
ping_goals_cmd(ctx.clone(), gh_id, message_data, args).await
}
ChatCommand::DocsUpdate => trigger_docs_update(message_data, &ctx.zulip),
ChatCommand::UserInfo {
username,
organization,
} => user_info_cmd(&ctx, gh_id, username, &organization)
.await
.map(Some),
ChatCommand::TeamStats { name, repo } => {
let repo = normalize_repo(&ctx, repo).await?;
team_status_cmd(&ctx, name, &repo).await
}
};
let output = output?;
// Let the impersonated person know about the impersonation if we should notify
if impersonated && matches!(impersonation_mode, ImpersonationMode::Notify) {
let impersonated_zulip_id =
ctx.team.github_to_zulip_id(gh_id).await?.ok_or_else(|| {
anyhow::anyhow!("Zulip user for GitHub ID {gh_id} was not found")
})?;
let users = ctx.zulip.get_zulip_users().await?;
let user = users
.iter()
.find(|m| m.user_id == impersonated_zulip_id)
.ok_or_else(|| format_err!("Could not find Zulip user email."))?;
let sender = &message_data.sender_full_name;
let message = format!(
"{sender} ran `{message}` on your behalf. Output:\n{}",
output.as_deref().unwrap_or("<empty>")
);
MessageApiRequest {
recipient: Recipient::Private {
id: user.user_id,
email: &user.email,
},
content: &message,
}
.send(&ctx.zulip)
.await?;
}
Ok(output)
} else {
// We are in a stream, where someone wrote `@**triagebot** <command(s)>`
//
// Yet we need to process each lines separately as the command can only be
// one line.
for line in message.lines() {
let words: Vec<&str> = line.split_whitespace().collect();
// Try to find the ping, continue to the next line if we don't find it here.
let Some(cmd_index) = words.iter().position(|w| *w == "@**triagebot**") else {
continue;
};
// Skip @**triagebot**
let cmd_index = cmd_index + 1;
// Error on unexpected end-of-line
if cmd_index >= words.len() {
return Ok(Some(
"Error parsing command: unexpected end-of-line".to_string(),
));
}
let cmd = parse_cli::<StreamCommand, _>(words[cmd_index..].iter().copied())?;
tracing::info!("command parsed to {cmd:?}");
// Process the command and early return (we don't expect multi-commands in the
// same message)
return match cmd {
StreamCommand::EndTopic => {
post_waiter(&ctx, message_data, WaitingMessage::end_topic())
.await
.map_err(|e| format_err!("Failed to await at this time: {e:?}"))
}
StreamCommand::EndMeeting => {
post_waiter(&ctx, message_data, WaitingMessage::end_meeting())
.await
.map_err(|e| format_err!("Failed to await at this time: {e:?}"))
}
StreamCommand::Read => {
post_waiter(&ctx, message_data, WaitingMessage::start_reading())
.await
.map_err(|e| format_err!("Failed to await at this time: {e:?}"))
}
StreamCommand::PingGoals(args) => {
ping_goals_cmd(ctx, gh_id, message_data, &args).await
}
StreamCommand::DocsUpdate => trigger_docs_update(message_data, &ctx.zulip),
StreamCommand::Backport(args) => {
accept_decline_backport(ctx, message_data, &args).await
}
StreamCommand::UserInfo {
username,
organization,
} => user_info_cmd(&ctx, gh_id, &username, &organization)
.await
.map(Some),
};
}
tracing::warn!("no command found, yet we were pinged, weird");
Ok(Some("Unknown command".to_string()))
}
}
// TODO: shorter variant of this command (f.e. `backport accept` or even `accept`) that infers everything from the Message payload
async fn accept_decline_backport(
ctx: Arc<Context>,
message_data: &Message,
args_data: &BackportArgs,
) -> anyhow::Result<Option<String>> {
let message = message_data.clone();
let args = args_data.clone();
let stream_id = message.stream_id.unwrap();
let subject = message.subject.unwrap();
let zulip_client = &ctx.zulip;
// Repository owner and name are hardcoded
// This command is only used in this repository
let repo_owner = std::env::var("MAIN_GH_REPO_OWNER").unwrap_or("rust-lang".to_string());
let repo_name = std::env::var("MAIN_GH_REPO_NAME").unwrap_or("rust".to_string());
let issue_repo = github::IssueRepository {
organization: repo_owner.clone(),
repository: repo_name.clone(),
};
let issue = ctx
.github
.pull_request(&issue_repo, args.pr_num)
.await
.context(format!(
"Could not get #{} details (hint: maybe not a PR?)",
args.pr_num
))?;
let nominated = issue.labels.iter().any(|l| l.name.contains("-nominated"));
if !nominated {
return Ok(Some(format!(
"Can't approve backport: #{} was not {} nominated",
&args.pr_num, args.channel,
)));
}
// TODO: factor out the Zulip "URL encoder" to make it practical to use
let zulip_send_req = crate::zulip::MessageApiRequest {
recipient: Recipient::Stream {
id: stream_id,
topic: &subject,
},
content: "",
};
// NOTE: the Zulip Message API cannot yet pin exactly a single message so the link in the GitHub comment will be to the whole topic
// See: https://rust-lang.zulipchat.com/#narrow/channel/122653-zulip/topic/.22near.22.20parameter.20in.20payload.20of.20send.20message.20API
let zulip_link = zulip_send_req.url(zulip_client);
let (message_body, approve_backport) = match args.verb {
BackportVerbArgs::Accept
| BackportVerbArgs::Accepted
| BackportVerbArgs::Approve
| BackportVerbArgs::Approved => (
get_text_backport_approved(&args.channel, &args.verb, &zulip_link),
true,
),
BackportVerbArgs::Decline | BackportVerbArgs::Declined => (
get_text_backport_declined(&args.channel, &args.verb, &zulip_link),
false,
),
};
// post a comment on GitHub
issue
.post_comment(&ctx.github, &message_body)
.await
.with_context(|| anyhow::anyhow!("unable to post comment on #{}", args.pr_num))?;
// Add or remove backport labels
if approve_backport {
issue
.add_labels(
&ctx.github,
vec![github::Label {
name: format!("{}-accepted", args.channel),
}],
)
.await
.context("failed to add labels to the issue")?;
} else {
issue
.remove_labels(
&ctx.github,
vec![
github::Label {
name: format!("{}-nominated", args.channel),
},
github::Label {
name: format!("{}-accepted", args.channel),
},
],
)
.await
.context("failed to remove labels from the issue")?;
}
Ok(None)
}
async fn ping_goals_cmd(
ctx: Arc<Context>,
gh_id: u64,
message: &Message,
args: &PingGoalsArgs,
) -> anyhow::Result<Option<String>> {
if project_goals::check_project_goal_acl(&ctx.team, gh_id).await? {
let args = args.clone();
let message = message.clone();
tokio::spawn(async move {
let res = ping_project_goals_owners(
&ctx.github,
&ctx.zulip,
&ctx.team,
false,
args.threshold as i64,
&format!("on {}", args.next_update),
)
.await;
let status = match res {
Ok(_res) => "OK".to_string(),
Err(err) => {
tracing::error!("ping_project_goals_owners: {err:?}");
format!("ERROR\n\n```\n{err:#?}\n```\n")
}
};
let res = MessageApiRequest {
recipient: message.sender_to_recipient(),
content: &format!("End pinging project groups owners: {status}"),
}
.send(&ctx.zulip)
.await;
if let Err(err) = res {
tracing::error!(
"error sending project goals ping reply: {err:?} for status: {status}"
);
}
});
Ok(Some("Started pinging project groups owners...".to_string()))
} else {
Err(format_err!(
"That command is only permitted for those running the project-goal program.",
))
}
}
/// Output recent GitHub activity made by a given user (both globally and in a given organization).
/// This command can only be used by team members.
async fn user_info_cmd(
ctx: &Context,
gh_id: u64,
username: &str,
organization: &str,
) -> anyhow::Result<String> {
const RECENT_COMMENTS_LIMIT: usize = 10;
let gh_login = ctx
.team
.username_from_gh_id(gh_id)
.await?
.ok_or_else(|| anyhow::anyhow!("Username for GitHub user {gh_id} not found"))?;
if !ctx.team.is_team_member(&gh_login).await? {
return Err(anyhow::anyhow!(
"This command is only available to team members."
));
}
if ctx.team.repos().await?.repos.get(organization).is_none() {
return Err(anyhow::anyhow!(
"Organization `{organization}` is not managed by the team database."
));
}
let pr_limit = 100;
let recent_days = 7;
// Load data concurrently to make the command faster
let (user, user_prs, org_user_prs, user_repos) = futures::future::join4(
ctx.github.user_info(username),
ctx.github.recent_user_prs(username, pr_limit),
ctx.github
.recent_user_prs_in_org(username, organization, pr_limit),
ctx.github.recent_user_repositories(username, 100),
)
.await;
let (user, user_prs, org_user_prs, user_repos) = (user?, user_prs?, org_user_prs?, user_repos?);
let recent_date_cutoff = Utc::now() - Duration::days(recent_days as i64);
let all_prs_stats = analyze_pr_stats(&user_prs, pr_limit, recent_days);
let org_prs_stats = analyze_pr_stats(&org_user_prs, pr_limit, recent_days);
let pr_orgs = all_prs_stats
.recent_prs
.iter()
.map(|pr| pr.repo_owner.clone())
.collect::<HashSet<_>>();
let pr_repo_count = all_prs_stats
.recent_prs
.iter()
.map(|pr| format!("{}/{}", pr.repo_owner, pr.repo_name))
.collect::<HashSet<_>>()
.len();
let org_pr_count = pr_orgs.len();
let opened_orgs = if org_pr_count > 0 {
let mut orgs = pr_orgs.into_iter().collect::<Vec<_>>();
orgs.sort();
let orgs = orgs
.into_iter()
.take(10)
.map(|org| format!("`{org}`"))
.join(", ");
format!(" ({orgs})")
} else {
String::new()
};
let mut open_prs = 0;
let mut closed_prs = 0;
let mut merged_prs = 0;
for pr in &all_prs_stats.recent_prs {
match pr.state {
PullRequestState::Open => open_prs += 1,
PullRequestState::Closed => closed_prs += 1,
PullRequestState::Merged => merged_prs += 1,
}
}
let mut org_open_prs = 0;
let mut org_closed_prs = 0;
let mut org_merged_prs = 0;
for pr in &org_prs_stats.recent_prs {
match pr.state {
PullRequestState::Open => org_open_prs += 1,
PullRequestState::Closed => org_closed_prs += 1,
PullRequestState::Merged => org_merged_prs += 1,
}
}
let recently_opened_repos = user_repos
.iter()
.filter(|repo| repo.created_at >= recent_date_cutoff)
.collect::<Vec<_>>();
let recent_forks = recently_opened_repos
.iter()
.filter(|repo| repo.fork)
.count();
let recent_contributions_days = Duration::days(90);
let contributions = ctx
.github
.user_contributions_since(username, Utc::now() - recent_contributions_days)
.await
.context("Cannot load user contributions")?;
let mut message = format!(
r#"# User `{username}` activity
- Account created at: {date} ({ago})
- Public repository count: {repos}
- Repositories created in past {recent_days} days: `{recent_repo_count}` ({recent_forks} of those are forks)
## GitHub activity in the past {recent_days} days
The user opened `{recent_pr_count}{more_prs}` PRs ({open_prs} open, {merged_prs} merged, {closed_prs} closed) in `{pr_repo_count}` repo(s) and `{org_pr_count}` organization(s){opened_orgs}.
## GitHub activity in the past {contributions_since} days
- Created `{contribution_prs}` PRs
- Created `{contribution_issues}` issues
- Created `{contribution_commits}` commits
- Created `{contribution_repos}` repositories
## `{organization}` activity in the past {recent_days} days
The user opened `{org_recent_pr_count}{org_more_prs}` PRs ({org_open_prs} open, {org_merged_prs} merged, {org_closed_prs} closed).
"#,
date = format_date(Some(user.created_at)),
ago = format!("`{}` days ago", (Utc::now() - user.created_at).num_days()),
repos = user.public_repos,
recent_pr_count = all_prs_stats.recent_pr_count,
org_recent_pr_count = org_prs_stats.recent_pr_count,
more_prs = if all_prs_stats.maybe_has_more {
"+"
} else {
""
},
org_more_prs = if org_prs_stats.maybe_has_more {
"+"
} else {
""
},
recent_repo_count = recently_opened_repos.len(),
contributions_since = recent_contributions_days.num_days(),
contribution_prs = contributions.total_created_prs,
contribution_commits = contributions.total_created_commits,
contribution_issues = contributions.total_created_issues,
contribution_repos = contributions.total_created_repos,
);
let comments = ctx
.github
.recent_user_comments_in_org(username, organization, RECENT_COMMENTS_LIMIT)
.await
.context("Cannot load recent comments")?;
if !comments.is_empty() {
message.push_str(&format!("\n\n## Recent comments in `{organization}`\n"));
for comment in &comments {
message.push_str(&format_user_comment(comment));
}
}
Ok(message)
}
struct PullRequestStats<'a> {
recent_prs: Vec<&'a UserPullRequest>,
recent_pr_count: u64,
// Does the user possibly have more recent PRs than `recent_count`?
// This can happen when we do not fetch enough PRs from GitHub.
maybe_has_more: bool,
}
fn analyze_pr_stats(
prs: &[UserPullRequest],
pr_limit: usize,
recent_days: u32,
) -> PullRequestStats<'_> {
let recent_pr_cutoff = Utc::now() - Duration::days(recent_days as i64);
let recent_prs: Vec<&UserPullRequest> = prs
.iter()
.filter(|pr| {
let Some(date) = pr.created_at else {
return false;
};
date >= recent_pr_cutoff
})
.collect();
let oldest_pr_created_at = prs.last().and_then(|pr| pr.created_at);
let maybe_has_more = oldest_pr_created_at
.map(|date| date > recent_pr_cutoff)
.unwrap_or(false)
&& prs.len() == pr_limit;
PullRequestStats {
recent_pr_count: recent_prs.len() as u64,
recent_prs,
maybe_has_more,
}
}
async fn team_status_cmd(
ctx: &Context,
team_name: &str,
repo: &str,
) -> anyhow::Result<Option<String>> {
use std::fmt::Write;
let Some(team) = ctx.team.get_team(team_name).await? else {
return Ok(Some(format!("Team {team_name} not found")));
};
let mut members = team.members;
members.sort_by(|a, b| a.github.cmp(&b.github));
let usernames: Vec<&str> = members
.iter()
.map(|member| member.github.as_str())
.collect();
let db = ctx.db.get().await;
let review_prefs = get_review_prefs_batch(&db, &usernames)
.await
.context("cannot load review preferences")?;
// If a repository name was provided then check for an adhoc group named after that team in
// that repository's `triagebot.toml` and require that team members be in that list to be
// considered on rotation.
let adhoc_group: Option<Vec<String>> = {
let repo = ctx
.github
.repository(repo)
.await
.context("failed retrieving the repository informations")?;
let config = crate::config::get(&ctx.github, &repo)
.await
.context("failed to get triagebot configuration")?;
if let Some(adhoc_group) = config
.assign
.as_ref()
.and_then(|a| a.adhoc_groups.get(team_name))
{
Some(
adhoc_group
.into_iter()
.map(|reviewer| {
// Adhoc groups reviewers are by convention prefixed with `@`, let's
// strip it to avoid issues with unprefixed GitHub handles.
//
// Also lowercase the reviewer, in case it has a different
// casing between our different sources.
reviewer
.strip_prefix('@')
.unwrap_or(reviewer)
.to_lowercase()
})
.collect(),
)
} else {
None
}
};
let workqueue_arc = ctx
.workqueue_map
.get(repo)
.unwrap_or_else(|| Arc::new(tokio::sync::RwLock::new(ReviewerWorkqueue::default())));
let workqueue = workqueue_arc.read().await;
let total_assigned: u64 = members
.iter()
.map(|member| workqueue.assigned_pr_count(member.github_id))
.sum();
let mut available = vec![];
let mut full_capacity = vec![];
let mut off_rotation = vec![];
for member in &members {
let status = get_reviewer_status(
member,
&review_prefs,
repo,
team_name,
adhoc_group.as_ref(),
&workqueue,
);
match status {
ReviewerStatus::Available => available.push((member, status)),
ReviewerStatus::FullCapacity => full_capacity.push((member, status)),
status => off_rotation.push((member, status)),
}
}
available.sort_by_key(|(member, _)| Reverse(workqueue.assigned_pr_count(member.github_id)));
full_capacity.sort_by_key(|(member, _)| Reverse(workqueue.assigned_pr_count(member.github_id)));
off_rotation.sort_by(|(member_a, status_a), (member_b, status_b)| {
// Order by off rotation reason first
match (status_a, status_b) {
(ReviewerStatus::OffRotationGlobally, ReviewerStatus::OffRotationThroughTeam) => {
return Ordering::Less;
}
(ReviewerStatus::OffRotationThroughTeam, ReviewerStatus::OffRotationGlobally) => {
return Ordering::Greater;
}
_ => {}
}
// Then by assigned PR count
workqueue
.assigned_pr_count(member_a.github_id)
.cmp(&workqueue.assigned_pr_count(member_b.github_id))
.reverse()
});
let format_row = |(member, status): (&TeamMember, ReviewerStatus)| {
let review_prefs = review_prefs.get(member.github.as_str());
let max_capacity = review_prefs
.as_ref()
.and_then(|prefs| prefs.repo_review_prefs.get(repo))
.and_then(|prefs| prefs.max_assigned_prs)
.map(|c| c.to_string());
let max_capacity = max_capacity.as_deref().unwrap_or("unlimited");
let assigned_prs = workqueue.assigned_pr_count(member.github_id);
let status = match status {
ReviewerStatus::Available => format_args!(":check:"),
ReviewerStatus::FullCapacity => format_args!(":stop_sign:"),
ReviewerStatus::NotInAdhocGroup => format_args!("Not in adhoc group"),
ReviewerStatus::OffRotationGlobally => format_args!("Off (global)"),
ReviewerStatus::OffRotationThroughTeam => format_args!("Off ({team_name})"),
};
format!(
"| `{}` | {} | `{assigned_prs}` | `{max_capacity}` | {status} |",
member.github, member.name
)
};
let write_table = |msg: &mut String,
members: Vec<(&TeamMember, ReviewerStatus)>,
title: &str,
align_left: bool| {
if members.is_empty() {
return;
}
let rows = members.into_iter().map(format_row).collect::<Vec<_>>();
writeln!(
msg,
r"### {title} ({})
| Username | Name | Assigned PRs | Review capacity | Status |
|----------|------|-------------:|----------------:|:--------{}|",
rows.len(),
if align_left { "" } else { ":" }
)
.unwrap();
writeln!(msg, "{}\n", rows.join("\n")).unwrap();
};
// e.g. 2 members, 5 PRs assigned
let mut msg = format!(
r#"`{team_name}` team stats for the `{repo}` repository:
{} {}, {} {} assigned
"#,
members.len(),
pluralize("member", members.len()),
total_assigned,
pluralize("PR", total_assigned as usize)
);
write_table(&mut msg, available, "Available", false);
write_table(&mut msg, full_capacity, "Full capacity", false);
write_table(&mut msg, off_rotation, "Off rotation", true);
Ok(Some(msg))
}
enum ReviewerStatus {
Available,
FullCapacity,
NotInAdhocGroup,
OffRotationGlobally,
OffRotationThroughTeam,
}
fn get_reviewer_status(
member: &TeamMember,
review_prefs: &HashMap<&str, ReviewPreferences>,
repo: &str,
team_name: &str,
adhoc_group: Option<&Vec<String>>,
workqueue: &ReviewerWorkqueue,
) -> ReviewerStatus {
let prefs = review_prefs.get(member.github.as_str());
let rotation_mode = prefs.map(|prefs| prefs.rotation_mode).unwrap_or_default();
let team_rotation_mode = prefs
.and_then(|prefs| prefs.team_review_prefs.get(team_name))
.map(|prefs| prefs.rotation_mode)
.unwrap_or_default();
let in_adhoc_group = adhoc_group
.as_ref()
.map(|reviewers| reviewers.contains(&member.github.to_lowercase()))
.unwrap_or(true);
let capacity_is_full = if let Some(capacity) = prefs
.and_then(|prefs| prefs.repo_review_prefs.get(repo))
.and_then(|prefs| prefs.max_assigned_prs)
&& capacity <= workqueue.assigned_pr_count(member.github_id) as u32
{
true
} else {
false
};
if !in_adhoc_group {
ReviewerStatus::NotInAdhocGroup
} else if !matches!(team_rotation_mode, RotationMode::OnRotation) {
ReviewerStatus::OffRotationThroughTeam
} else if !matches!(rotation_mode, RotationMode::OnRotation) {
ReviewerStatus::OffRotationGlobally
} else if capacity_is_full {
ReviewerStatus::FullCapacity
} else {
ReviewerStatus::Available
}
}
/// How does impersonation work for a given command.
enum ImpersonationMode {
/// Impersonation is enabled, but the impersonated user will not be notified.
/// Should only be used for commands that are "read-only".
Silent,
/// Impersonation is enabled and the impersonated user will be notified.
Notify,
/// Impersonation is disabled.
/// Should be used for commands where impersonation doesn't make sense or if there are some
/// specific permissions required to run the command.
Disabled,
}
/// Returns the impersonation mode of the command.
fn get_cmd_impersonation_mode(cmd: &ChatCommand) -> ImpersonationMode {
match cmd {
ChatCommand::Acknowledge { .. }
| ChatCommand::Add { .. }
| ChatCommand::Move { .. }
| ChatCommand::Meta { .. }
| ChatCommand::DocsUpdate
| ChatCommand::PingGoals(_)
| ChatCommand::UserInfo { .. }
| ChatCommand::TeamStats { .. }
| ChatCommand::Lookup(_) => ImpersonationMode::Disabled,
ChatCommand::Whoami => ImpersonationMode::Silent,
ChatCommand::Work(cmd) => match cmd {
WorkqueueCmd::Show { .. } => ImpersonationMode::Silent,
WorkqueueCmd::SetPrLimit { .. }
| WorkqueueCmd::SetRotationMode { .. }
| WorkqueueCmd::SetTeamRotationMode { .. } => ImpersonationMode::Notify,
},
}
}
/// Commands for working with the workqueue, e.g. showing how many PRs are assigned
/// or modifying the PR review assignment limit.
async fn workqueue_commands(
ctx: &Context,
gh_id: u64,
cmd: &WorkqueueCmd,