-
Notifications
You must be signed in to change notification settings - Fork 101
/
Copy pathengine.dart
1867 lines (1809 loc) · 70.7 KB
/
engine.dart
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
// Copyright 2019 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'dart:async';
import 'dart:convert';
import 'dart:io';
import 'dart:typed_data';
import 'package:appengine/appengine.dart'
show authClientService, runAppEngine, withAppEngineServices;
import 'package:crypto/crypto.dart';
import 'package:dart_jsonwebtoken/dart_jsonwebtoken.dart';
import 'package:github/github.dart';
import 'package:googleapis/secretmanager/v1.dart';
import 'package:http/http.dart' as http show Client;
import 'package:nyxx/nyxx.dart';
import 'bytes.dart';
import 'discord.dart';
import 'json.dart';
import 'utils.dart';
const int port = 8213; // used only when not using appengine
const int maxLogLength = 1024;
sealed class GitHubSettings {
static const String organization = 'flutter';
static const String teamName = 'flutter-hackers';
static final RepositorySlug primaryRepository = RepositorySlug(
organization,
'flutter',
);
static const String teamPrefix = 'team-';
static const String triagedPrefix = 'triaged-';
static const String fyiPrefix = 'fyi-';
static const String designDoc = 'design doc';
static const String permanentlyLocked = 'permanently locked';
static const String thumbsUpLabel = ':+1:';
static const String staleIssueLabel = ':hourglass_flowing_sand:';
static const Set<String> priorities = <String>{'P0', 'P1', 'P2', 'P3'};
static const String staleP1Message =
'This issue is marked P1 but has had no recent status updates.\n'
'\n'
'The P1 label indicates high-priority issues that are at the top of the work list. '
'This is the highest priority level a bug can have '
'if it isn\'t affecting a top-tier customer or breaking the build. '
'Bugs marked P1 are generally actively being worked on '
'unless the assignee is dealing with a P0 bug (or another P1 bug). '
'Issues at this level should be resolved in a matter of months and should have monthly updates on GitHub.\n'
'\n'
'Please consider where this bug really falls in our current priorities, and label it or assign it accordingly. '
'This allows people to have a clearer picture of what work is actually planned. Thanks!';
static const String willNeedAdditionalTriage = 'will need additional triage';
static const Set<String> teams = <String>{
// these are the teams that the self-test issue is assigned to
'accessibility',
'android',
'codelabs',
'design',
'ecosystem',
'engine',
'framework',
'games',
'go_router',
'infra',
'ios',
'linux',
'macos',
'news',
'release',
'text-input',
'tool',
'web',
'windows',
};
static const int thumbsMinimum =
100; // an issue needs at least this many thumbs up to trigger retriage
static const double thumbsThreshold =
2.0; // and the count must have increased by this factor since last triage
static const Set<String> knownBots = <String>{
// we don't report events from bots to Discord
'auto-submit[bot]',
'DartDevtoolWorkflowBot',
'dependabot[bot]',
'engine-flutter-autoroll',
'flutter-dashboard[bot]',
'flutter-triage-bot[bot]', // that's us!
'fluttergithubbot',
'github-actions[bot]',
'google-cla[bot]',
'google-ospo-administrator[bot]',
'skia-flutter-autoroll',
};
static bool isRelevantLabel(String label, {bool ignorePriorities = false}) {
return label.startsWith(GitHubSettings.teamPrefix) ||
label.startsWith(GitHubSettings.triagedPrefix) ||
label.startsWith(GitHubSettings.fyiPrefix) ||
label == GitHubSettings.designDoc ||
label == GitHubSettings.permanentlyLocked ||
label == GitHubSettings.thumbsUpLabel ||
label == GitHubSettings.staleIssueLabel ||
(!ignorePriorities && GitHubSettings.priorities.contains(label));
}
}
sealed class Timings {
static const Duration backgroundUpdatePeriod = Duration(
seconds: 1,
); // how long to wait between issues when scanning in the background
static const Duration cleanupUpdateDelay = Duration(
minutes: 45,
); // how long to wait for an issue to be idle before cleaning it up
static const Duration cleanupUpdatePeriod = Duration(
seconds: 60,
); // time between attempting to clean up the pending cleanup issues
static const Duration longTermTidyingPeriod = Duration(
hours: 5,
); // time between attempting to run long-term tidying of all issues
static const Duration credentialsUpdatePeriod = Duration(
minutes: 45,
); // how often to update GitHub credentials
static const Duration timeUntilStale = Duration(
days: 18 * 7,
); // how long since the last team interaction before considering an issue stale
static const Duration timeUntilReallyStale = Duration(
days: 29 * 7,
); // how long since the last team interaction before unassigning an issue
static const Duration timeUntilUnlock = Duration(
days: 28,
); // how long to leave open issues locked
static const Duration selfTestPeriod = Duration(
days: 6 * 7,
); // how often to file an issue to test the triage process
static const Duration selfTestWindow = Duration(
days: 18,
); // how long to leave the self-test issue open before assigning it to critical triage
static const Duration refeedDelay = Duration(
hours: 24,
); // how long between times we mark an issue as needing retriage (max 7 a week per team)
}
final class Secrets {
Future<List<int>> get serverCertificate => _getSecret('server.cert.pem');
Future<DateTime> get serverCertificateModificationDate =>
_getSecretModificationDate('server.cert.pem');
Future<List<int>> get serverIntermediateCertificates =>
_getSecret('server.intermediates.pem');
Future<DateTime> get serverIntermediateCertificatesModificationDate =>
_getSecretModificationDate('server.intermediates.pem');
Future<List<int>> get serverKey => _getSecret('server.key.pem');
Future<DateTime> get serverKeyModificationDate =>
_getSecretModificationDate('server.key.pem');
Future<String> get discordToken async =>
utf8.decode(await _getSecret('discord.token'));
Future<int> get discordAppId async =>
int.parse(utf8.decode(await _getSecret('discord.appid')));
Future<List<int>> get githubWebhookSecret =>
_getSecret('github.webhook.secret');
Future<String> get githubAppKey async =>
utf8.decode(await _getSecret('github.app.key.pem'));
Future<String> get githubAppId async =>
utf8.decode(await _getSecret('github.app.id'));
Future<String> get githubInstallationId async =>
utf8.decode(await _getSecret('github.installation.id'));
final File store = File('store.db');
static const String _projectId =
'xxxxx?????xxxxx'; // TODO(ianh): we should update this appropriately
static File asFile(String name) => File('secrets/$name');
static String asKey(String name) =>
'projects/$_projectId/secrets/$name/versions/latest';
static Future<List<int>> _getSecret(String name) async {
final file = asFile(name);
if (await file.exists()) {
return file.readAsBytes();
}
// authClientService is https://pub.dev/documentation/gcloud/latest/http/authClientService.html
final secretManager = SecretManagerApi(authClientService);
final key = asKey(name);
final response = await secretManager.projects.secrets.versions.access(key);
return response.payload!.dataAsBytes;
}
static Future<DateTime> _getSecretModificationDate(String name) async {
final file = asFile(name);
if (await file.exists()) {
return file.lastModified();
}
// authClientService is https://pub.dev/documentation/gcloud/latest/http/authClientService.html
final secretManager = SecretManagerApi(authClientService);
final key = asKey(name);
final response = await secretManager.projects.secrets.versions.get(key);
return DateTime.parse(response.createTime!);
}
}
class IssueStats {
IssueStats({
this.lastContributorTouch,
this.lastAssigneeTouch,
Set<String>? labels,
this.openedAt,
this.lockedAt,
this.assignedAt,
this.assignedToTeamMemberReporter = false,
this.triagedAt,
this.thumbsAtTriageTime,
this.thumbs = 0,
}) : labels = labels ?? <String>{};
factory IssueStats.read(FileReader reader) {
return IssueStats(
lastContributorTouch: reader.readNullOr<DateTime>(reader.readDateTime),
lastAssigneeTouch: reader.readNullOr<DateTime>(reader.readDateTime),
labels: reader.readSet<String>(reader.readString),
openedAt: reader.readNullOr<DateTime>(reader.readDateTime),
lockedAt: reader.readNullOr<DateTime>(reader.readDateTime),
assignedAt: reader.readNullOr<DateTime>(reader.readDateTime),
assignedToTeamMemberReporter: reader.readBool(),
triagedAt: reader.readNullOr<DateTime>(reader.readDateTime),
thumbsAtTriageTime: reader.readNullOr<int>(reader.readInt),
thumbs: reader.readInt(),
);
}
static void write(FileWriter writer, IssueStats value) {
writer.writeNullOr<DateTime>(
value.lastContributorTouch,
writer.writeDateTime,
);
writer.writeNullOr<DateTime>(value.lastAssigneeTouch, writer.writeDateTime);
writer.writeSet<String>(writer.writeString, value.labels);
writer.writeNullOr<DateTime>(value.openedAt, writer.writeDateTime);
writer.writeNullOr<DateTime>(value.lockedAt, writer.writeDateTime);
writer.writeNullOr<DateTime>(value.assignedAt, writer.writeDateTime);
writer.writeBool(value.assignedToTeamMemberReporter);
writer.writeNullOr<DateTime>(value.triagedAt, writer.writeDateTime);
writer.writeNullOr<int>(value.thumbsAtTriageTime, writer.writeInt);
writer.writeInt(value.thumbs);
}
DateTime? lastContributorTouch;
DateTime? lastAssigneeTouch;
Set<String> labels;
DateTime? openedAt;
DateTime? lockedAt;
DateTime? assignedAt;
bool assignedToTeamMemberReporter = false;
DateTime? triagedAt;
int? thumbsAtTriageTime;
int thumbs;
@override
String toString() {
final buffer = StringBuffer();
buffer.write('{${(labels.toList()..sort()).join(', ')}} and $thumbs 👍');
if (openedAt != null) {
buffer.write('; openedAt: $openedAt');
}
if (lastContributorTouch != null) {
buffer.write('; lastContributorTouch: $lastContributorTouch');
} else {
buffer.write('; lastContributorTouch: never');
}
if (assignedAt != null) {
buffer.write('; assignedAt: $assignedAt');
if (assignedToTeamMemberReporter) {
buffer.write(' (to team-member reporter)');
}
if (lastAssigneeTouch != null) {
buffer.write('; lastAssigneeTouch: $lastAssigneeTouch');
} else {
buffer.write('; lastAssigneeTouch: never');
}
} else {
if (lastAssigneeTouch != null) {
buffer.write('; lastAssigneeTouch: $lastAssigneeTouch (?!)');
}
if (assignedToTeamMemberReporter) {
buffer.write('; assigned to team-member reporter (?!)');
}
}
if (lockedAt != null) {
buffer.write('; lockedAt: $lockedAt');
}
if (triagedAt != null) {
buffer.write('; triagedAt: $triagedAt');
if (thumbsAtTriageTime != null) {
buffer.write(' with $thumbsAtTriageTime 👍');
}
} else {
if (thumbsAtTriageTime != null) {
buffer.write(
'; not triaged with $thumbsAtTriageTime 👍 when triaged (?!)',
);
}
}
return buffer.toString();
}
}
typedef StoreFields =
({
Map<int, IssueStats> issues,
Map<int, DateTime> pendingCleanupIssues,
int? selfTestIssue,
DateTime? selfTestClosedDate,
int currentBackgroundIssue,
int highestKnownIssue,
Map<String, DateTime> lastRefeedByTime,
DateTime? lastCleanupStart,
DateTime? lastCleanupEnd,
DateTime? lastTidyStart,
DateTime? lastTidyEnd,
});
class Engine {
Engine._({
required this.webhookSecret,
required this.discord,
required this.github,
required this.secrets,
required Set<String> contributors,
required StoreFields? store,
}) : _contributors = contributors,
_issues = store?.issues ?? <int, IssueStats>{},
_pendingCleanupIssues = store?.pendingCleanupIssues ?? <int, DateTime>{},
_selfTestIssue = store?.selfTestIssue,
_selfTestClosedDate = store?.selfTestClosedDate,
_currentBackgroundIssue = store?.currentBackgroundIssue ?? 1,
_highestKnownIssue = store?.highestKnownIssue ?? 1,
_lastRefeedByTime = store?.lastRefeedByTime ?? <String, DateTime>{},
_lastCleanupStart = store?.lastCleanupStart,
_lastCleanupEnd = store?.lastCleanupEnd,
_lastTidyStart = store?.lastTidyStart,
_lastTidyEnd = store?.lastTidyEnd {
_startup = DateTime.timestamp();
scheduleMicrotask(_updateStoreInBackground);
_nextCleanup = (_lastCleanupEnd ?? _startup).add(
Timings.cleanupUpdatePeriod,
);
_cleanupTimer = Timer(_nextCleanup.difference(_startup), _performCleanups);
_nextTidy = (_lastTidyEnd ?? _startup).add(Timings.longTermTidyingPeriod);
_tidyTimer = Timer(_nextTidy.difference(_startup), _performLongTermTidying);
log('Startup');
}
static Future<Engine> initialize({
required List<int> webhookSecret,
required INyxx discord,
required GitHub github,
void Function()? onChange,
required Secrets secrets,
}) async {
return Engine._(
webhookSecret: webhookSecret,
discord: discord,
github: github,
secrets: secrets,
contributors: await _loadContributors(github),
store: await _read(secrets),
);
}
final List<int> webhookSecret;
final INyxx discord;
final GitHub github;
final Secrets secrets;
// data this is stored on local disk
final Set<String> _contributors;
final Map<int, IssueStats> _issues;
final Map<int, DateTime> _pendingCleanupIssues;
int? _selfTestIssue;
DateTime? _selfTestClosedDate;
int _currentBackgroundIssue;
int _highestKnownIssue;
final Map<String, DateTime>
_lastRefeedByTime; // last time we forced an otherwise normal issue to get retriaged by each team
final Set<String> _recentIds =
<String>{}; // used to detect duplicate messages and discard them
final List<String> _log = <String>[];
late final DateTime _startup;
DateTime? _lastCleanupStart;
DateTime? _lastCleanupEnd;
late DateTime _nextCleanup;
Timer? _cleanupTimer;
DateTime? _lastTidyStart;
DateTime? _lastTidyEnd;
late DateTime _nextTidy;
Timer? _tidyTimer;
void log(String message) {
stderr.writeln(message);
_log.add('${DateTime.timestamp().toIso8601String()} $message');
while (_log.length > maxLogLength) {
_log.removeAt(0);
}
}
int _actives = 0;
bool _shuttingDown = false;
Completer<void> _pendingIdle = Completer<void>();
Future<void> shutdown(Future<void> Function() shutdownCallback) async {
assert(!_shuttingDown, 'shutdown called reentrantly');
_shuttingDown = true;
while (_actives > 0) {
await _pendingIdle.future;
}
return shutdownCallback();
}
static Future<Set<String>> _loadContributors(GitHub github) async {
final teamId =
(await github.organizations.getTeamByName(
GitHubSettings.organization,
GitHubSettings.teamName,
)).id!;
return github.organizations
.listTeamMembers(teamId)
.map((TeamMember member) => member.login!)
.toSet();
}
static Future<StoreFields?> _read(Secrets secrets) async {
if (await secrets.store.exists()) {
try {
final reader = FileReader(
(await secrets.store.readAsBytes()).buffer.asByteData(),
);
return (
issues: reader.readMap<int, IssueStats>(
reader.readInt,
reader.readerForCustom<IssueStats>(IssueStats.read),
),
pendingCleanupIssues: reader.readMap<int, DateTime>(
reader.readInt,
reader.readDateTime,
),
selfTestIssue: reader.readNullOr<int>(reader.readInt),
selfTestClosedDate: reader.readNullOr<DateTime>(reader.readDateTime),
currentBackgroundIssue: reader.readInt(),
highestKnownIssue: reader.readInt(),
lastRefeedByTime: reader.readMap<String, DateTime>(
reader.readString,
reader.readDateTime,
),
lastCleanupStart: reader.readNullOr<DateTime>(reader.readDateTime),
lastCleanupEnd: reader.readNullOr<DateTime>(reader.readDateTime),
lastTidyStart: reader.readNullOr<DateTime>(reader.readDateTime),
lastTidyEnd: reader.readNullOr<DateTime>(reader.readDateTime),
);
} catch (e) {
print(
'Error loading issue store, consider deleting ${secrets.store.path} file.',
);
rethrow;
}
}
return null;
}
bool _writing = false;
bool _dirty = false;
Future<void> _write() async {
if (_writing) {
_dirty = true;
return;
}
try {
_writing = true;
final writer = FileWriter();
writer.writeMap<int, IssueStats>(
writer.writeInt,
writer.writerForCustom<IssueStats>(IssueStats.write),
_issues,
);
writer.writeMap<int, DateTime>(
writer.writeInt,
writer.writeDateTime,
_pendingCleanupIssues,
);
writer.writeNullOr<int>(_selfTestIssue, writer.writeInt);
writer.writeNullOr<DateTime>(_selfTestClosedDate, writer.writeDateTime);
writer.writeInt(_currentBackgroundIssue);
writer.writeInt(_highestKnownIssue);
writer.writeMap<String, DateTime>(
writer.writeString,
writer.writeDateTime,
_lastRefeedByTime,
);
writer.writeNullOr<DateTime>(_lastCleanupStart, writer.writeDateTime);
writer.writeNullOr<DateTime>(_lastCleanupEnd, writer.writeDateTime);
writer.writeNullOr<DateTime>(_lastTidyStart, writer.writeDateTime);
writer.writeNullOr<DateTime>(_lastTidyEnd, writer.writeDateTime);
await writer.write(secrets.store);
} finally {
_writing = false;
}
if (_dirty) {
_dirty = false;
return _write();
}
}
// the maxFraction argument represents the fraction of the total rate limit that is allowed to be
// used before waiting.
//
// the background update code sets it to 0.5 so that there is still a buffer for the other calls,
// otherwise the background update code could just use it all up and then stall everything else.
Future<void> _githubReady([double maxFraction = 0.95]) async {
if (github.rateLimitRemaining != null &&
github.rateLimitRemaining! <
(github.rateLimitLimit! * (1.0 - maxFraction)).round()) {
assert(github.rateLimitReset != null);
await _until(github.rateLimitReset!);
}
}
static Future<void> _until(DateTime target) {
final now = DateTime.timestamp();
if (!now.isBefore(target)) {
return Future<void>.value();
}
final delta = target.difference(now);
return Future<void>.delayed(delta);
}
Future<void> handleRequest(HttpRequest request) async {
_actives += 1;
try {
try {
if (await _handleDebugRequests(request)) {
return;
}
final bytes =
await request.expand((Uint8List sublist) => sublist).toList();
final expectedSignature =
'sha256=${Hmac(sha256, webhookSecret).convert(bytes).bytes.map(hex).join()}';
final actualSignatures =
request.headers['X-Hub-Signature-256'] ?? const <String>[];
final eventKind = request.headers['X-GitHub-Event'] ?? const <String>[];
final eventId =
request.headers['X-GitHub-Delivery'] ?? const <String>[];
if (actualSignatures.length != 1 ||
expectedSignature != actualSignatures.single ||
eventKind.length != 1 ||
eventId.length != 1) {
request.response.writeln('Invalid metadata.');
return;
}
if (_recentIds.contains(eventId.single)) {
request.response.writeln('I got that one already.');
return;
}
_recentIds.add(eventId.single);
while (_recentIds.length > 50) {
_recentIds.remove(_recentIds.first);
}
final dynamic payload = Json.parse(utf8.decode(bytes));
await _updateModelFromWebhook(eventKind.single, payload);
await _updateDiscordFromWebhook(eventKind.single, payload);
request.response.writeln('Acknowledged.');
} catch (e, s) {
log('Failed to handle ${request.uri}: $e (${e.runtimeType})\n$s');
} finally {
await request.response.close();
}
} finally {
_actives -= 1;
if (_shuttingDown && _actives == 0) {
_pendingIdle.complete();
_pendingIdle = Completer<void>();
}
}
}
Future<bool> _handleDebugRequests(HttpRequest request) async {
if (request.uri.path == '/debug') {
final now = DateTime.timestamp();
request.response.writeln('FLUTTER TRIAGE BOT');
request.response.writeln('==================');
request.response.writeln();
request.response.writeln('Current time: $now');
request.response.writeln(
'Uptime: ${now.difference(_startup)} (startup at $_startup).',
);
request.response.writeln(
'Cleaning: ${_cleaning ? "active" : "pending"} (${_pendingCleanupIssues.length} issue${s(_pendingCleanupIssues.length)}); last started $_lastCleanupStart, last ended $_lastCleanupEnd, next in ${_nextCleanup.difference(now)}.',
);
request.response.writeln(
'Tidying: ${_tidying ? "active" : "pending"}; last started $_lastTidyStart, last ended $_lastTidyEnd, next in ${_nextTidy.difference(now)}.',
);
request.response.writeln(
'Background scan: currently fetching issue #$_currentBackgroundIssue, highest known issue #$_highestKnownIssue.',
);
request.response.writeln(
'${_contributors.length} known contributor${s(_contributors.length)}.',
);
request.response.writeln(
'GitHub Rate limit status: ${github.rateLimitRemaining}/${github.rateLimitLimit} (reset at ${github.rateLimitReset})',
);
if (_selfTestIssue != null) {
request.response.writeln('Current self test issue: #$_selfTestIssue');
}
if (_selfTestClosedDate != null) {
request.response.writeln(
'Self test last closed on: $_selfTestClosedDate (${now.difference(_selfTestClosedDate!)} ago, next in ${_selfTestClosedDate!.add(Timings.selfTestPeriod).difference(now)})',
);
}
request.response.writeln();
request.response.writeln(
'Last refeeds (refeed delay: ${Timings.refeedDelay}):',
);
for (final team
in _lastRefeedByTime.keys.toList()..sort(
(String a, String b) =>
_lastRefeedByTime[a]!.compareTo(_lastRefeedByTime[b]!),
)) {
final delta = now.difference(_lastRefeedByTime[team]!);
final annotation =
delta > Timings.refeedDelay ? '' : '; blocking immediate refeeds';
request.response.writeln(
'${team.padRight(30, '.')}.${_lastRefeedByTime[team]} ($delta ago$annotation)',
);
}
request.response.writeln();
request.response.writeln(
'Tracking ${_issues.length} issue${s(_issues.length)}:',
);
for (final number in _issues.keys.toList()..sort()) {
var cleanup = '';
if (_pendingCleanupIssues.containsKey(number)) {
final delta =
Timings.cleanupUpdateDelay -
now.difference(_pendingCleanupIssues[number]!);
if (delta < Duration.zero) {
cleanup = ' [cleanup pending]';
} else if (delta.inMinutes <= 1) {
cleanup = ' [cleanup soon]';
} else {
cleanup =
' [cleanup in ${delta.inMinutes} minute${s(delta.inMinutes)}]';
}
}
request.response.writeln(
' #${number.toString().padLeft(6, "0")}: ${_issues[number]}$cleanup',
);
}
request.response.writeln();
request.response.writeln('LOG');
_log.forEach(request.response.writeln);
return true;
}
if (request.uri.path == '/force-update') {
final number = int.parse(
request.uri.query,
); // if input is not an integer, this'll throw
await _updateStoreInBackgroundForIssue(number);
request.response.writeln('${_issues[number]}');
return true;
}
if (request.uri.path == '/force-cleanup') {
log('User-triggered forced cleanup');
await _performCleanups();
_log.forEach(request.response.writeln);
return true;
}
if (request.uri.path == '/force-tidy') {
log('User-triggered forced tidy');
await _performLongTermTidying();
_log.forEach(request.response.writeln);
return true;
}
return false;
}
// Called when we get a webhook message.
Future<void> _updateModelFromWebhook(String event, dynamic payload) async {
final now = DateTime.timestamp();
switch (event) {
case 'issue_comment':
if (!(payload.issue.hasKey('pull_request') as bool) &&
payload.repository.full_name.toString() ==
GitHubSettings.primaryRepository.fullName) {
_updateIssueFromWebhook(
payload.sender.login.toString(),
payload.issue,
now,
);
}
case 'issues':
if (payload.repository.full_name.toString() !=
GitHubSettings.primaryRepository.fullName) {
return;
}
if (payload.action.toString() == 'closed') {
final number = payload.issue.number.toInt() as int;
_issues.remove(number);
_pendingCleanupIssues.remove(number);
if (number == _selfTestIssue) {
_selfTestIssue = null;
_selfTestClosedDate = now;
}
} else {
final issue = _updateIssueFromWebhook(
payload.sender.login.toString(),
payload.issue,
now,
);
if (issue != null) {
if (payload.action.toString() == 'assigned') {
// if we are adding a second assignee, _updateIssueFromWebhook won't update the assignedAt timestamp
_issues[payload.issue.number.toInt()]!.assignedAt = now;
} else if (payload.action.toString() == 'opened' ||
payload.action.toString() == 'reopened') {
_issues[payload.issue.number.toInt()]!.openedAt = now;
} else if (payload.action.toString() == 'labeled') {
final label = payload.label.name.toString();
final team = getTeamFor(GitHubSettings.triagedPrefix, label);
if (team != null) {
final teams = getTeamsFor(
GitHubSettings.teamPrefix,
issue.labels,
);
if (teams.length == 1) {
if (teams.single == team) {
issue.triagedAt = now;
}
}
}
}
}
}
case 'membership':
if (payload.team.slug.toString() ==
'${GitHubSettings.organization}/${GitHubSettings.teamName}') {
switch (payload.action.toString()) {
case 'added':
_contributors.add(payload.member.login.toString());
case 'removed':
_contributors.remove(payload.member.login.toString());
}
}
}
await _write();
}
// Called when we get a webhook message that we've established is an
// interesting update to an issue.
// Attempts to build up and/or update the data for an issue based on
// the data in a change event. This will be approximate until we can actually
// scan the issue properly in _updateStoreInBackground.
IssueStats? _updateIssueFromWebhook(String user, dynamic data, DateTime now) {
final number = data.number.toInt() as int;
if (number > _highestKnownIssue) {
_highestKnownIssue = number;
}
if (data.state.toString() == 'closed') {
_issues.remove(number);
_pendingCleanupIssues.remove(number);
if (number == _selfTestIssue) {
_selfTestIssue = null;
_selfTestClosedDate = now;
}
return null;
}
final issue = _issues.putIfAbsent(number, IssueStats.new);
final newLabels = <String>{};
for (final dynamic label in data.labels.asIterable() as Iterable) {
final name = label.name.toString();
if (GitHubSettings.isRelevantLabel(name)) {
newLabels.add(name);
}
}
issue.labels = newLabels;
final assignees = <String>{};
for (final dynamic assignee in data.assignees.asIterable() as Iterable) {
assignees.add(assignee.login.toString());
}
final reporter = data.user.login.toString();
if (assignees.isEmpty) {
issue.lastAssigneeTouch = null;
issue.assignedAt = null;
issue.assignedToTeamMemberReporter = false;
} else {
issue.assignedAt ??= now;
if (assignees.contains(user)) {
issue.lastAssigneeTouch = now;
}
issue.assignedToTeamMemberReporter =
assignees.contains(reporter) && _contributors.contains(reporter);
}
if (_contributors.contains(user)) {
issue.lastContributorTouch = now;
}
if (!(data.locked.toBoolean() as bool)) {
issue.lockedAt = null;
} else {
issue.lockedAt ??= now;
}
final teams = getTeamsFor(GitHubSettings.triagedPrefix, newLabels);
if (teams.isEmpty) {
issue.thumbsAtTriageTime = null;
issue.triagedAt = null;
}
_pendingCleanupIssues[number] = now;
return issue;
}
Future<void> _updateDiscordFromWebhook(String event, dynamic payload) async {
if (GitHubSettings.knownBots.contains(payload.sender.login.toString())) {
return;
}
switch (event) {
case 'star':
switch (payload.action.toString()) {
case 'created':
await sendDiscordMessage(
discord: discord,
body:
'**@${payload.sender.login}** starred ${payload.repository.full_name}',
channel: DiscordChannels.github2,
emoji: UnicodeEmoji('🌟'),
log: log,
);
}
case 'label':
switch (payload.action.toString()) {
case 'created':
String message;
if (payload.label.description.toString().isEmpty) {
message =
'**@${payload.sender.login}** created a new label in ${payload.repository.full_name}, `${payload.label.name}`, but did not give it a description!';
} else {
message =
'**@${payload.sender.login}** created a new label in ${payload.repository.full_name}, `${payload.label.name}`, with the description "${payload.label.description}".';
}
await sendDiscordMessage(
discord: discord,
body: message,
channel: DiscordChannels.hiddenChat,
embedTitle: '${payload.label.name}',
embedDescription: '${payload.label.description}',
embedColor: '${payload.label.color}',
log: log,
);
}
case 'pull_request':
switch (payload.action.toString()) {
case 'closed':
final merged = payload.pull_request.merged_at.toScalar() != null;
await sendDiscordMessage(
discord: discord,
body:
'**@${payload.sender.login}** ${merged ? "merged" : "closed"} *${payload.pull_request.title}* (${payload.pull_request.html_url})',
channel: DiscordChannels.github2,
log: log,
);
case 'opened':
await sendDiscordMessage(
discord: discord,
body:
'**@${payload.sender.login}** submitted a new pull request: **${payload.pull_request.title}** (${payload.repository.full_name} #${payload.pull_request.number.toInt()})\n${stripBoilerplate(payload.pull_request.body.toString())}',
suffix: '*${payload.pull_request.html_url}*',
channel: DiscordChannels.github2,
log: log,
);
}
case 'pull_request_review':
switch (payload.action.toString()) {
case 'submitted':
switch (payload.review.state.toString()) {
case 'approved':
await sendDiscordMessage(
discord: discord,
body:
payload.review.body.toString().isEmpty
? '**@${payload.sender.login}** gave **LGTM** for *${payload.pull_request.title}* (${payload.pull_request.html_url})'
: '**@${payload.sender.login}** gave **LGTM** for *${payload.pull_request.title}* (${payload.pull_request.html_url}): ${stripBoilerplate(payload.review.body.toString(), inline: true)}',
channel: DiscordChannels.github2,
log: log,
);
}
}
case 'pull_request_review_comment':
await sendDiscordMessage(
discord: discord,
body:
'**@${payload.sender.login}** wrote: ${stripBoilerplate(payload.comment.body.toString(), inline: true)}',
suffix: '*${payload.comment.html_url} ${payload.pull_request.title}*',
channel: DiscordChannels.github2,
log: log,
);
case 'issue_comment':
switch (payload.action.toString()) {
case 'created':
await sendDiscordMessage(
discord: discord,
body:
'**@${payload.sender.login}** wrote: ${stripBoilerplate(payload.comment.body.toString(), inline: true)}',
suffix: '*${payload.comment.html_url} ${payload.issue.title}*',
channel: DiscordChannels.github2,
log: log,
);
}
case 'issues':
switch (payload.action.toString()) {
case 'closed':
await sendDiscordMessage(
discord: discord,
body:
'**@${payload.sender.login}** closed *${payload.issue.title}* (${payload.issue.html_url})',
channel: DiscordChannels.github2,
log: log,
);
case 'reopened':
await sendDiscordMessage(
discord: discord,
body:
'**@${payload.sender.login}** reopened *${payload.issue.title}* (${payload.issue.html_url})',
channel: DiscordChannels.github2,
log: log,
);
case 'opened':
await sendDiscordMessage(
discord: discord,
body:
'**@${payload.sender.login}** filed a new issue: **${payload.issue.title}** (${payload.repository.full_name} #${payload.issue.number.toInt()})\n${stripBoilerplate(payload.issue.body.toString())}',
suffix: '*${payload.issue.html_url}*',
channel: DiscordChannels.github2,
log: log,
);
var isDesignDoc = false;
for (final dynamic label
in payload.issue.labels.asIterable() as Iterable) {
final name = label.name.toString();
if (name == GitHubSettings.designDoc) {
isDesignDoc = true;
break;
}
}
if (isDesignDoc) {
await sendDiscordMessage(
discord: discord,
body:
'**@${payload.sender.login}** wrote a new design doc: **${payload.issue.title}**\n${stripBoilerplate(payload.issue.body.toString())}',
suffix: '*${payload.issue.html_url}*',
channel: DiscordChannels.hiddenChat,
log: log,
);
}
case 'locked':
case 'unlocked':
await sendDiscordMessage(
discord: discord,
body:
'**@${payload.sender.login}** ${payload.action} ${payload.issue.html_url} - ${payload.issue.title}',
channel: DiscordChannels.github2,
log: log,
);
}
case 'membership':
await sendDiscordMessage(
discord: discord,
body:
'**@${payload.sender.login}** ${payload.action} user **@${payload.member.login}** (${payload.team.name})',
channel: DiscordChannels.github2,
log: log,
);
case 'gollum':
for (final dynamic page in payload.pages.asIterable() as Iterable) {
// sadly the commit message doesn't get put into the event payload
await sendDiscordMessage(
discord: discord,
body:
'**@${payload.sender.login}** ${page.action} the **${page.title}** wiki page',
suffix: '*${page.html_url}*',
channel: DiscordChannels.github2,
log: log,
);
}
}
}
// This is called every few seconds to update one issue in our store.
// We do this because (a) initially, we don't have any data so we need
// to fill our database somehow, and (b) thereafter, we might go out of
// sync if we miss an event, e.g. due to network issues.
Future<void> _updateStoreInBackground() async {
await _updateStoreInBackgroundForIssue(_currentBackgroundIssue);
_currentBackgroundIssue -= 1;
if (_currentBackgroundIssue <= 0) {
_currentBackgroundIssue = _highestKnownIssue;