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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
//! The batched calls of [`TaskSource`] — many searches, many comments, many updates — answered
//! in as few requests as GitHub's GraphQL API allows: aliased fields of one document where the
//! single-item call sends one document each.
//!
//! Every item stays its own: one alias GitHub refuses fails that item's answer alone, and the
//! others are answered beside it, because GitHub runs each aliased field on its own and answers
//! a refusal at the refused field's path. What GitHub refuses as a whole — a batched node read
//! naming an id that resolves to nothing — is read again one item at a time, as
//! [`GitHubProjectsSource::items_by_ids`] already reads it.
//!
//! [`TaskSource`]: onetaskgraph_plugin_api::TaskSource
use std::collections::BTreeMap;
use onetaskgraph_plugin_api::{
BatchAnswer, BatchComment, BatchUpdate, Comment, Cursor, ItemKind, NativeId, Page, PageRequest,
ProjectFilter, SourceError, Task, TaskQuery, TaskSource, TaskUpdateOutcome, decided_on,
};
use serde::{Deserialize, Serialize};
use serde_json::{Value, json};
use super::{
ANSWER_ERRORS, BOARD_ITEMS_PAGE_SIZE, BoardKind, COMMENT_BATCH, ContentKind,
GitHubProjectsSource, MAX_PAGE_SIZE, MUTATION_BATCH, NESTED_PAGE_SIZE, ORIGIN_FIELD, Resolved,
SEARCH_BATCH, SEARCH_BATCH_FIRST_PAGE, SEARCH_BATCH_ORIGINS, SEARCH_CURSOR_VERSION,
SEARCH_PAGE_SIZE, SearchConnection, SearchPosition, TASK_FIELD_BATCH, as_stored, comment_from,
graphql, optional_nodes, quoted, refuse_unsearchable, required_bool, required_str,
search_qualifiers, task_matches, validate_cursor_progress, validate_page,
};
/// The board field writes and issue updates a batch of targeted updates holds back while it
/// runs, each against the task it was made for, so they go out together once every update has
/// been composed: every field write first, then every issue update of a task whose field writes
/// all landed. Held only for the length of one [`GitHubProjectsSource::updates_batched`].
#[derive(Default)]
pub(super) struct TaskWrites {
/// The task whose update is being composed.
current: Option<NativeId>,
/// Each task's board field writes: the board, the board item, each `(field, value)`
/// written and each field cleared.
fields: Vec<(NativeId, HeldFields)>,
/// Each task's issue update, its `UpdateIssueInput` members other than `id`.
issues: Vec<(NativeId, Value)>,
}
/// One task's board field writes on one board, held by [`TaskWrites`].
pub(super) struct HeldFields {
board: String,
item: String,
writes: Vec<(String, Value)>,
clears: Vec<String>,
}
/// Where a batched origin lookup stands between two pages of its answer: each of its two
/// connections, and the candidates its earlier pages already answered.
///
/// Its own shape, which [`SearchPosition`] cannot be read as, so a cursor of one never resumes
/// the other.
#[derive(Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
struct OriginPosition {
version: u32,
origin_items: SearchConnection,
origin_search: SearchConnection,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
answered: Vec<NativeId>,
}
/// One search of a batch, as one slot of [`graphql::SEARCH_BATCH`] asks it.
struct Slotted {
/// The search, scoped to this board.
search: String,
/// Where its page resumes; `None` for its first page.
after: Option<String>,
/// The rows its page asks for.
first: u32,
}
/// One task query of a batch that [`graphql::SEARCH_BATCH`] answers.
enum Batched {
/// A narrowed issue search.
Search(Slotted),
/// An origin lookup: the board's field filter, and the issue search for the origin's
/// mirror in the body — each `None` once walked to its end.
Origin {
filter: String,
items: Option<Slotted>,
search: Option<Slotted>,
answered: Vec<NativeId>,
},
}
impl Batched {
fn search_slots(&self) -> usize {
match self {
Self::Search(_) => 1,
Self::Origin { search, .. } => usize::from(search.is_some()),
}
}
fn origin_slots(&self) -> usize {
match self {
Self::Search(_) => 0,
Self::Origin { items, .. } => usize::from(items.is_some()),
}
}
/// This ask, each of its parts given the next free slot of its kind.
fn placed(self, searches: &mut usize, origins: &mut usize) -> Slots {
let next = |free: &mut usize| {
let slot = *free;
*free += 1;
slot
};
match self {
Self::Search(slotted) => Slots::Search(slotted, next(searches)),
Self::Origin {
filter,
items,
search,
answered,
} => Slots::Origin {
filter,
items: items.map(|items| (items, next(origins))),
search: search.map(|search| (search, next(searches))),
answered,
},
}
}
}
/// A [`Batched`] ask placed in one request, each part beside the slot it was given.
enum Slots {
/// A narrowed issue search, in this `s<slot>`.
Search(Slotted, usize),
/// An origin lookup: its board filter in an `o<slot>`, its body search in an `s<slot>`.
Origin {
filter: String,
items: Option<(Slotted, usize)>,
search: Option<(Slotted, usize)>,
answered: Vec<NativeId>,
},
}
/// One batched ask placed in a request: where its answer goes, its query, and its slots.
struct Placed<'a> {
at: usize,
query: &'a TaskQuery,
slots: Slots,
}
/// The messages of every GraphQL error a response carried beside its data whose path begins at
/// `alias`, or every error naming no alias at all — what refused the field `alias`.
pub(super) fn errors_at(data: &Value, alias: &str) -> Vec<String> {
data.get(ANSWER_ERRORS)
.and_then(Value::as_array)
.into_iter()
.flatten()
.filter(|error| {
error
.get("path")
.and_then(Value::as_array)
.and_then(|path| path.first())
.and_then(Value::as_str)
.is_none_or(|first| first == alias)
})
.map(|error| {
error
.get("message")
.and_then(Value::as_str)
.unwrap_or("GitHub returned a GraphQL error")
.to_owned()
})
.collect()
}
/// The refusal of the aliased field `alias` of a request `doing` something, in GitHub's words
/// when it gave any.
fn refused_alias(data: &Value, alias: &str, doing: &str) -> SourceError {
let said = errors_at(data, alias);
SourceError::Refused {
message: if said.is_empty() {
format!("GitHub answered nothing for {alias} while {doing}")
} else {
format!("GitHub refused {alias} while {doing}: {}", said.join("; "))
},
}
}
/// `data`'s answer for `alias`: `None` when it is absent or null. One answered beside an error
/// naming that alias is partial — and, for a write, may still have landed — so it is malformed,
/// never taken as the alias's whole answer.
pub(super) fn alias_answer<'a>(
data: &'a Value,
alias: &str,
doing: &str,
) -> Result<Option<&'a Value>, SourceError> {
let Some(value) = data.get(alias).filter(|value| !value.is_null()) else {
return Ok(None);
};
// llmlint: ignore[boundary_inputs_validated] Only an error whose path starts at this alias is about this alias: GraphQL gives every error raised while executing a field that field's path, and a pathless one is a request error answered with no data, so it never stands beside a populated alias. Counting pathless errors here would also turn every write that landed beside another alias's failure into an error, inviting a duplicate retry.
let own: Vec<&str> = data
.get(ANSWER_ERRORS)
.and_then(Value::as_array)
.into_iter()
.flatten()
.filter(|error| {
error
.get("path")
.and_then(Value::as_array)
.and_then(|path| path.first())
.and_then(Value::as_str)
== Some(alias)
})
.map(|error| {
error
.get("message")
.and_then(Value::as_str)
.unwrap_or("GitHub returned a GraphQL error")
})
.collect();
if own.is_empty() {
return Ok(Some(value));
}
Err(SourceError::Malformed {
message: format!(
"GitHub answered {alias} while {doing} beside an error naming it ({}); what it \
asked may have been done, so read it before sending it again",
own.join("; ")
),
})
}
impl GitHubProjectsSource {
/// Whether this process has written anything of this board, which a narrowed read
/// completes its answer with — see `with_own_writes` — and a batched one cannot.
fn wrote_any(&self) -> Result<bool, SourceError> {
Ok(!self.created()?.is_empty() || !self.updated()?.is_empty())
}
/// How [`graphql::SEARCH_BATCH`] would answer `query` at `page`, or `None` for a query its
/// own read answers — one validated or refused there, narrowed by a project or by comment
/// activity, carrying no narrowing, or resumed from a cursor that read handed out.
fn batched(query: &TaskQuery, page: &PageRequest, scope: &str) -> Option<Batched> {
if validate_page(page).is_err()
|| refuse_unsearchable(query).is_err()
|| query.commented_since.is_some()
|| matches!(query.project, ProjectFilter::Is(_))
{
return None;
}
let limit = page.limit.min(MAX_PAGE_SIZE);
let first = |after: &Option<String>| match after {
None => SEARCH_BATCH_FIRST_PAGE.min(limit),
Some(_) => SEARCH_PAGE_SIZE.min(limit),
};
let resumed = |connection: &SearchConnection| match connection {
SearchConnection::Initial {} => Some(None),
SearchConnection::Continuing { after } => Some(Some(after.0.clone())),
SearchConnection::Exhausted {} => None,
};
if let Some(origin) = &query.origin {
let (items, search, answered) = match &page.cursor {
None => (Some(None), Some(None), Vec::new()),
Some(cursor) => {
let position = serde_json::from_str::<OriginPosition>(&cursor.0)
.ok()
.filter(|position| position.version == SEARCH_CURSOR_VERSION)?;
(
resumed(&position.origin_items),
resumed(&position.origin_search),
position.answered,
)
}
};
let search_for = format!("{scope} in:body {}", quoted(&as_stored(origin)));
return Some(Batched::Origin {
filter: format!("{ORIGIN_FIELD}:{}", quoted(origin)),
items: items.map(|after| Slotted {
search: String::new(),
first: first(&after),
after,
}),
search: search.map(|after| Slotted {
search: search_for,
first: first(&after),
after,
}),
answered,
});
}
let also = search_qualifiers(query)?;
let after = match &page.cursor {
None => None,
Some(cursor) => {
let position = serde_json::from_str::<SearchPosition>(&cursor.0).ok()?;
match position.connection {
SearchConnection::Continuing { after }
if position.version == SEARCH_CURSOR_VERSION
&& position.offset == 0
&& position.seen.is_empty()
&& position.own.is_empty()
&& !after.0.is_empty() =>
{
Some(after.0)
}
_ => return None,
}
}
};
Some(Batched::Search(Slotted {
search: format!("{scope} {also}"),
first: first(&after),
after,
}))
}
/// [`TaskSource::query_tasks_batch`](onetaskgraph_plugin_api::TaskSource::query_tasks_batch):
/// every narrowed search and origin lookup a page at a time in one
/// [`graphql::SEARCH_BATCH`] request a round, and every other query by its own read.
pub(super) async fn search_batched(
&self,
asks: &[(TaskQuery, PageRequest)],
) -> Vec<Result<Page<Task>, SourceError>> {
let mut answers: Vec<Option<Result<Page<Task>, SourceError>>> =
asks.iter().map(|_| None).collect();
let scope = self.board_search(None);
// What this process wrote completes a narrowed read's answer, which only that read's
// own walk does; a batch is asked of a board this process has not written.
let batchable = match self.wrote_any() {
Ok(wrote) => !wrote,
Err(error) => return asks.iter().map(|_| Err(error.clone())).collect(),
};
let mut batched: Vec<(usize, Batched)> = if batchable {
asks.iter()
.enumerate()
.filter_map(|(at, (query, page))| {
Self::batched(query, page, &scope).map(|batched| (at, batched))
})
.collect()
} else {
Vec::new()
};
// One search alone is its own read, which asks a page of its own size at one point; an
// origin resumed from a batch's cursor is answered only by another batch.
let resumed_origin = batched.iter().any(|(at, batched)| {
matches!(batched, Batched::Origin { .. }) && asks[*at].1.cursor.is_some()
});
if batched.len() < 2 && !resumed_origin {
batched.clear();
}
while !batched.is_empty() {
let mut placed: Vec<Placed<'_>> = Vec::new();
let (mut searches, mut origins) = (0, 0);
let mut rest = Vec::new();
for (at, ask) in batched {
if searches + ask.search_slots() <= SEARCH_BATCH
&& origins + ask.origin_slots() <= SEARCH_BATCH_ORIGINS
{
placed.push(Placed {
at,
query: &asks[at].0,
slots: ask.placed(&mut searches, &mut origins),
});
} else {
rest.push((at, ask));
}
}
batched = rest;
for (at, answer) in self.search_round(placed, &scope).await {
answers[at] = Some(answer);
}
}
let mut out = Vec::with_capacity(asks.len());
for ((query, page), answer) in asks.iter().zip(answers) {
out.push(match answer {
Some(answer) => answer,
None => TaskSource::query_tasks(self, query, page).await,
});
}
out
}
/// One [`graphql::SEARCH_BATCH`] request answering every ask `placed` holds, each with its
/// page or the refusal of its own slots.
async fn search_round(
&self,
placed: Vec<Placed<'_>>,
scope: &str,
) -> Vec<(usize, Result<Page<Task>, SourceError>)> {
let mut variables = serde_json::Map::new();
for (name, value) in [
("owner", json!(self.owner)),
("number", json!(self.project_number)),
("type", json!("ISSUE")),
("nestedFirst", json!(NESTED_PAGE_SIZE)),
("boardItems", json!(BOARD_ITEMS_PAGE_SIZE)),
("duplicates", json!(true)),
] {
variables.insert(name.to_owned(), value);
}
// A slot no ask holds is left out by its `@include`, bound to a well-formed search of
// one row, which GitHub requires of a variable it never runs.
for slot in 0..SEARCH_BATCH {
variables.insert(format!("search{slot}"), json!(scope));
variables.insert(format!("after{slot}"), Value::Null);
variables.insert(format!("first{slot}"), json!(1));
variables.insert(format!("ask{slot}"), json!(false));
}
for slot in 0..SEARCH_BATCH_ORIGINS {
variables.insert(format!("filter{slot}"), json!(""));
variables.insert(format!("itemsAfter{slot}"), Value::Null);
variables.insert(format!("itemsFirst{slot}"), json!(1));
variables.insert(format!("origin{slot}"), json!(false));
}
// Every resumed page of the round shares one page of rows: see
// `search_batch_resumed_page`.
let resumed = placed
.iter()
.map(|ask| match &ask.slots {
Slots::Search(slotted, _) => usize::from(slotted.after.is_some()),
Slots::Origin { items, search, .. } => [items, search]
.into_iter()
.flatten()
.filter(|(slotted, _)| slotted.after.is_some())
.count(),
})
.sum::<usize>();
let shared = super::search_batch_resumed_page(resumed);
let first = |slotted: &Slotted| {
if slotted.after.is_some() {
slotted.first.min(shared)
} else {
slotted.first
}
};
for ask in &placed {
let (search, origin) = match &ask.slots {
Slots::Search(slotted, slot) => (Some((slotted, *slot)), None),
Slots::Origin {
filter,
items,
search,
..
} => (
search.as_ref().map(|(search, slot)| (search, *slot)),
items.as_ref().map(|(items, slot)| (items, *slot, filter)),
),
};
if let Some((search, slot)) = search {
variables.insert(format!("search{slot}"), json!(search.search));
variables.insert(format!("after{slot}"), json!(search.after));
variables.insert(format!("first{slot}"), json!(first(search)));
variables.insert(format!("ask{slot}"), json!(true));
}
if let Some((items, slot, filter)) = origin {
variables.insert(format!("filter{slot}"), json!(filter));
variables.insert(format!("itemsAfter{slot}"), json!(items.after));
variables.insert(format!("itemsFirst{slot}"), json!(first(items)));
variables.insert(format!("origin{slot}"), json!(true));
}
}
let data = match self
.graphql(graphql::SEARCH_BATCH, Value::Object(variables))
.await
{
Ok(data) => data,
Err(error) => {
return placed
.into_iter()
.map(|ask| (ask.at, Err(error.clone())))
.collect();
}
};
let mut answered = Vec::with_capacity(placed.len());
for ask in placed {
let at = ask.at;
answered.push((at, self.answer_slots(&data, ask).await));
}
answered
}
/// The page one ask's slots of a [`graphql::SEARCH_BATCH`] answer hold, or the refusal of
/// one of them.
async fn answer_slots(&self, data: &Value, ask: Placed<'_>) -> Result<Page<Task>, SourceError> {
let doing = "searching this board's issues several ways at once";
let connection = |alias: &str, pointer: &str| -> Result<Value, SourceError> {
match alias_answer(data, alias, doing)? {
Some(value) => value
.pointer(pointer)
.filter(|value| !value.is_null())
.cloned()
.ok_or_else(|| SourceError::Refused {
message: format!(
"GitHub project {}/{} was not found or is not visible to the token",
self.owner, self.project_number
),
}),
None => Err(refused_alias(data, alias, doing)),
}
};
let next_of =
|connection: &Value, after: Option<&str>| -> Result<Option<String>, SourceError> {
let info = connection
.get("pageInfo")
.ok_or_else(|| SourceError::Malformed {
message: "GitHub search connection has no pageInfo".into(),
})?;
let next = required_bool(info, "hasNextPage")?
.then(|| required_str(info, "endCursor"))
.transpose()?
.map(str::to_owned);
if let Some(next) = &next {
validate_cursor_progress(after, next)?;
}
Ok(next)
};
let mut found: Vec<Resolved> = Vec::new();
let keep = |resolved: Resolved, found: &mut Vec<Resolved>| {
if !found.iter().any(|held| held.id == resolved.id) {
found.push(resolved);
}
};
let page = match ask.slots {
Slots::Search(slotted, slot) => {
let alias = format!("s{slot}");
let searched = connection(&alias, "")?;
for node in optional_nodes(Some(&searched), "search")?
.into_iter()
.flatten()
{
if let Some(resolved) = self.resolve_issue(node).await? {
keep(resolved, &mut found);
}
}
let next = next_of(&searched, slotted.after.as_deref())?;
let tasks = self.matching(&found, ask.query)?;
Page {
items: tasks,
next: next.map(|after| {
let position = SearchPosition {
connection: SearchConnection::Continuing {
after: Cursor(after),
},
..SearchPosition::default()
};
Cursor(
serde_json::to_string(&position)
.expect("search position is serializable"),
)
}),
}
}
Slots::Origin {
items,
search,
mut answered,
..
} => {
let mut items_next = SearchConnection::Exhausted {};
let mut search_next = SearchConnection::Exhausted {};
if let Some((items, slot)) = &items {
let read = connection(&format!("o{slot}"), "/projectV2/items")?;
for item in optional_nodes(Some(&read), "project items")?
.into_iter()
.flatten()
{
// The board's own items list its drafts too, and a draft is no issue:
// no narrowed read answers with one, whatever its origin field holds.
if let Some(resolved) = self.resolve(item)?
&& resolved.content_kind == ContentKind::Issue
{
keep(resolved, &mut found);
}
}
if let Some(next) = next_of(&read, items.after.as_deref())? {
items_next = SearchConnection::Continuing {
after: Cursor(next),
};
}
}
if let Some((search, slot)) = &search {
let read = connection(&format!("s{slot}"), "")?;
for node in optional_nodes(Some(&read), "search")?.into_iter().flatten() {
if let Some(resolved) = self.resolve_issue(node).await? {
keep(resolved, &mut found);
}
}
if let Some(next) = next_of(&read, search.after.as_deref())? {
search_next = SearchConnection::Continuing {
after: Cursor(next),
};
}
}
// A candidate an earlier page answered is not answered again.
found.retain(|item| !answered.contains(&item.id));
answered.extend(found.iter().map(|item| item.id.clone()));
let tasks = self.matching(&found, ask.query)?;
let more = !items_next.exhausted() || !search_next.exhausted();
Page {
items: tasks,
next: more.then(|| {
let position = OriginPosition {
version: SEARCH_CURSOR_VERSION,
origin_items: items_next,
origin_search: search_next,
answered,
};
Cursor(
serde_json::to_string(&position)
.expect("origin position is serializable"),
)
}),
}
}
};
Ok(page)
}
/// Every task among `found` that `query` keeps, in order — confirmed exactly as a read of
/// one confirms its candidates.
fn matching(&self, found: &[Resolved], query: &TaskQuery) -> Result<Vec<Task>, SourceError> {
let mut tasks = Vec::new();
for item in found
.iter()
.filter(|item| item.kind == BoardKind::Work(ItemKind::Task))
{
let task = item.task()?;
if task_matches(&task, query, &query.project) {
tasks.push(task);
}
}
Ok(tasks)
}
/// Read the first page of each candidate's comments that a comment-activity read is about
/// to confirm, together — [`DETAIL_BATCH`](super::DETAIL_BATCH) to a
/// [`graphql::ISSUE_DETAILS`] request — and hold each for the confirmation and for the one
/// comment listing of that task that follows in this command.
///
/// So confirming a page of candidates and then listing their comments costs one request
/// per batch rather than two per candidate. A candidate whose read fails is left to its own
/// read, as it always was.
pub(super) async fn hold_comment_pages(
&self,
candidates: &[NativeId],
) -> Result<(), SourceError> {
let unheld: Vec<NativeId> = {
let held = self.held_comments()?;
candidates
.iter()
.filter(|id| !held.contains_key(id))
.cloned()
.collect()
};
if unheld.len() < 2 {
return Ok(());
}
let page = PageRequest {
cursor: None,
limit: MAX_PAGE_SIZE,
};
let read = self.issue_details(&unheld, Some(&page)).await;
let mut held = self.held_comments()?;
for (id, read) in unheld.into_iter().zip(read) {
if let Ok(Some(onetaskgraph_plugin_api::TaskDetailRead {
comments: Some(Ok(Some(first))),
..
})) = read
{
held.insert(id, first);
}
}
Ok(())
}
/// The tasks among `items` whose comments a read of `query`'s comment activity confirms
/// it by: each task issue it otherwise keeps that changed at or after the instant, or that
/// this process commented on — none, for a query not narrowed by comment activity.
pub(super) fn comment_candidates<'a>(
&self,
items: impl Iterator<Item = &'a Resolved>,
query: &TaskQuery,
project: &ProjectFilter,
) -> Result<Vec<NativeId>, SourceError> {
let Some(since) = query.commented_since else {
return Ok(Vec::new());
};
let commented = self.commented()?.clone();
let mut candidates = Vec::new();
for item in items {
if item.kind != BoardKind::Work(ItemKind::Task)
|| item.content_kind != ContentKind::Issue
|| (item.updated_at.is_some_and(|updated| updated < since)
&& !commented.contains(&item.id))
|| candidates.contains(&item.id)
{
continue;
}
if task_matches(&item.task()?, query, project) {
candidates.push(item.id.clone());
}
}
Ok(candidates)
}
pub(super) fn held_comments(
&self,
) -> Result<std::sync::MutexGuard<'_, BTreeMap<NativeId, Page<Comment>>>, SourceError> {
self.held_comments
.lock()
.map_err(|_| SourceError::Unavailable {
message: "comment pages held for this command were left inconsistent; run the \
command again"
.into(),
})
}
/// [`TaskSource::add_comments`](onetaskgraph_plugin_api::TaskSource::add_comments): one
/// batched read of every task commented on — deciding each comment's hold on it — and every
/// comment that read lets through in one [`graphql::ADD_COMMENTS`] request per
/// [`COMMENT_BATCH`].
pub(super) async fn comments_batched(
&self,
comments: &[BatchComment],
) -> Vec<Result<BatchAnswer<Comment>, SourceError>> {
if comments.len() < 2 || self.expected.journaling() {
let mut answers = Vec::with_capacity(comments.len());
for each in comments {
answers.push(self.comment_alone(each).await);
}
return answers;
}
let mut answers: Vec<Option<Result<BatchAnswer<Comment>, SourceError>>> =
comments.iter().map(|_| None).collect();
// An author is refused before anything is read, as one comment's is.
for (at, each) in comments.iter().enumerate() {
if each.comment.author.is_some() {
answers[at] = Some(
TaskSource::add_comment(self, &each.task, &each.comment)
.await
.map(|written| written.map_or(BatchAnswer::Missing, BatchAnswer::Written)),
);
}
}
let wanted: Vec<NativeId> = comments
.iter()
.zip(&answers)
.filter(|(_, answer)| answer.is_none())
.map(|(each, _)| each.task.clone())
.fold(Vec::new(), |mut ids, id| {
if !ids.contains(&id) {
ids.push(id);
}
ids
});
let read = match self.items_by_ids(&wanted).await {
Ok(read) => read,
Err(error) => {
return answers
.into_iter()
.map(|answer| answer.unwrap_or_else(|| Err(error.clone())))
.collect();
}
};
let item_of = |id: &NativeId| {
wanted
.iter()
.position(|wanted| wanted == id)
.and_then(|at| read[at].clone())
};
let mut sending: Vec<(usize, NativeId, String)> = Vec::new();
// A held comment on a task an earlier comment of this batch is sent to is decided only
// once that one is answered: a comment moves its task's version.
let mut later: Vec<usize> = Vec::new();
for (at, each) in comments.iter().enumerate() {
if answers[at].is_some() {
continue;
}
if each.if_version.is_some()
&& sending
.iter()
.any(|(earlier, _, _)| comments[*earlier].task == each.task)
{
later.push(at);
continue;
}
let item =
item_of(&each.task).filter(|item| item.kind == BoardKind::Work(ItemKind::Task));
let decided = match &item {
Some(item) if item.content_kind == ContentKind::DraftIssue => {
Some(Err(self.draft_has_no_comments(&each.task)))
}
Some(item) => match item.task() {
Ok(task) => {
decided_on(self, Some(&task), each.if_version.as_deref(), &[]).map(Ok)
}
Err(error) => Some(Err(error)),
},
None => Some(Ok(BatchAnswer::Missing)),
};
match (decided, item) {
(Some(answer), _) => answers[at] = Some(answer),
(None, Some(item)) => {
sending.push((at, item.id, each.comment.body.as_str().to_owned()));
}
(None, None) => answers[at] = Some(Ok(BatchAnswer::Missing)),
}
}
for chunk in sending.chunks(COMMENT_BATCH) {
for (at, answer) in self.comment_round(chunk).await {
answers[at] = Some(answer);
}
}
for at in later {
let each = &comments[at];
let moved = (0..at).any(|earlier| {
comments[earlier].task == each.task
&& matches!(answers[earlier], Some(Ok(BatchAnswer::Written(_))))
});
answers[at] = Some(if moved {
// The earlier comment moved the task past the version this one is held to, to
// one no write's answer settles.
Ok(BatchAnswer::VersionMoved { found: None })
} else {
self.comment_alone(each).await
});
}
answers
.into_iter()
.map(|answer| answer.unwrap_or(Ok(BatchAnswer::Missing)))
.collect()
}
/// One comment of a batch on its own, as the default of
/// [`TaskSource::add_comments`](onetaskgraph_plugin_api::TaskSource::add_comments) adds it:
/// one read where its hold needs one, then the comment.
async fn comment_alone(
&self,
each: &BatchComment,
) -> Result<BatchAnswer<Comment>, SourceError> {
if each.if_version.is_some() {
let task = TaskSource::get_task(self, &each.task).await?;
if let Some(answer) = decided_on(self, task.as_ref(), each.if_version.as_deref(), &[]) {
return Ok(answer);
}
}
Ok(TaskSource::add_comment(self, &each.task, &each.comment)
.await?
.map_or(BatchAnswer::Missing, BatchAnswer::Written))
}
/// One [`graphql::ADD_COMMENTS`] request adding every comment of `chunk` — each `(answer
/// index, issue, body)` — answered one per comment.
async fn comment_round(
&self,
chunk: &[(usize, NativeId, String)],
) -> Vec<(usize, Result<BatchAnswer<Comment>, SourceError>)> {
let input = |(_, issue, body): &(usize, NativeId, String)| json!({"subjectId": issue.0, "body": body});
let mut variables = serde_json::Map::new();
for slot in 0..COMMENT_BATCH {
// A slot no comment holds repeats the first one's input, well formed as GitHub
// requires of a variable it never runs.
variables.insert(
format!("comment{slot}"),
input(chunk.get(slot).unwrap_or(&chunk[0])),
);
variables.insert(format!("send{slot}"), json!(slot < chunk.len()));
}
if let Ok(mut held) = self.held_comments() {
for (_, issue, _) in chunk {
held.remove(issue);
}
}
let data = match self
.graphql(graphql::ADD_COMMENTS, Value::Object(variables))
.await
{
Ok(data) => data,
Err(error) => {
return chunk
.iter()
.map(|(at, _, _)| (*at, Err(error.clone())))
.collect();
}
};
let mut answered = Vec::with_capacity(chunk.len());
for (slot, (at, issue, _)) in chunk.iter().enumerate() {
let alias = format!("comment{slot}");
let doing = "adding several comments together";
let answer = match alias_answer(&data, &alias, doing) {
Err(error) => Err(error),
Ok(None) => Err(refused_alias(&data, &alias, doing)),
Ok(Some(added)) => self.added_comment(added, issue),
};
answered.push((*at, answer));
}
answered
}
/// One `addComment` payload of `issue`, read as [`TaskSource::add_comment`] reads its own.
///
/// [`TaskSource::add_comment`]: onetaskgraph_plugin_api::TaskSource::add_comment
fn added_comment(
&self,
added: &Value,
issue: &NativeId,
) -> Result<BatchAnswer<Comment>, SourceError> {
let subject = added
.get("subject")
.filter(|value| !value.is_null())
.ok_or_else(|| SourceError::Malformed {
message: "GitHub comment addition returned no subject".into(),
})?;
if required_str(subject, "id")? != issue.0 {
return Err(SourceError::Malformed {
message: "GitHub comment addition answered about another issue".into(),
});
}
let node = added
.pointer("/commentEdge/node")
.filter(|value| !value.is_null())
.ok_or_else(|| SourceError::Malformed {
message: "GitHub comment addition returned no comment".into(),
})?;
let comment = comment_from(node)?;
self.remember_commented(issue)?;
Ok(BatchAnswer::Written(comment))
}
fn task_writes(&self) -> Result<std::sync::MutexGuard<'_, Option<TaskWrites>>, SourceError> {
self.task_writes
.lock()
.map_err(|_| SourceError::Unavailable {
message: "the writes a batch of updates held back were left inconsistent; run the \
command again"
.into(),
})
}
/// Whether the batch of updates running is holding back the writes of the update of `id`
/// it is composing.
pub(super) fn holding_writes_of(&self, id: &NativeId) -> bool {
self.task_writes().is_ok_and(|held| {
held.as_ref()
.is_some_and(|batch| batch.current.as_ref() == Some(id))
})
}
/// Hold one task's board field writes on `board` for the batch of updates running, when one
/// is: answers whether they were held.
pub(super) fn hold_fields(
&self,
board: &str,
item: &str,
writes: &[(String, Value)],
clears: &[&str],
) -> Result<bool, SourceError> {
let mut held = self.task_writes()?;
let Some(batch) = held.as_mut() else {
return Ok(false);
};
let Some(task) = batch.current.clone() else {
return Ok(false);
};
batch.fields.push((
task,
HeldFields {
board: board.to_owned(),
item: item.to_owned(),
writes: writes.to_vec(),
clears: clears.iter().map(|field| (*field).to_owned()).collect(),
},
));
Ok(true)
}
/// Hold one task's issue update for the batch of updates running, when one is: answers
/// whether it was held.
pub(super) fn hold_issue(&self, fields: &Value) -> Result<bool, SourceError> {
let mut held = self.task_writes()?;
let Some(batch) = held.as_mut() else {
return Ok(false);
};
let Some(task) = batch.current.clone() else {
return Ok(false);
};
batch.issues.push((task, fields.clone()));
Ok(true)
}
/// One update of a batch on its own, as the default of
/// [`TaskSource::update_tasks`](onetaskgraph_plugin_api::TaskSource::update_tasks) makes it:
/// one read where its hold or its guard needs one, then the update.
async fn update_alone(
&self,
each: &BatchUpdate,
) -> Result<BatchAnswer<TaskUpdateOutcome>, SourceError> {
if each.if_version.is_some() || !each.when_priority.is_empty() {
let task = TaskSource::get_task(self, &each.id).await?;
if let Some(answer) = decided_on(
self,
task.as_ref(),
each.if_version.as_deref(),
&each.when_priority,
) {
return Ok(answer);
}
}
Ok(self
.targeted_update(&each.id, &each.update)
.await?
.map_or(BatchAnswer::Missing, BatchAnswer::Written))
}
/// [`TaskSource::update_tasks`](onetaskgraph_plugin_api::TaskSource::update_tasks): one
/// batched read of every task updated, deciding each update's hold and guard on it; then
/// every update that read lets through composed exactly as one update is, with its board
/// field writes and its issue update held back, and sent together in
/// [`graphql::WRITE_TASKS`] requests — every field write first, then the issue update of
/// every task whose field writes all landed.
///
/// A batch of one is the update alone, as are a task that is a board draft, an update
/// naming dependencies, and one of an item whose body this process has not read — each
/// sends writes of its own the batch does not hold.
pub(super) async fn updates_batched(
&self,
updates: &[BatchUpdate],
) -> Vec<Result<BatchAnswer<TaskUpdateOutcome>, SourceError>> {
let alone = updates.len() < 2
|| self.expected.journaling()
|| self.deferring().unwrap_or(true)
|| self.task_writes().map_or(true, |held| held.is_some());
if alone {
let mut answers = Vec::with_capacity(updates.len());
for each in updates {
answers.push(self.update_alone(each).await);
}
return answers;
}
let mut answers: Vec<Option<Result<BatchAnswer<TaskUpdateOutcome>, SourceError>>> =
updates.iter().map(|_| None).collect();
let wanted: Vec<NativeId> =
updates
.iter()
.map(|each| each.id.clone())
.fold(Vec::new(), |mut ids, id| {
if !ids.contains(&id) {
ids.push(id);
}
ids
});
let read = match self.items_by_ids(&wanted).await {
Ok(read) => read,
Err(error) => return updates.iter().map(|_| Err(error.clone())).collect(),
};
let mut writing: Vec<usize> = Vec::new();
let mut separately: Vec<usize> = Vec::new();
// An update of a task an earlier update of this batch writes, decided only once that
// one is written, on what it left; and each such task as this batch read it.
let mut later: Vec<usize> = Vec::new();
let mut first_read: BTreeMap<NativeId, Task> = BTreeMap::new();
for (at, each) in updates.iter().enumerate() {
if first_read.contains_key(&each.id) {
later.push(at);
continue;
}
let item = wanted
.iter()
.position(|id| *id == each.id)
.and_then(|slot| read[slot].clone())
.filter(|item| item.kind == BoardKind::Work(ItemKind::Task));
let Some(item) = item else {
answers[at] = Some(Ok(BatchAnswer::Missing));
continue;
};
let task = match item.task() {
Ok(task) => task,
Err(error) => {
answers[at] = Some(Err(error));
continue;
}
};
if let Some(answer) = decided_on(
self,
Some(&task),
each.if_version.as_deref(),
&each.when_priority,
) {
answers[at] = Some(Ok(answer));
continue;
}
first_read.insert(each.id.clone(), task);
if item.content_kind == ContentKind::DraftIssue
|| each.update.depends_on.is_some()
|| self.is_unread(&each.id)
{
separately.push(at);
} else {
writing.push(at);
}
}
// A task updated more than once is written one update at a time, in the batch's order,
// each composed on what the one before left.
let repeated: Vec<usize> = writing
.iter()
.copied()
.filter(|at| {
later
.iter()
.any(|other| updates[*other].id == updates[*at].id)
})
.collect();
writing.retain(|at| !repeated.contains(at));
separately.extend(repeated);
separately.extend(later.iter().copied());
separately.sort_unstable();
// A later update is decided on what the write before it left — its version unknown, as no
// write's answer settles one — or, that write not made, on the task as this batch read it.
let mut left: BTreeMap<NativeId, Task> = BTreeMap::new();
for at in separately {
let each = &updates[at];
if later.contains(&at) {
let basis = left.get(&each.id).or_else(|| first_read.get(&each.id));
let decided = match basis {
Some(task) => decided_on(
self,
Some(task),
each.if_version.as_deref(),
&each.when_priority,
),
// The task's first update in this batch found it missing or unreadable.
None => Some(BatchAnswer::Missing),
};
if let Some(answer) = decided {
answers[at] = Some(Ok(answer));
continue;
}
}
let written = self.targeted_update(&each.id, &each.update).await;
if let Ok(Some(outcome)) = &written {
let mut task = outcome.task.clone();
task.version = None;
left.insert(each.id.clone(), task);
}
answers[at] = Some(
written.map(|written| written.map_or(BatchAnswer::Missing, BatchAnswer::Written)),
);
}
if let Err(error) = self
.task_writes()
.map(|mut held| *held = Some(TaskWrites::default()))
{
for at in writing {
answers[at] = Some(Err(error.clone()));
}
return answers
.into_iter()
.map(|answer| answer.unwrap_or(Ok(BatchAnswer::Missing)))
.collect();
}
let mut composed: Vec<(usize, TaskUpdateOutcome)> = Vec::new();
for at in writing {
let id = &updates[at].id;
if let Ok(mut held) = self.task_writes()
&& let Some(batch) = held.as_mut()
{
batch.current = Some(id.clone());
}
let written = self.targeted_update(id, &updates[at].update).await;
match written {
Ok(Some(outcome)) => composed.push((at, outcome)),
failed => {
// Nothing of an update that was not composed whole is sent.
if let Ok(mut held) = self.task_writes()
&& let Some(batch) = held.as_mut()
{
batch.fields.retain(|(task, _)| task != id);
batch.issues.retain(|(task, _)| task != id);
}
answers[at] =
Some(failed.map(|written| {
written.map_or(BatchAnswer::Missing, BatchAnswer::Written)
}));
}
}
}
let held = self
.task_writes()
.map(|mut held| held.take())
.ok()
.flatten()
.unwrap_or_default();
let refused = self.send_task_writes(held).await;
let versions = self
.versions_after_writes(
composed
.iter()
.map(|(at, _)| updates[*at].id.clone())
.filter(|id| !refused.contains_key(id))
.collect(),
)
.await;
for (at, mut outcome) in composed {
let id = &updates[at].id;
answers[at] = Some(match refused.get(id) {
None => {
outcome.task.version = versions.get(id).cloned();
Ok(BatchAnswer::Written(outcome))
}
Some(error) => {
// What this process recorded of the write is not what the board holds.
let _ = self.forget(id);
Err(error.clone())
}
});
}
answers
.into_iter()
.map(|answer| answer.unwrap_or(Ok(BatchAnswer::Missing)))
.collect()
}
/// The change token each task in `written` holds after this batch's writes of it: the one
/// its issue update's own answer in [`graphql::WRITE_TASKS`] spelled, which selects the
/// issue whole; and, for a task whose update wrote its board fields alone — no answer of
/// which shows the issue — the one a batched read of those tasks, made once every write has
/// been sent, spells. A task neither can answer gets no version, never the one it was read
/// at before the writes; and that read failing leaves every write as written.
async fn versions_after_writes(&self, written: Vec<NativeId>) -> BTreeMap<NativeId, String> {
let mut versions = BTreeMap::new();
let mut unanswered = Vec::new();
for id in written {
match self.written_answer(&id) {
Some(Some(token)) => {
versions.insert(id, token);
}
// Shown whole without every part of a token: a read would read the same parts.
Some(None) => {}
None => unanswered.push(id),
}
}
if unanswered.is_empty() {
return versions;
}
let Ok(read) = self.items_by_ids(&unanswered).await else {
return versions;
};
for (id, item) in unanswered.into_iter().zip(read) {
if let Some(item) = item
&& let Some(token) = item.written_version()
{
self.remember_written_token(&item, token.clone());
versions.insert(id, token);
}
}
versions
}
/// Send every write `held` holds, in [`graphql::WRITE_TASKS`] requests: every task's field
/// writes and clears, then the issue update of every task none of whose field writes was
/// refused — answering, by task, the refusal of each that was not written whole.
async fn send_task_writes(&self, held: TaskWrites) -> BTreeMap<NativeId, SourceError> {
let mut refused: BTreeMap<NativeId, SourceError> = BTreeMap::new();
// Every board-field write and clear of one task goes in one request — its issue update
// follows in a later one, sent only once those all landed.
let mut requests: Vec<Vec<&(NativeId, HeldFields)>> = Vec::new();
let (mut writes, mut clears) = (0, 0);
for held in &held.fields {
let (more_writes, more_clears) = (held.1.writes.len(), held.1.clears.len());
let fits = writes + more_writes <= TASK_FIELD_BATCH
&& clears + more_clears <= MUTATION_BATCH
&& !requests.is_empty();
if !fits {
requests.push(Vec::new());
(writes, clears) = (0, 0);
}
writes += more_writes;
clears += more_clears;
if let Some(request) = requests.last_mut() {
request.push(held);
}
}
for request in requests {
for (task, error) in self.send_field_writes(&request).await {
refused.entry(task).or_insert(error);
}
}
let issues: Vec<&(NativeId, Value)> = held
.issues
.iter()
.filter(|(task, _)| !refused.contains_key(task))
.collect();
for chunk in issues.chunks(MUTATION_BATCH) {
for (task, error) in self.send_issue_updates(chunk).await {
refused.entry(task).or_insert(error);
}
}
refused
}
/// The variables of one [`graphql::WRITE_TASKS`] request sending nothing, every input well
/// formed and naming `filler`, as GitHub requires of a variable it never runs.
fn unsent_task_writes(filler: &str) -> serde_json::Map<String, Value> {
let mut variables = serde_json::Map::new();
for slot in 0..TASK_FIELD_BATCH {
variables.insert(
format!("field{slot}"),
json!({"projectId":filler,"itemId":filler,"fieldId":filler,"value":{"text":""}}),
);
variables.insert(format!("sendField{slot}"), json!(false));
}
for slot in 0..MUTATION_BATCH {
variables.insert(
format!("clear{slot}"),
json!({"projectId":filler,"itemId":filler,"fieldId":filler}),
);
variables.insert(format!("sendClear{slot}"), json!(false));
variables.insert(format!("update{slot}"), json!({"id":filler}));
variables.insert(format!("sendUpdate{slot}"), json!(false));
}
// What each issue update selects of the issue it wrote is read at a read's page sizes.
variables.insert("nestedFirst".to_owned(), json!(super::NESTED_PAGE_SIZE));
variables.insert("boardItems".to_owned(), json!(super::BOARD_ITEMS_PAGE_SIZE));
variables.insert("duplicates".to_owned(), json!(true));
variables
}
/// One [`graphql::WRITE_TASKS`] request of `request`'s field writes and clears, answering
/// each task with a write GitHub refused or answered about another item.
async fn send_field_writes(
&self,
request: &[&(NativeId, HeldFields)],
) -> Vec<(NativeId, SourceError)> {
let Some((_, first)) = request.first() else {
return Vec::new();
};
let mut variables = Self::unsent_task_writes(&first.item);
let mut sent: Vec<(String, &NativeId, &str)> = Vec::new();
let (mut writes, mut clears) = (0, 0);
for (task, held) in request {
for (field, value) in &held.writes {
let alias = format!("field{writes}");
variables.insert(
alias.clone(),
json!({"projectId":held.board,"itemId":held.item,"fieldId":field,"value":value}),
);
variables.insert(format!("sendField{writes}"), json!(true));
sent.push((alias, task, &held.item));
writes += 1;
}
for field in &held.clears {
let alias = format!("clear{clears}");
variables.insert(
alias.clone(),
json!({"projectId":held.board,"itemId":held.item,"fieldId":field}),
);
variables.insert(format!("sendClear{clears}"), json!(true));
sent.push((alias, task, &held.item));
clears += 1;
}
}
let doing = "writing several tasks' board fields together";
let data = match self
.graphql(graphql::WRITE_TASKS, Value::Object(variables))
.await
{
Ok(data) => data,
Err(error) => {
return request
.iter()
.map(|(task, _)| (task.clone(), error.clone()))
.collect();
}
};
let mut refused = Vec::new();
for (alias, task, item) in sent {
let answered = match alias_answer(&data, &alias, doing) {
Ok(answered) => answered
.and_then(|value| value.pointer("/projectV2Item/id"))
.and_then(Value::as_str),
Err(error) => {
refused.push((task.clone(), error));
continue;
}
};
match answered {
Some(answered) if answered == item => {}
Some(_) => refused.push((
task.clone(),
SourceError::Malformed {
message: format!(
"GitHub answered {alias} while {doing} with another project item"
),
},
)),
None => refused.push((task.clone(), refused_alias(&data, &alias, doing))),
}
}
refused
}
/// One [`graphql::WRITE_TASKS`] request of the issue updates of `chunk`, answering each task
/// GitHub refused or answered about another issue.
async fn send_issue_updates(
&self,
chunk: &[&(NativeId, Value)],
) -> Vec<(NativeId, SourceError)> {
let Some((first, _)) = chunk.first() else {
return Vec::new();
};
let mut variables = Self::unsent_task_writes(&first.0);
for (slot, (task, fields)) in chunk.iter().enumerate() {
let mut input = fields.clone();
input["id"] = json!(task.0);
variables.insert(format!("update{slot}"), input);
variables.insert(format!("sendUpdate{slot}"), json!(true));
}
let doing = "updating several tasks together";
let data = match self
.graphql(graphql::WRITE_TASKS, Value::Object(variables))
.await
{
Ok(data) => data,
Err(error) => {
return chunk
.iter()
.map(|(task, _)| (task.clone(), error.clone()))
.collect();
}
};
let mut refused = Vec::new();
for (slot, (task, _)) in chunk.iter().enumerate() {
let alias = format!("update{slot}");
let answered = match alias_answer(&data, &alias, doing) {
Ok(answered) => answered
.and_then(|value| value.pointer("/issue/id"))
.and_then(Value::as_str),
Err(error) => {
refused.push((task.clone(), error));
continue;
}
};
match answered {
Some(answered) if answered == task.0 => {
if let Some(issue) = data.get(&alias).and_then(|value| value.get("issue")) {
self.record_written_issue(issue);
}
}
Some(_) => refused.push((
task.clone(),
SourceError::Malformed {
message: format!(
"GitHub answered {alias} while {doing} with another issue"
),
},
)),
None => refused.push((task.clone(), refused_alias(&data, &alias, doing))),
}
}
refused
}
}