-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathproject_issues.rs
More file actions
2659 lines (2542 loc) · 99.8 KB
/
Copy pathproject_issues.rs
File metadata and controls
2659 lines (2542 loc) · 99.8 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
//! Projects ↔ issues membership REST surface
//! (`linear-projects-v2.md` §7.2).
//!
//! Four routes ship here:
//!
//! | route | what it does |
//! |--------------------------------------------------------|---------------------------------------------------------------|
//! | `GET /projects/{id}/issues` | paginated issue list scoped to a project (`IssueListResponse`) |
//! | `POST /projects/{id}/issues` | bulk add (`{ expected_version, issue_ids: [..] }`) ⇒ `BulkAddResult` |
//! | `DELETE /projects/{id}/issues/{issue_id}?expected_version=` | single detach, CAS-gated; 204 on success |
//! | `GET /issues/{id}/project` | resolve the (single, per v1 `UNIQUE (issue_id)`) project for an issue, or `null` |
//!
//! `BulkAddResult` mirrors the per-row outcome shape pinned in
//! `linear-projects-v2.md` §7.2 / `SCOPE-PROJECTS.md` §7 — every
//! input id ends up either in `added` (the store accepted it) or in
//! `skipped` with a closed-vocabulary `reason` (`"already_in_project"`
//! also carries `existing_project_id` so the UI can render the
//! `Move here?` follow-up without a second round-trip).
//!
//! The bulk-add request is CAS-gated on the **project's** `version`
//! (matches `PATCH /projects/{id}` from §7.1). The detach takes the
//! same `expected_version` as a query param so the URL stays a clean
//! REST shape. The list and "what project owns this issue" GETs are
//! pure reads — no CAS.
//!
//! Authorisation: `(projects, read)` for the two GETs and `(projects,
//! write)` for POST / DELETE — same lanes as the §7.1 CRUD spine.
//! Audit verbs are pinned in [`crate::audit`]: one
//! [`PROJECT_ISSUE_ADD`] per accepted row in a bulk add, and one
//! [`PROJECT_ISSUE_REMOVE`] per detach. Skipped rows never audit
//! (they did not mutate state).
//!
//! [`PROJECT_ISSUE_ADD`]: crate::audit::PROJECT_ISSUE_ADD
//! [`PROJECT_ISSUE_REMOVE`]: crate::audit::PROJECT_ISSUE_REMOVE
use std::sync::Arc;
use axum::{
extract::{Extension, Path, Query, State},
http::StatusCode,
response::{IntoResponse, Json, Response},
routing::{delete, get, post},
Router,
};
use serde::{Deserialize, Serialize};
use utoipa::ToSchema;
use uuid::Uuid;
use dp_domain::project::{ProjectIssueAddOutcome, ProjectIssueAddSkip};
use dp_domain::store::StoreError;
use crate::audit::{self, Principal};
use crate::error::ApiError;
use crate::issues_read::{
attach_repo_slugs, IssueBucket, IssueDto, IssueListResponse,
};
use crate::projects::ProjectDto;
use crate::repos::{clamp_limit, clamp_offset};
use crate::state::AppState;
// ---------------------------------------------------------------------------
// Wire DTOs
// ---------------------------------------------------------------------------
/// Hard cap on `issue_ids` per bulk-add request, pinned in
/// `linear-projects-v2.md` §7.2 / §9.3. Larger selections from the
/// §6.6 triage bulk affordance are chunked client-side.
pub const BULK_ADD_ISSUE_CAP: usize = 100;
/// Body for `POST /projects/{id}/issues`. CAS-gated on the project's
/// current `version` (§7.2); `issue_ids` is capped at
/// [`BULK_ADD_ISSUE_CAP`].
#[derive(Debug, Clone, Deserialize, Serialize, ToSchema)]
pub struct BulkAddIssuesRequest {
/// The `version` the caller observed on the project row. A
/// mismatch returns `409 stale_project_version` just like the
/// §7.1 PATCH / archive routes. Optional only when `view_id`
/// is set — view-scoped adds don't mutate the project row and
/// therefore don't need CAS. Required for project-level adds;
/// the handler returns `400 missing_expected_version` if it's
/// missing in that case.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub expected_version: Option<i64>,
/// Issue ids to attach. Capped at [`BULK_ADD_ISSUE_CAP`]; over
/// the cap returns `400 bulk_add_too_large`. An empty array is
/// accepted as a no-op (returns `BulkAddResult { added: [],
/// skipped: [] }` and does not bump the project version).
pub issue_ids: Vec<Uuid>,
/// Optional saved-view id (PROJECT-VIEW.md §5.4 amendment).
/// When set, the accepted issues are *also* attached to the
/// named view's membership table after the project add
/// succeeds, so the tab the user added them on retains them.
/// Skipped (already-in-project) ids are still added to the
/// view — the user expects the issues to appear on the tab
/// regardless of whether they were brand new to the project.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub view_id: Option<Uuid>,
}
/// One row in [`BulkAddResult::skipped`]. Mirrors
/// [`ProjectIssueAddSkip`] but kept as a separate wire type so the
/// OpenAPI schema is decoupled from the domain crate and so the
/// `reason` vocabulary is documented at the REST boundary.
#[derive(Debug, Clone, Serialize, Deserialize, ToSchema)]
pub struct BulkAddSkipDto {
/// The issue id that was rejected.
pub issue_id: Uuid,
/// Closed-vocabulary reason; one of:
///
/// * `"already_in_project"` — the v1 `UNIQUE (issue_id)`
/// constraint fired. `existing_project_id` is set so the UI
/// can render a `Move here?` affordance.
/// * `"unknown_issue"` — the issue id did not resolve in
/// `dp_issues`.
/// * `"cross_org"` — the issue's `org_id` differs from the
/// project's `org_id` (v1: one org per project, §4).
pub reason: String,
/// Set when `reason == "already_in_project"`. Lets the UI link
/// directly to the existing project's detail page.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub existing_project_id: Option<Uuid>,
}
impl From<ProjectIssueAddSkip> for BulkAddSkipDto {
fn from(s: ProjectIssueAddSkip) -> Self {
Self {
issue_id: s.issue_id,
reason: s.reason,
existing_project_id: s.existing_project_id,
}
}
}
/// `BulkAddResult` — the per-row outcome shape `linear-projects-v2.md`
/// §7.2 / `SCOPE-PROJECTS.md` §7 wire through the REST layer so the
/// UI can render add-by-add status from one round-trip.
#[derive(Debug, Clone, Serialize, Deserialize, ToSchema)]
pub struct BulkAddResult {
/// Issue ids the store accepted into the project.
pub added: Vec<Uuid>,
/// Issue ids the store refused, each with a closed-vocabulary
/// `reason`. See [`BulkAddSkipDto`].
pub skipped: Vec<BulkAddSkipDto>,
}
impl From<ProjectIssueAddOutcome> for BulkAddResult {
fn from(o: ProjectIssueAddOutcome) -> Self {
Self {
added: o.added,
skipped: o.skipped.into_iter().map(BulkAddSkipDto::from).collect(),
}
}
}
/// Query params for `DELETE /projects/{id}/issues/{issue_id}`. The
/// `expected_version` rides as a query param so the URL stays a
/// clean REST shape — matches the §7.1 PATCH convention.
#[derive(Debug, Clone, Deserialize)]
pub struct RemoveIssueQuery {
/// The `version` the caller observed on the project row.
/// Required when `view` is absent (project-level detach);
/// ignored when `view` is set (view-membership detach does not
/// mutate the project row).
#[serde(default)]
pub expected_version: Option<i64>,
/// Optional saved-view id (PROJECT-VIEW.md §5.4 amendment).
/// When set, the detach is scoped to the view's membership
/// table only — the issue stays on the project and on every
/// other view that includes it. When absent, the detach is
/// project-level (and cascades into every view via the FK).
#[serde(default)]
pub view: Option<Uuid>,
}
/// Query params for `GET /projects/{id}/issues`. Slice A keeps the
/// filter narrow: pagination + state + a title substring. The full
/// `ListIssuesQuery` lane is reserved for slice B once project-aware
/// SQL filtering lands; v1 pulls the membership list, hydrates each
/// row, and filters in-memory — which is correct for the
/// O(≤100) project sizes the slice-A surfaces target.
#[derive(Debug, Clone, Default, Deserialize)]
pub struct ListProjectIssuesQuery {
/// State filter (`open` / `closed` / `all`); defaults to `all`
/// here (a project detail surface wants to see both open and
/// closed work by default — different from `GET /issues` which
/// defaults to `open`). Pass `?state=open` for an active-only
/// view.
#[serde(default)]
pub state: Option<String>,
/// Case-insensitive substring on issue title.
#[serde(default)]
pub q: Option<String>,
/// Page size; clamped 1..=200, default 50.
#[serde(default)]
pub limit: Option<i64>,
/// Page offset, 0-based.
#[serde(default)]
pub offset: Option<i64>,
/// Group-by dimension (PROJECT-VIEW.md §5.1 / §7.2). Accepted:
/// `status`, `tag:<key>`. Unknown values return
/// `400 invalid_group_by`. When absent, the response is the
/// flat list (no `buckets` sidecar).
#[serde(default)]
pub group_by: Option<String>,
/// AND-combined filter chips (PROJECT-VIEW.md §5.2 / §5.4).
/// Wire form: `<dim>:<value>;<dim>:<value>;…` with `;` as
/// the chip separator and `:` as the dim/value separator
/// (§5.4 — `,` is unsafe inside tag values, `;` is not legal
/// in tag values nor UUIDs). Tag values themselves may
/// contain `:` (e.g. `team:backend:v2`); the parser splits on
/// the **first** `:` after the dim. Accepted dims this slice:
///
/// * `status:open` / `status:closed`
/// * `assignee:<login>`
/// * `label:<text>`
/// * `tag:<key>:<value>`
///
/// Unknown dims return `400 invalid_filter`. Filters apply
/// **before** bucket counts, so the `buckets` sidecar always
/// reflects post-filter totals (§5.2).
#[serde(default)]
pub filter: Option<String>,
/// Sort order (PROJECT-VIEW.md §5.3). Accepted:
/// `updated_desc` (default), `updated_asc`, `title_asc`.
/// Unknown values return `400 invalid_sort`.
#[serde(default)]
pub sort: Option<String>,
/// Optional saved-view id (PROJECT-VIEW.md §5.4 amendment).
/// When set, the response intersects project membership with
/// the view's `dp_project_view_issues` rows, then applies the
/// caller-supplied `filter` / `group_by` / `sort` on top. When
/// absent, the request behaves as the "All" tab and returns
/// every project-level issue (the historical default).
#[serde(default)]
pub view: Option<Uuid>,
}
// ---------------------------------------------------------------------------
// Handlers
// ---------------------------------------------------------------------------
pub(crate) fn map_cas_error(project_id: Uuid, err: StoreError) -> ApiError {
match err {
StoreError::NotFound { entity: "project", .. } => ApiError::NotFound {
code: "project_not_found",
message: format!("no project with id {project_id}"),
},
StoreError::NotFound { entity: "project_issue", id } => ApiError::NotFound {
code: "project_issue_not_found",
message: format!("issue {id} is not attached to project {project_id}"),
},
StoreError::Conflict(msg) => ApiError::Conflict {
code: "stale_project_version",
message: msg,
},
StoreError::Invalid(msg) => ApiError::BadRequest {
code: "project_invalid",
message: msg,
},
e => e.into(),
}
}
/// `GET /projects/{id}/issues` — paginated issue list scoped to a
/// project (§7.2). Same envelope as `GET /issues`.
///
/// Implementation note: v1 resolves membership via
/// [`Store::list_issue_ids_for_project`], fetches each issue row
/// with [`Store::get_issue`], applies optional `state` / `q` filters
/// in-memory, then paginates. Correct for the slice-A target of
/// projects with ≤ 100 issues. The natural follow-up — a SQL-level
/// "filter `dp_issues` by `project_id`" — is deferred until
/// `IssueListFilter` grows a `project_id` field in slice B.
#[utoipa::path(
get,
path = "/projects/{id}/issues",
params(
("id" = Uuid, Path, description = "Project id"),
("state" = Option<String>, Query, description = "open|closed|all (default all)"),
("q" = Option<String>, Query, description = "Substring search on title"),
("limit" = Option<i64>, Query, description = "Page size (1..=200, default 50)"),
("offset" = Option<i64>, Query, description = "Page offset (default 0)"),
("group_by" = Option<String>, Query, description = "Bucket dimension: status | tag:<key> (PROJECT-VIEW.md §5.1)"),
("filter" = Option<String>, Query, description = "AND-combined chips: <dim>:<value>;… — status|assignee|label|tag:<key> (PROJECT-VIEW.md §5.2/§5.4)"),
("sort" = Option<String>, Query, description = "updated_desc (default) | updated_asc | title_asc"),
),
responses(
(status = 200, description = "Paginated issue list scoped to the project", body = IssueListResponse),
(status = 404, description = "No such project"),
),
tag = "projects",
)]
pub async fn list_project_issues(
State(state): State<AppState>,
Path(project_id): Path<Uuid>,
Query(q): Query<ListProjectIssuesQuery>,
) -> Result<Json<IssueListResponse>, ApiError> {
// 404 fast when the project itself is missing so the caller does
// not get an empty-rows list and assume an empty project.
let _project = state
.store
.get_project(project_id)
.await?
.ok_or_else(|| ApiError::NotFound {
code: "project_not_found",
message: format!("no project with id {project_id}"),
})?;
let state_filter = match q.state.as_deref() {
None | Some("") | Some("all") => None,
Some("open") => Some(dp_domain::issue::IssueState::Open),
Some("closed") => Some(dp_domain::issue::IssueState::Closed),
Some(other) => {
return Err(ApiError::BadRequest {
code: "invalid_state",
message: format!("invalid state filter: {other}"),
});
}
};
let q_str = q.q.as_deref().map(|s| s.trim().to_lowercase());
// Parse group_by / filter / sort upfront so a malformed param
// doesn't waste a DB round-trip.
let group_by = parse_group_by(q.group_by.as_deref())?;
let filter_clauses = parse_filter(q.filter.as_deref())?;
let sort_order = parse_sort(q.sort.as_deref())?;
// PROJECT-VIEW.md §5.4 amendment — saved-view tabs are
// independent containers. When `?view=` is set the membership
// list comes *only* from `dp_project_view_issues`; we do not
// intersect with project-level membership. This is what makes
// an issue added on a saved-view tab appear *only* on that tab
// and not bleed into the "All" tab.
let ids: Vec<Uuid> = match q.view {
Some(view_id) => state.store.list_issue_ids_for_view(view_id).await?,
None => state.store.list_issue_ids_for_project(project_id).await?,
};
// Resolve each issue row. Missing rows (target FK was hard-deleted
// out from under us — unlikely given `ON DELETE CASCADE` but
// belt-and-braces) are silently dropped; the membership row
// would normally have been cascaded along with it, so this
// branch should never fire in practice.
let mut issues: Vec<dp_domain::issue::Issue> = Vec::with_capacity(ids.len());
for id in &ids {
if let Some(i) = state.store.get_issue(*id).await? {
issues.push(i);
}
}
// Apply in-memory filters in the same conjunctive style the SQL
// layer would.
if let Some(s) = state_filter {
issues.retain(|i| i.state == s);
}
if let Some(needle) = q_str.as_deref().filter(|s| !s.is_empty()) {
issues.retain(|i| i.title.to_lowercase().contains(needle));
}
// §5.2 — filter chips apply **before** group-by bucket counts,
// so the `buckets` sidecar always reflects post-filter totals.
apply_filter_clauses(&*state.store, project_id, &filter_clauses, &mut issues).await?;
// Build the per-issue bucket assignments + counts. Done **after**
// filtering so the counts the client renders next to each
// collapsed section match what's inside (§5.2 — post-filter
// counts are non-negotiable for triage surfaces).
let bucketing = match &group_by {
Some(g) => Some(build_buckets(&*state.store, project_id, g, &issues).await?),
None => None,
};
// Sort post-filter, pre-pagination (§5.3). Stable sort so equal
// keys retain the existing `added_at ASC, issue_id ASC` order
// that `list_issue_ids_for_project` already gives us.
apply_sort(&mut issues, sort_order);
let total = issues.len() as i64;
let limit = clamp_limit(q.limit);
let offset = clamp_offset(q.offset);
let start = offset.max(0) as usize;
let end = (start + limit.max(0) as usize).min(issues.len());
let page = if start >= issues.len() {
Vec::new()
} else {
issues[start..end].to_vec()
};
let mut dtos: Vec<IssueDto> = page.into_iter().map(IssueDto::from).collect();
attach_repo_slugs(&*state.store, &mut dtos).await?;
// Attach `bucket_keys` per row from the precomputed assignment
// map. Issues that fell into the "No <key>" bucket carry a
// single-element `[None]` so the client always knows the grouping
// is active.
let buckets_out = if let Some(b) = bucketing {
for d in dtos.iter_mut() {
let keys = b
.assignments
.get(&d.id)
.cloned()
.unwrap_or_else(|| vec![None]);
d.bucket_keys = Some(keys);
}
Some(b.buckets)
} else {
None
};
Ok(Json(IssueListResponse {
rows: dtos,
total,
limit,
offset,
buckets: buckets_out,
}))
}
/// Parsed group-by dimension (PROJECT-VIEW.md §5.1).
#[derive(Debug, Clone)]
enum GroupBy {
/// Bucket by `dp_issues.state` — two buckets, `open` and
/// `closed`. The "No <key>" bucket never fires (state is
/// non-null).
Status,
/// Bucket by `dp_tags.value` joined through `dp_tag_links`
/// where `dp_tags.key = <key>` and `kind='kv'`. Issues with no
/// matching link surface under the synthetic "No <key>" bucket.
Tag { key: String },
}
fn parse_group_by(raw: Option<&str>) -> Result<Option<GroupBy>, ApiError> {
let Some(raw) = raw.map(str::trim).filter(|s| !s.is_empty()) else {
return Ok(None);
};
if raw == "status" {
return Ok(Some(GroupBy::Status));
}
if let Some(key) = raw.strip_prefix("tag:") {
if !is_valid_tag_key(key) {
return Err(ApiError::BadRequest {
code: "invalid_group_by",
message: format!("invalid tag key in group_by: {key:?}"),
});
}
return Ok(Some(GroupBy::Tag { key: key.to_owned() }));
}
Err(ApiError::BadRequest {
code: "invalid_group_by",
message: format!("unsupported group_by dimension: {raw:?}"),
})
}
/// Mirrors `tagging.md` §3 — kv keys are `[a-z0-9][a-z0-9-]*` up to
/// 50 chars. Keeps the parser identical to what the tag-write path
/// will enforce so views and tags can't drift.
fn is_valid_tag_key(s: &str) -> bool {
if s.is_empty() || s.len() > 50 {
return false;
}
let mut chars = s.chars();
let first = chars.next().unwrap();
if !first.is_ascii_lowercase() && !first.is_ascii_digit() {
return false;
}
chars.all(|c| c.is_ascii_lowercase() || c.is_ascii_digit() || c == '-')
}
/// One parsed filter clause (PROJECT-VIEW.md §5.2). AND-combined
/// across the wire `filter=` param.
#[derive(Debug, Clone)]
pub(crate) enum FilterClause {
Status(dp_domain::issue::IssueState),
Assignee(String),
Label(String),
Tag { key: String, value: String },
/// `milestone:<dp_milestones.id>` — narrows the issue set to
/// those pointing at the given milestone (PROJECT-VIEW.md
/// §5.4, Slice 3↔1 bridge). The value is the dev-pulse
/// surrogate UUID, not the GitHub number or title, so the
/// filter survives milestone renames and disambiguates
/// same-title milestones in different repos.
Milestone(Uuid),
}
/// Lower a stored [`dp_domain::project_view::ProjectViewFilterClause`]
/// into the in-memory [`FilterClause`] the issue handler already
/// knows how to apply. The stored clauses were validated at write
/// time so any unknown / malformed entry here is a corruption-class
/// bug, not user input — we silently drop it (returning `None`) so
/// the rest of the count still reflects the well-formed clauses.
pub(crate) fn view_clause_to_filter(
c: &dp_domain::project_view::ProjectViewFilterClause,
) -> Option<FilterClause> {
use dp_domain::project_view::ProjectViewFilterClause as V;
match c {
V::Status { value } => match value.as_str() {
"open" => Some(FilterClause::Status(dp_domain::issue::IssueState::Open)),
"closed" => Some(FilterClause::Status(dp_domain::issue::IssueState::Closed)),
_ => None,
},
V::Assignee { value } => Some(FilterClause::Assignee(value.clone())),
V::Label { value } => Some(FilterClause::Label(value.clone())),
V::Tag { key, value } => Some(FilterClause::Tag {
key: key.clone(),
value: value.clone(),
}),
V::Milestone { value } => Uuid::parse_str(value).ok().map(FilterClause::Milestone),
}
}
/// Parse the wire `filter=` param (PROJECT-VIEW.md §5.4). `;`
/// separates clauses; the first `:` in each clause separates the
/// dim from the value (so tag values like `team:backend:v2` round-
/// trip). Empty clauses (`a;;b`) are ignored. An empty / absent
/// param parses to an empty vec.
fn parse_filter(raw: Option<&str>) -> Result<Vec<FilterClause>, ApiError> {
let Some(raw) = raw.map(str::trim).filter(|s| !s.is_empty()) else {
return Ok(Vec::new());
};
let mut out = Vec::new();
for chunk in raw.split(';') {
let chunk = chunk.trim();
if chunk.is_empty() {
continue;
}
let (dim, value) = chunk.split_once(':').ok_or_else(|| ApiError::BadRequest {
code: "invalid_filter",
message: format!("filter clause missing ':' separator: {chunk:?}"),
})?;
let dim = dim.trim();
let value = value.trim();
if value.is_empty() {
return Err(ApiError::BadRequest {
code: "invalid_filter",
message: format!("filter clause has empty value: {chunk:?}"),
});
}
match dim {
"status" => match value {
"open" => out.push(FilterClause::Status(dp_domain::issue::IssueState::Open)),
"closed" => out.push(FilterClause::Status(dp_domain::issue::IssueState::Closed)),
other => {
return Err(ApiError::BadRequest {
code: "invalid_filter",
message: format!("status filter must be 'open' or 'closed', got {other:?}"),
});
}
},
"assignee" => out.push(FilterClause::Assignee(value.to_owned())),
"label" => out.push(FilterClause::Label(value.to_owned())),
"milestone" => {
let id = Uuid::parse_str(value).map_err(|_| ApiError::BadRequest {
code: "invalid_filter",
message: format!(
"milestone filter value must be a milestone UUID, got {value:?}"
),
})?;
out.push(FilterClause::Milestone(id));
}
"tag" => {
let (key, tag_value) = value.split_once(':').ok_or_else(|| {
ApiError::BadRequest {
code: "invalid_filter",
message: format!("tag filter must be 'tag:<key>:<value>', got {chunk:?}"),
}
})?;
if !is_valid_tag_key(key) {
return Err(ApiError::BadRequest {
code: "invalid_filter",
message: format!("invalid tag key in filter: {key:?}"),
});
}
if tag_value.is_empty() {
return Err(ApiError::BadRequest {
code: "invalid_filter",
message: format!("tag filter has empty value: {chunk:?}"),
});
}
out.push(FilterClause::Tag {
key: key.to_owned(),
value: tag_value.to_owned(),
});
}
other => {
return Err(ApiError::BadRequest {
code: "invalid_filter",
message: format!("unknown filter dim: {other:?}"),
});
}
}
}
Ok(out)
}
/// Apply parsed [`FilterClause`]s in-memory against the project's
/// issue set. Tag filters resolve through the store's
/// `list_project_issue_tag_values` so the SQL is the same one the
/// group-by path uses — keeps "filter by category:firmware ⇒ group
/// by gate" totals aligned with the bucket counts (§5.2).
pub(crate) async fn apply_filter_clauses(
store: &dyn dp_domain::store::Store,
project_id: Uuid,
clauses: &[FilterClause],
issues: &mut Vec<dp_domain::issue::Issue>,
) -> Result<(), ApiError> {
use std::collections::HashSet;
for clause in clauses {
match clause {
FilterClause::Status(s) => {
issues.retain(|i| i.state == *s);
}
FilterClause::Assignee(login) => {
let needle = login.to_ascii_lowercase();
issues.retain(|i| {
i.assignees
.iter()
.any(|a| a.eq_ignore_ascii_case(&needle))
});
}
FilterClause::Label(label) => {
let needle = label.to_ascii_lowercase();
issues.retain(|i| {
i.labels.iter().any(|l| l.eq_ignore_ascii_case(&needle))
});
}
FilterClause::Tag { key, value } => {
let scope_ids: Vec<Uuid> = issues.iter().map(|i| i.id).collect();
let _ = project_id;
let pairs = store
.list_issue_tag_values(&scope_ids, key)
.await?;
let matching: HashSet<Uuid> = pairs
.into_iter()
.filter(|(_, v)| v == value)
.map(|(id, _)| id)
.collect();
issues.retain(|i| matching.contains(&i.id));
}
FilterClause::Milestone(mid) => {
// Resolve via `list_project_milestones` so the
// filter only matches milestones already adopted
// by this project — a stale URL pointing at a
// milestone from another project (or a deleted
// one) collapses to an empty result, not an
// accidental cross-project leak. Until
// `dp_issues.milestone_id` ships, match by
// (repo_id, title) — milestone titles are
// unique per repo on the GitHub side.
let milestones = store
.list_project_milestones(project_id, /* include_closed */ true)
.await?;
let Some(m) = milestones.into_iter().find(|m| m.id == *mid) else {
issues.clear();
continue;
};
issues.retain(|i| {
i.repo_id == m.repo_id
&& i.milestone.as_deref() == Some(m.title.as_str())
});
}
}
}
Ok(())
}
/// Sort order (PROJECT-VIEW.md §5.3).
#[derive(Debug, Clone, Copy, Default)]
enum SortOrder {
#[default]
UpdatedDesc,
UpdatedAsc,
TitleAsc,
}
fn parse_sort(raw: Option<&str>) -> Result<SortOrder, ApiError> {
match raw.map(str::trim).filter(|s| !s.is_empty()) {
None | Some("updated_desc") => Ok(SortOrder::UpdatedDesc),
Some("updated_asc") => Ok(SortOrder::UpdatedAsc),
Some("title_asc") => Ok(SortOrder::TitleAsc),
Some(other) => Err(ApiError::BadRequest {
code: "invalid_sort",
message: format!("unknown sort: {other:?}"),
}),
}
}
fn apply_sort(issues: &mut [dp_domain::issue::Issue], sort: SortOrder) {
match sort {
SortOrder::UpdatedDesc => {
issues.sort_by(|a, b| b.updated_at.cmp(&a.updated_at));
}
SortOrder::UpdatedAsc => {
issues.sort_by(|a, b| a.updated_at.cmp(&b.updated_at));
}
SortOrder::TitleAsc => {
issues.sort_by(|a, b| a.title.to_lowercase().cmp(&b.title.to_lowercase()));
}
}
}
/// Output of [`build_buckets`]: the ordered bucket list returned in
/// the response plus a per-issue-id assignment map used to stamp
/// `IssueDto::bucket_keys` after pagination.
struct Bucketing {
buckets: Vec<IssueBucket>,
/// `issue_id → bucket_keys`. An issue can map to multiple keys
/// when grouping by a multi-valued tag (e.g. an issue tagged
/// `category:firmware` and `category:hardware`). `None` in the
/// vector means the synthetic "No <key>" bucket.
assignments: std::collections::HashMap<Uuid, Vec<Option<String>>>,
}
async fn build_buckets(
store: &dyn dp_domain::store::Store,
project_id: Uuid,
group_by: &GroupBy,
issues: &[dp_domain::issue::Issue],
) -> Result<Bucketing, ApiError> {
use std::collections::{HashMap, HashSet};
let issue_ids: HashSet<Uuid> = issues.iter().map(|i| i.id).collect();
let mut assignments: HashMap<Uuid, Vec<Option<String>>> =
HashMap::with_capacity(issues.len());
match group_by {
GroupBy::Status => {
let mut open = 0i64;
let mut closed = 0i64;
for i in issues {
match i.state {
dp_domain::issue::IssueState::Open => {
open += 1;
assignments.insert(i.id, vec![Some("open".to_owned())]);
}
dp_domain::issue::IssueState::Closed => {
closed += 1;
assignments.insert(i.id, vec![Some("closed".to_owned())]);
}
}
}
// Hide empty status buckets — post-filter (§5.2). When
// the user filtered to `state=closed` there's no point
// rendering an empty `Open` section.
let mut buckets = Vec::new();
if open > 0 {
buckets.push(IssueBucket {
key: Some("open".into()),
label: "Open".into(),
open,
closed: 0,
});
}
if closed > 0 {
buckets.push(IssueBucket {
key: Some("closed".into()),
label: "Closed".into(),
open: 0,
closed,
});
}
Ok(Bucketing { buckets, assignments })
}
GroupBy::Tag { key } => {
// Pull every (issue_id, value) link for this key across
// the post-filter issues set. We scope by the actual
// issue ids (not just `dp_project_issues`) so saved-view
// tabs whose membership lives in `dp_project_view_issues`
// also pick up their tag links (PROJECT-VIEW.md §5.4).
let scope_ids: Vec<Uuid> = issues.iter().map(|i| i.id).collect();
let rows = store
.list_issue_tag_values(&scope_ids, key)
.await?;
let _ = project_id;
// Per-bucket open/closed counters. The issues vector is
// already post-filter — use it as the source of truth
// for issue states so a stale tag link on a filtered-out
// issue doesn't get counted.
let state_by_id: HashMap<Uuid, dp_domain::issue::IssueState> =
issues.iter().map(|i| (i.id, i.state)).collect();
let mut counts: HashMap<String, (i64, i64)> = HashMap::new();
for (issue_id, value) in &rows {
if !issue_ids.contains(issue_id) {
continue; // filtered out by state/q
}
let entry = assignments.entry(*issue_id).or_default();
if !entry.iter().any(|v| v.as_deref() == Some(value.as_str())) {
entry.push(Some(value.clone()));
}
let bucket = counts.entry(value.clone()).or_insert((0, 0));
match state_by_id.get(issue_id).copied() {
Some(dp_domain::issue::IssueState::Open) => bucket.0 += 1,
Some(dp_domain::issue::IssueState::Closed) => bucket.1 += 1,
None => {}
}
}
// Synthetic "No <key>" bucket: every project issue that
// didn't receive any assignment above.
let mut no_key_open = 0i64;
let mut no_key_closed = 0i64;
for i in issues {
if !assignments.contains_key(&i.id) {
assignments.insert(i.id, vec![None]);
match i.state {
dp_domain::issue::IssueState::Open => no_key_open += 1,
dp_domain::issue::IssueState::Closed => no_key_closed += 1,
}
}
}
// Order: count desc, then key asc as a deterministic
// tie-breaker. The ordinal-taxonomy override
// (PROJECT-VIEW.md §5.1 — gate/priority) lands with the
// config table; for now even `gate` falls under count
// desc. The synthetic "No <key>" bucket is pinned last
// and only emitted when non-empty (§5.2).
let mut bucket_entries: Vec<(String, i64, i64)> = counts
.into_iter()
.map(|(k, (o, c))| (k, o, c))
.collect();
bucket_entries.sort_by(|a, b| {
(b.1 + b.2)
.cmp(&(a.1 + a.2))
.then_with(|| a.0.cmp(&b.0))
});
let mut buckets: Vec<IssueBucket> = bucket_entries
.into_iter()
.map(|(k, o, c)| IssueBucket {
label: format!("{key}:{k}"),
key: Some(k),
open: o,
closed: c,
})
.collect();
if no_key_open + no_key_closed > 0 {
buckets.push(IssueBucket {
key: None,
label: format!("No {key}"),
open: no_key_open,
closed: no_key_closed,
});
}
Ok(Bucketing { buckets, assignments })
}
}
}
/// `POST /projects/{id}/issues` — bulk add (§7.2). Returns
/// `BulkAddResult` so per-row outcomes flow back in one round-trip.
///
/// * `issue_ids` capped at [`BULK_ADD_ISSUE_CAP`]; over the cap
/// returns `400 bulk_add_too_large`.
/// * CAS-gated on the project's `version`; mismatch returns
/// `409 stale_project_version`.
/// * One audit row per accepted issue
/// ([`audit::PROJECT_ISSUE_ADD`]); skipped rows never audit.
#[utoipa::path(
post,
path = "/projects/{id}/issues",
params(("id" = Uuid, Path, description = "Project id")),
request_body = BulkAddIssuesRequest,
responses(
(status = 200, description = "Per-row outcome of the bulk add", body = BulkAddResult),
(status = 400, description = "Validation failure (cap, etc.)"),
(status = 404, description = "No such project"),
(status = 409, description = "Stale `expected_version`"),
),
tag = "projects",
)]
pub async fn bulk_add_issues(
State(state): State<AppState>,
Extension(principal): Extension<Principal>,
Path(project_id): Path<Uuid>,
Json(body): Json<BulkAddIssuesRequest>,
) -> Result<Json<BulkAddResult>, ApiError> {
if body.issue_ids.len() > BULK_ADD_ISSUE_CAP {
return Err(ApiError::BadRequest {
code: "bulk_add_too_large",
message: format!(
"issue_ids is capped at {BULK_ADD_ISSUE_CAP}; got {}",
body.issue_ids.len()
),
});
}
// PROJECT-VIEW.md §5.4 amendment — saved-view tabs are
// independent containers. A POST with `view_id` attaches the
// issues *only* to the view membership and never touches
// `dp_project_issues`. No CAS, no version bump, no "All" tab
// side effect. We still validate cross-org + unknown-issue so
// the UI gets the same closed-vocabulary `skipped` surface.
if let Some(view_id) = body.view_id {
let project = state
.store
.get_project(project_id)
.await?
.ok_or_else(|| ApiError::NotFound {
code: "project_not_found",
message: format!("no project with id {project_id}"),
})?;
let mut added: Vec<Uuid> = Vec::new();
let mut skipped: Vec<BulkAddSkipDto> = Vec::new();
for &issue_id in &body.issue_ids {
match state.store.get_issue(issue_id).await? {
None => skipped.push(BulkAddSkipDto {
issue_id,
reason: "unknown_issue".into(),
existing_project_id: None,
}),
Some(i) if i.org_id != project.org_id => skipped.push(BulkAddSkipDto {
issue_id,
reason: "cross_org".into(),
existing_project_id: None,
}),
Some(_) => added.push(issue_id),
}
}
if !added.is_empty() {
state.store.add_issues_to_view(view_id, &added).await?;
}
for issue_id in &added {
audit::record(
state.store.as_ref(),
principal.actor_user_id,
audit::PROJECT_ISSUE_ADD,
format!("{project_id}:{issue_id}:view={view_id}"),
)
.await?;
}
return Ok(Json(BulkAddResult { added, skipped }));
}
// Project-level add (the "All" tab). CAS is mandatory here
// because the project row's `version`/`issue_count` mutates.
let expected_version = body.expected_version.ok_or(ApiError::BadRequest {
code: "missing_expected_version",
message: "expected_version is required for project-level bulk add".into(),
})?;
let outcome = state
.store
.add_issues_to_project(
project_id,
expected_version,
&body.issue_ids,
Some(principal.actor_user_id),
)
.await
.map_err(|e| map_cas_error(project_id, e))?;
for issue_id in &outcome.added {
audit::record(
state.store.as_ref(),
principal.actor_user_id,
audit::PROJECT_ISSUE_ADD,
format!("{project_id}:{issue_id}"),
)
.await?;
}
Ok(Json(outcome.into()))
}
/// `DELETE /projects/{id}/issues/{issue_id}?expected_version=` —
/// single detach (§7.2). 204 on success; CAS-gated on the project's
/// `version`. A no-op detach (the issue is not currently in this
/// project) is `404 project_issue_not_found` — same idempotence-at-
/// the-application-boundary contract as the store layer.
#[utoipa::path(
delete,
path = "/projects/{id}/issues/{issue_id}",
params(
("id" = Uuid, Path, description = "Project id"),
("issue_id" = Uuid, Path, description = "Issue id to detach"),
("expected_version" = i64, Query, description = "Caller-observed project version (CAS)"),
),
responses(
(status = 204, description = "Detached"),
(status = 404, description = "No such project, or issue is not in this project"),
(status = 409, description = "Stale `expected_version`"),
),
tag = "projects",
)]
pub async fn remove_project_issue(
State(state): State<AppState>,
Extension(principal): Extension<Principal>,
Path((project_id, issue_id)): Path<(Uuid, Uuid)>,
Query(q): Query<RemoveIssueQuery>,
) -> Result<Response, ApiError> {
// PROJECT-VIEW.md §5.4 amendment — a `?view=` scopes the detach
// to the saved view's membership only; the issue stays on the
// project. No `expected_version` is required (the project row
// doesn't mutate). Audit verb stays `project_issue_remove`
// with the view id appended so an operator can still trace
// "why did this issue disappear from a tab".
if let Some(view_id) = q.view {
// Confirm the project exists so we 404 rather than silently
// succeed on a stale URL.
if state.store.get_project(project_id).await?.is_none() {
return Err(ApiError::NotFound {
code: "project_not_found",
message: format!("no project with id {project_id}"),
});