steid

@jamesgill /

Rust41.2 KBCode·Blame·History·Raw
1//! Issues: opening one, reading them, commenting, closing, reopening and editing.
2//!
3//! **Reading follows the repository's visibility; every write is owner-only.** Both
4//! rules live here rather than on the pages, so `/api` and a future transport cannot
5//! reach a different answer than the issues page does.
6//!
7//! The two refusals are deliberately different, matching the split
8//! [`view_repo`](super::view_repo) already sets:
9//!
10//! - A repository the actor may not *see* is `NotFound` (or `Ok(None)` on a read), so a
11//! private repository stays absent rather than merely locked.
12//! - A repository the actor *can* see but does not own is `Forbidden`, because the
13//! repository is public anyway and pretending otherwise would be theatre.
14
15use std::{collections::HashMap, time::SystemTime};
16
17use crate::domain::{
18 Actor, DomainError, Issue, IssueComment, IssueCommentId, IssueId, IssueNumber, IssueState,
19 OrgName, RepoName, Repository, UserId,
20 repository::{
21 IssueCounts, IssueRepository, LabelRepository, MembershipRepository, OrgRepository,
22 RepoRepository, UserRepository,
23 },
24};
25
26use super::{
27 authz::{is_org_member, is_org_owner},
28 error::{Error, Result},
29 label::{LabelView, labels_by_issue},
30 paging::{Paged, clamp, offset, page_count},
31};
32
33/// How many issues the repository has in one state.
34fn state_count(counts: IssueCounts, state: IssueState) -> usize {
35 let count = match state {
36 IssueState::Open => counts.open,
37 IssueState::Closed => counts.closed,
38 };
39
40 count as usize
41}
42
43/// How many issues one page of a list shows.
44///
45/// The log's page rather than the refs pages': an issue row is two lines and read, not
46/// scanned past.
47pub const ISSUE_LIMIT: usize = 50;
48
49/// What someone typed into the new-issue form. Raw — validation is [`Issue::new`]'s job.
50#[derive(Debug, Clone, PartialEq, Eq)]
51pub struct NewIssue {
52 pub title: String,
53 pub body: String,
54}
55
56/// An edit to an issue's title and body. The same shape as [`NewIssue`], kept separate
57/// so the two cannot be passed for one another.
58#[derive(Debug, Clone, PartialEq, Eq)]
59pub struct IssueEdit {
60 pub title: String,
61 pub body: String,
62}
63
64/// An issue as it appears in a listing.
65///
66/// The body is absent on purpose: a list row shows one line, and carrying every body
67/// through it would load the whole conversation to render titles.
68#[derive(Debug, Clone, PartialEq, Eq)]
69pub struct IssueSummary {
70 pub number: IssueNumber,
71 pub title: String,
72 pub state: IssueState,
73 /// The author's handle, or `None` if their account is gone. Rendered as "someone"
74 /// rather than left blank — an issue outlives the account that opened it.
75 pub author: Option<OrgName>,
76 pub created_at: SystemTime,
77 pub comments: u64,
78 /// Rendered as pills after the title. By name, like everywhere else labels are
79 /// listed.
80 pub labels: Vec<LabelView>,
81}
82
83/// A repository's issues in one state, plus the counts the toolbar needs for both.
84#[derive(Debug, Clone, PartialEq, Eq)]
85pub struct IssueList {
86 /// Which state was asked for, carried back so a page cannot render the wrong tab as
87 /// current after a bad query string.
88 pub state: IssueState,
89 pub open: u64,
90 pub closed: u64,
91 /// One page of them, newest first, [`ISSUE_LIMIT`] to a page.
92 pub issues: Paged<IssueSummary>,
93 pub viewer_is_owner: bool,
94 /// The label `?label=` asked for, when the repository has one by that name.
95 ///
96 /// `None` both when nothing was asked for and when the name matches no label —
97 /// which is why the counts and the list are empty in the second case rather than
98 /// unfiltered. The page has the raw query value and renders the pill from that, so
99 /// a filter for a label that has been deleted still says what it was filtering on.
100 pub filter: Option<LabelView>,
101}
102
103/// One comment, as a page renders it.
104#[derive(Debug, Clone, PartialEq, Eq)]
105pub struct CommentView {
106 pub author: Option<OrgName>,
107 pub body: String,
108 pub created_at: SystemTime,
109}
110
111/// An issue and its conversation.
112#[derive(Debug, Clone, PartialEq, Eq)]
113pub struct IssueDetail {
114 pub number: IssueNumber,
115 pub title: String,
116 pub body: String,
117 pub state: IssueState,
118 pub author: Option<OrgName>,
119 pub created_at: SystemTime,
120 pub closed_at: Option<SystemTime>,
121 /// Oldest first — a conversation reads forwards.
122 pub comments: Vec<CommentView>,
123 pub viewer_is_owner: bool,
124 /// The labels this issue carries.
125 pub labels: Vec<LabelView>,
126 /// Every label the repository has, for the owner's checkbox list. Empty for anyone
127 /// else — they have no control to fill, and reading them would be a query spent on
128 /// nothing.
129 pub repo_labels: Vec<LabelView>,
130}
131
132// --- Reads --------------------------------------------------------------------------
133
134/// A repository's issues in one state, optionally narrowed to one label.
135///
136/// `Ok(None)` means the repository is not there *or* the viewer may not see it, and the
137/// caller must render both identically — the rule [`view_repo`](super::view_repo) sets.
138///
139/// `filter` is a label **name**, straight off `?label=`. A name the repository has no
140/// label for matches nothing rather than matching everything: silently dropping a
141/// filter it could not resolve would show a list that looks filtered and is not.
142///
143/// **The open and closed counts obey the filter.** A toolbar saying "Open 12" above two
144/// rows is a toolbar you stop reading. Paying for that costs one extra listing — the
145/// other state's — and only when a filter is actually applied.
146#[allow(clippy::too_many_arguments)]
147pub async fn list_issues(
148 actor: &Actor,
149 handle: &OrgName,
150 name: &RepoName,
151 state: IssueState,
152 filter: Option<&str>,
153 page: usize,
154 orgs: &impl OrgRepository,
155 memberships: &impl MembershipRepository,
156 repos: &impl RepoRepository,
157 issues: &impl IssueRepository,
158 users: &impl UserRepository,
159 labels: &impl LabelRepository,
160) -> Result<Option<IssueList>> {
161 let Some((repo, viewer_is_owner)) =
162 readable_repo(actor, handle, name, orgs, memberships, repos).await?
163 else {
164 return Ok(None);
165 };
166
167 // One query for every row's pills rather than one per row.
168 let on_issue = labels_by_issue(&repo, labels).await?;
169
170 let filter = match filter {
171 Some(name) => Some(labels.find_by_name(&repo.id, name).await?),
172 None => None,
173 };
174
175 let mut counts = issues.counts(&repo.id).await?;
176
177 // Two paths, because a label filter is not something SQL can answer here: which
178 // labels an issue wears lives in a second table that is already read whole to
179 // render the pills, so a filtered list is narrowed in memory and paged from there.
180 // Unfiltered, the port pages it — which is the case a repository with a thousand
181 // issues actually spends its time in.
182 let mut listed = match filter.is_some() {
183 true => issues.list_by_repo(&repo.id, state, 0, usize::MAX).await?,
184 false => {
185 let total = state_count(counts, state);
186
187 issues
188 .list_by_repo(
189 &repo.id,
190 state,
191 offset(clamp(page, page_count(total, ISSUE_LIMIT)), ISSUE_LIMIT),
192 ISSUE_LIMIT,
193 )
194 .await?
195 }
196 };
197
198 if let Some(wanted) = &filter {
199 let carries = |issue: &Issue| {
200 wanted.as_ref().is_some_and(|wanted| {
201 on_issue
202 .get(&issue.id)
203 .is_some_and(|labels| labels.iter().any(|label| label.id == wanted.id))
204 })
205 };
206
207 let other = match state {
208 IssueState::Open => IssueState::Closed,
209 IssueState::Closed => IssueState::Open,
210 };
211 let others = issues.list_by_repo(&repo.id, other, 0, usize::MAX).await?;
212
213 listed.retain(&carries);
214 let here = listed.len() as u64;
215 let there = others.iter().filter(|issue| carries(issue)).count() as u64;
216
217 counts = match state {
218 IssueState::Open => IssueCounts {
219 open: here,
220 closed: there,
221 },
222 IssueState::Closed => IssueCounts {
223 open: there,
224 closed: here,
225 },
226 };
227 }
228
229 // The filtered list arrived whole and is cut here; the unfiltered one was cut by
230 // the port and arrives as its own page already.
231 let total = match filter.is_some() {
232 true => listed.len(),
233 false => state_count(counts, state),
234 };
235 let paged = match filter.is_some() {
236 true => Paged::slice(listed, page, ISSUE_LIMIT),
237 false => Paged::of(listed, total, page, ISSUE_LIMIT),
238 };
239
240 // One query for every row's comment count rather than one per row.
241 let comments: HashMap<IssueId, u64> =
242 issues.comment_counts(&repo.id).await?.into_iter().collect();
243
244 let mut handles = Handles::default();
245 let mut summaries = Vec::with_capacity(paged.items.len());
246
247 for issue in paged.items {
248 summaries.push(IssueSummary {
249 number: issue.number,
250 title: issue.title,
251 state: issue.state,
252 author: handles.of(&issue.author_id, orgs, users).await?,
253 created_at: issue.created_at,
254 comments: comments.get(&issue.id).copied().unwrap_or(0),
255 labels: on_issue.get(&issue.id).cloned().unwrap_or_default(),
256 });
257 }
258
259 Ok(Some(IssueList {
260 state,
261 open: counts.open,
262 closed: counts.closed,
263 issues: Paged::of(summaries, paged.total, paged.page, ISSUE_LIMIT),
264 viewer_is_owner,
265 filter: filter.flatten().map(LabelView::from),
266 }))
267}
268
269/// One issue and its comments.
270///
271/// `Ok(None)` covers an invisible repository, a missing repository and a number that
272/// does not exist there. A page 404s on all three, which is what it should do: a
273/// number is guessable, and answering differently for one that exists on a private
274/// repository would count them.
275#[allow(clippy::too_many_arguments)]
276pub async fn view_issue(
277 actor: &Actor,
278 handle: &OrgName,
279 name: &RepoName,
280 number: IssueNumber,
281 orgs: &impl OrgRepository,
282 memberships: &impl MembershipRepository,
283 repos: &impl RepoRepository,
284 issues: &impl IssueRepository,
285 users: &impl UserRepository,
286 labels: &impl LabelRepository,
287) -> Result<Option<IssueDetail>> {
288 let Some((repo, viewer_is_owner)) =
289 readable_repo(actor, handle, name, orgs, memberships, repos).await?
290 else {
291 return Ok(None);
292 };
293
294 let Some(issue) = issues.find_by_number(&repo.id, number).await? else {
295 return Ok(None);
296 };
297
298 let mut handles = Handles::default();
299 let author = handles.of(&issue.author_id, orgs, users).await?;
300
301 let mut comments = Vec::new();
302 for comment in issues.list_comments(&issue.id).await? {
303 comments.push(CommentView {
304 author: handles.of(&comment.author_id, orgs, users).await?,
305 body: comment.body,
306 created_at: comment.created_at,
307 });
308 }
309
310 Ok(Some(IssueDetail {
311 number: issue.number,
312 title: issue.title,
313 body: issue.body,
314 state: issue.state,
315 author,
316 created_at: issue.created_at,
317 closed_at: issue.closed_at,
318 comments,
319 viewer_is_owner,
320 labels: labels
321 .labels_for_issue(&issue.id)
322 .await?
323 .into_iter()
324 .map(LabelView::from)
325 .collect(),
326 // Only the owner has a control to fill, so only the owner pays for the query.
327 repo_labels: if viewer_is_owner {
328 labels
329 .list_by_repo(&repo.id)
330 .await?
331 .into_iter()
332 .map(LabelView::from)
333 .collect()
334 } else {
335 Vec::new()
336 },
337 }))
338}
339
340// --- Writes -------------------------------------------------------------------------
341
342/// Opens an issue. Owner only.
343///
344/// Returns the created issue because the caller has to redirect to its number, and only
345/// the allocation knows what that is.
346///
347/// The number is allocated **before** the issue is validated, so a rejected title burns
348/// one. That is the trade the sequence's atomicity forces — see
349/// [`IssueRepository::next_number`] — and a gap costs nothing next to a reused number.
350#[allow(clippy::too_many_arguments)]
351pub async fn create_issue(
352 actor: &Actor,
353 handle: &OrgName,
354 name: &RepoName,
355 spec: &NewIssue,
356 now: SystemTime,
357 orgs: &impl OrgRepository,
358 memberships: &impl MembershipRepository,
359 repos: &impl RepoRepository,
360 issues: &impl IssueRepository,
361) -> Result<Issue> {
362 let repo = writable_repo(actor, handle, name, orgs, memberships, repos).await?;
363
364 // Present because `writable_repo` already refused an anonymous actor; unwrapping
365 // would still be a panic waiting for the day that changes.
366 let author_id = actor.user_id().ok_or(DomainError::Forbidden)?.clone();
367
368 let number = issues.next_number(&repo.id).await?;
369 let issue = Issue::new(
370 IssueId::generate(),
371 repo.id.clone(),
372 number,
373 spec.title.clone(),
374 spec.body.clone(),
375 author_id,
376 now,
377 )?;
378
379 issues.save(&issue).await?;
380
381 Ok(issue)
382}
383
384/// Adds a comment to an issue. Owner only.
385///
386/// The issue's `updated_at` moves with it: the conversation advanced even though what
387/// the issue says did not.
388#[allow(clippy::too_many_arguments)]
389pub async fn comment_on_issue(
390 actor: &Actor,
391 handle: &OrgName,
392 name: &RepoName,
393 number: IssueNumber,
394 body: &str,
395 now: SystemTime,
396 orgs: &impl OrgRepository,
397 memberships: &impl MembershipRepository,
398 repos: &impl RepoRepository,
399 issues: &impl IssueRepository,
400) -> Result<()> {
401 let repo = writable_repo(actor, handle, name, orgs, memberships, repos).await?;
402 let mut issue = existing_issue(&repo, number, issues).await?;
403 let author_id = actor.user_id().ok_or(DomainError::Forbidden)?.clone();
404
405 let comment = IssueComment::new(
406 IssueCommentId::generate(),
407 issue.id.clone(),
408 author_id,
409 body,
410 now,
411 )?;
412
413 issues.add_comment(&comment).await?;
414
415 issue.touch(now);
416 issues.save(&issue).await?;
417
418 Ok(())
419}
420
421/// Closes or reopens an issue. Owner only.
422///
423/// One use case rather than two, because the two differ only in the state asked for and
424/// splitting them would mean two copies of the same authorization.
425#[allow(clippy::too_many_arguments)]
426pub async fn set_issue_state(
427 actor: &Actor,
428 handle: &OrgName,
429 name: &RepoName,
430 number: IssueNumber,
431 state: IssueState,
432 now: SystemTime,
433 orgs: &impl OrgRepository,
434 memberships: &impl MembershipRepository,
435 repos: &impl RepoRepository,
436 issues: &impl IssueRepository,
437) -> Result<()> {
438 let repo = writable_repo(actor, handle, name, orgs, memberships, repos).await?;
439 let mut issue = existing_issue(&repo, number, issues).await?;
440
441 match state {
442 IssueState::Closed => issue.close(now),
443 IssueState::Open => issue.reopen(now),
444 }
445
446 issues.save(&issue).await?;
447
448 Ok(())
449}
450
451/// Changes an issue's title and body. Owner only.
452#[allow(clippy::too_many_arguments)]
453pub async fn edit_issue(
454 actor: &Actor,
455 handle: &OrgName,
456 name: &RepoName,
457 number: IssueNumber,
458 edit: &IssueEdit,
459 now: SystemTime,
460 orgs: &impl OrgRepository,
461 memberships: &impl MembershipRepository,
462 repos: &impl RepoRepository,
463 issues: &impl IssueRepository,
464) -> Result<()> {
465 let repo = writable_repo(actor, handle, name, orgs, memberships, repos).await?;
466 let mut issue = existing_issue(&repo, number, issues).await?;
467
468 // Validated before anything is written, so a rejected title leaves the issue exactly
469 // as it was.
470 issue.edit(edit.title.clone(), edit.body.clone(), now)?;
471 issues.save(&issue).await?;
472
473 Ok(())
474}
475
476// --- Shared resolution ----------------------------------------------------------------
477
478/// Resolves a repository the actor may read, and whether they own it.
479///
480/// The same rule [`view_repo`](super::view_repo) applies, but returning the stored
481/// [`Repository`] rather than a view — issues hang off its id, which a `RepoView` does
482/// not carry.
483pub(super) async fn readable_repo(
484 actor: &Actor,
485 handle: &OrgName,
486 name: &RepoName,
487 orgs: &impl OrgRepository,
488 memberships: &impl MembershipRepository,
489 repos: &impl RepoRepository,
490) -> Result<Option<(Repository, bool)>> {
491 let Some(org) = orgs.find_by_name(handle).await? else {
492 return Ok(None);
493 };
494
495 let Some(repo) = repos.find_by_org_and_name(&org.id, name).await? else {
496 return Ok(None);
497 };
498
499 if !repo.visibility.is_public() && !is_org_member(&org, actor, memberships).await? {
500 return Ok(None);
501 }
502
503 Ok(Some((repo, is_org_owner(&org, actor, memberships).await?)))
504}
505
506/// Resolves a repository the actor may **write issues on** — the owner, and nobody else.
507///
508/// Not found for a repository they cannot see, forbidden for one they can. A member's
509/// read access is not permission to add to someone's issue tracker, the same way it is
510/// not permission to create a repository.
511pub(super) async fn writable_repo(
512 actor: &Actor,
513 handle: &OrgName,
514 name: &RepoName,
515 orgs: &impl OrgRepository,
516 memberships: &impl MembershipRepository,
517 repos: &impl RepoRepository,
518) -> Result<Repository> {
519 let Some((repo, is_owner)) =
520 readable_repo(actor, handle, name, orgs, memberships, repos).await?
521 else {
522 return Err(Error::Domain(DomainError::NotFound {
523 entity: "repository",
524 }));
525 };
526
527 if !is_owner {
528 return Err(Error::Domain(DomainError::Forbidden));
529 }
530
531 Ok(repo)
532}
533
534/// The issue a write is aimed at, or `NotFound`.
535pub(super) async fn existing_issue(
536 repo: &Repository,
537 number: IssueNumber,
538 issues: &impl IssueRepository,
539) -> Result<Issue> {
540 issues
541 .find_by_number(&repo.id, number)
542 .await?
543 .ok_or(Error::Domain(DomainError::NotFound { entity: "issue" }))
544}
545
546/// Author handles, resolved once each.
547///
548/// A user's handle is their personal organisation's name, which is two lookups away
549/// from a `UserId`. A listing where every issue has the same author — every listing
550/// today — would otherwise pay those two per row.
551#[derive(Debug, Default)]
552pub(crate) struct Handles {
553 known: HashMap<UserId, Option<OrgName>>,
554}
555
556impl Handles {
557 pub(crate) async fn of(
558 &mut self,
559 user_id: &UserId,
560 orgs: &impl OrgRepository,
561 users: &impl UserRepository,
562 ) -> Result<Option<OrgName>> {
563 if let Some(known) = self.known.get(user_id) {
564 return Ok(known.clone());
565 }
566
567 // `None` rather than an error for a user who is gone: an issue outlives the
568 // account that opened it, and a deleted author must not make the page fail.
569 let handle = match users.find_by_id(user_id).await? {
570 Some(user) => orgs
571 .find_by_id(&user.personal_org_id)
572 .await?
573 .map(|org| org.name),
574 None => None,
575 };
576
577 self.known.insert(user_id.clone(), handle.clone());
578
579 Ok(handle)
580 }
581}
582
583#[cfg(test)]
584mod tests {
585 use std::time::Duration;
586
587 use super::*;
588 use crate::{
589 domain::{
590 Email, Membership, MembershipId, OrgId, Organization, PasswordHash, RepoId, Role, User,
591 Visibility,
592 repository::{MembershipRepository, OrgRepository},
593 },
594 infrastructure::repository::{
595 InMemoryIssueRepo, InMemoryLabelRepo, InMemoryMembershipRepo, InMemoryOrgRepo,
596 InMemoryRepoRepo, InMemoryUserRepo,
597 },
598 };
599
600 fn at(seconds: u64) -> SystemTime {
601 SystemTime::UNIX_EPOCH + Duration::from_secs(seconds)
602 }
603
604 struct Fixture {
605 orgs: InMemoryOrgRepo,
606 memberships: InMemoryMembershipRepo,
607 repos: InMemoryRepoRepo,
608 issues: InMemoryIssueRepo,
609 users: InMemoryUserRepo,
610 labels: InMemoryLabelRepo,
611 handle: OrgName,
612 owner: Actor,
613 member: Actor,
614 stranger: Actor,
615 }
616
617 /// One organisation with an owner and a plain member, a public repository `steid`
618 /// and a private one `secret`.
619 async fn fixture() -> Fixture {
620 let orgs = InMemoryOrgRepo::new();
621 let memberships = InMemoryMembershipRepo::new();
622 let repos = InMemoryRepoRepo::new();
623 let users = InMemoryUserRepo::new();
624
625 let org = Organization::new(OrgId::generate(), "acme", None).expect("valid org");
626 orgs.save(&org).await.expect("save org");
627
628 let actor_for = |email: &str, role: Role| {
629 let user = User::new(
630 UserId::generate(),
631 Email::new(email).expect("valid email"),
632 PasswordHash::from_trusted("$argon2id$test"),
633 org.id.clone(),
634 );
635 (user, role)
636 };
637
638 let (owner, _) = actor_for("owner@example.com", Role::Owner);
639 let (member, _) = actor_for("member@example.com", Role::Member);
640
641 for (user, role) in [(&owner, Role::Owner), (&member, Role::Member)] {
642 users.save(user).await.expect("save user");
643 memberships
644 .save(&Membership::new(
645 MembershipId::generate(),
646 org.id.clone(),
647 user.id.clone(),
648 role,
649 ))
650 .await
651 .expect("save membership");
652 }
653
654 for (name, visibility) in [
655 ("steid", Visibility::Public),
656 ("secret", Visibility::Private),
657 ] {
658 repos
659 .save(
660 &Repository::new(
661 RepoId::generate(),
662 org.id.clone(),
663 name,
664 None,
665 visibility,
666 at(1_000),
667 )
668 .expect("valid repo"),
669 )
670 .await
671 .expect("save repo");
672 }
673
674 Fixture {
675 orgs,
676 memberships,
677 repos,
678 issues: InMemoryIssueRepo::new(),
679 users,
680 labels: InMemoryLabelRepo::new(),
681 handle: org.name.clone(),
682 owner: Actor::User(owner.id),
683 member: Actor::User(member.id),
684 stranger: Actor::Anonymous,
685 }
686 }
687
688 fn repo(name: &str) -> RepoName {
689 RepoName::new(name).expect("valid name")
690 }
691
692 /// The id of one of the fixture's repositories, for the ports that take one.
693 async fn repo_id(f: &Fixture, name: &str) -> crate::domain::RepoId {
694 let org = f
695 .orgs
696 .find_by_name(&f.handle)
697 .await
698 .expect("should read")
699 .expect("the org exists");
700
701 f.repos
702 .find_by_org_and_name(&org.id, &repo(name))
703 .await
704 .expect("should read")
705 .expect("the repository exists")
706 .id
707 }
708
709 async fn open(f: &Fixture, name: &str, title: &str) -> Issue {
710 create_issue(
711 &f.owner,
712 &f.handle,
713 &repo(name),
714 &NewIssue {
715 title: title.to_owned(),
716 body: "the body".to_owned(),
717 },
718 at(2_000),
719 &f.orgs,
720 &f.memberships,
721 &f.repos,
722 &f.issues,
723 )
724 .await
725 .expect("should open")
726 }
727
728 async fn listed(
729 f: &Fixture,
730 actor: &Actor,
731 name: &str,
732 state: IssueState,
733 ) -> Option<IssueList> {
734 listed_page(f, actor, name, state, None, 1).await
735 }
736
737 async fn listed_page(
738 f: &Fixture,
739 actor: &Actor,
740 name: &str,
741 state: IssueState,
742 filter: Option<&str>,
743 page: usize,
744 ) -> Option<IssueList> {
745 list_issues(
746 actor,
747 &f.handle,
748 &repo(name),
749 state,
750 filter,
751 page,
752 &f.orgs,
753 &f.memberships,
754 &f.repos,
755 &f.issues,
756 &f.users,
757 &f.labels,
758 )
759 .await
760 .expect("should list")
761 }
762
763 #[tokio::test]
764 async fn the_second_page_of_issues_starts_where_the_first_ended() {
765 let f = fixture().await;
766
767 for n in 1..=(ISSUE_LIMIT + 3) {
768 open(&f, "steid", &format!("issue {n}")).await;
769 }
770
771 let first = listed_page(&f, &f.owner, "steid", IssueState::Open, None, 1)
772 .await
773 .expect("visible");
774 let second = listed_page(&f, &f.owner, "steid", IssueState::Open, None, 2)
775 .await
776 .expect("visible");
777
778 assert_eq!(first.issues.items.len(), ISSUE_LIMIT);
779 assert_eq!(second.issues.items.len(), 3);
780 assert_eq!(second.issues.offset(), ISSUE_LIMIT);
781 assert_eq!(second.issues.total, ISSUE_LIMIT + 3);
782 // Newest first, so the second page carries the three oldest.
783 assert_eq!(second.issues.items[2].title, "issue 1");
784 assert!(
785 !first
786 .issues
787 .items
788 .iter()
789 .any(|issue| issue.number == second.issues.items[0].number),
790 "the pages do not overlap"
791 );
792 }
793
794 #[tokio::test]
795 async fn an_issue_page_past_the_end_clamps() {
796 let f = fixture().await;
797 open(&f, "steid", "the only issue").await;
798
799 let list = listed_page(&f, &f.owner, "steid", IssueState::Open, None, 400)
800 .await
801 .expect("visible");
802
803 assert_eq!(list.issues.page, 1);
804 assert_eq!(list.issues.items.len(), 1);
805 }
806
807 #[tokio::test]
808 async fn a_filtered_list_pages_over_what_the_filter_left() {
809 // The path that cannot be paged in SQL: the filter is applied over the labels
810 // table the list already reads, so the page is cut after it.
811 let f = fixture().await;
812 crate::application::create_label(
813 &f.owner,
814 &f.handle,
815 &repo("steid"),
816 &crate::application::NewLabel {
817 name: "bug".to_owned(),
818 colour: crate::domain::LabelColour::Gray,
819 description: None,
820 },
821 at(1_500),
822 &f.orgs,
823 &f.memberships,
824 &f.repos,
825 &f.labels,
826 )
827 .await
828 .expect("should create");
829
830 let label = f
831 .labels
832 .find_by_name(&repo_id(&f, "steid").await, "bug")
833 .await
834 .expect("should read")
835 .expect("the label exists");
836
837 for n in 1..=(ISSUE_LIMIT + 2) {
838 let issue = open(&f, "steid", &format!("issue {n}")).await;
839
840 // Every other issue wears the label, so the filtered list is genuinely
841 // narrower than the whole and pages differently from it.
842 if n % 2 == 0 {
843 crate::application::set_issue_labels(
844 &f.owner,
845 &f.handle,
846 &repo("steid"),
847 issue.number,
848 std::slice::from_ref(&label.id),
849 &f.orgs,
850 &f.memberships,
851 &f.repos,
852 &f.issues,
853 &f.labels,
854 )
855 .await
856 .expect("should label");
857 }
858 }
859
860 let first = listed_page(&f, &f.owner, "steid", IssueState::Open, Some("bug"), 1)
861 .await
862 .expect("visible");
863 let second = listed_page(&f, &f.owner, "steid", IssueState::Open, Some("bug"), 2)
864 .await
865 .expect("visible");
866
867 assert_eq!(first.issues.total, 26, "half of 52, labelled");
868 assert_eq!(first.issues.items.len(), ISSUE_LIMIT.min(26));
869 assert!(!first.issues.is_paged(), "26 labelled issues fit one page");
870 assert_eq!(second.issues.page, 1, "and page 2 clamps back to it");
871 assert!(
872 first
873 .issues
874 .items
875 .iter()
876 .all(|issue| issue.labels.iter().any(|pill| pill.name == "bug")),
877 "every row on the page carries the filter's label"
878 );
879 }
880
881 async fn detail(f: &Fixture, actor: &Actor, name: &str, number: u64) -> Option<IssueDetail> {
882 view_issue(
883 actor,
884 &f.handle,
885 &repo(name),
886 IssueNumber::from_trusted(number),
887 &f.orgs,
888 &f.memberships,
889 &f.repos,
890 &f.issues,
891 &f.users,
892 &f.labels,
893 )
894 .await
895 .expect("should read")
896 }
897
898 fn is_forbidden(error: &Error) -> bool {
899 matches!(error, Error::Domain(DomainError::Forbidden))
900 }
901
902 fn is_not_found(error: &Error) -> bool {
903 matches!(error, Error::Domain(DomainError::NotFound { .. }))
904 }
905
906 // --- numbering ------------------------------------------------------------------
907
908 #[tokio::test]
909 async fn issues_are_numbered_from_one_per_repository() {
910 // The property the whole sequence exists for: `#1` on two repositories is two
911 // different issues, and neither repository's count affects the other's.
912 let f = fixture().await;
913
914 assert_eq!(open(&f, "steid", "first").await.number.get(), 1);
915 assert_eq!(open(&f, "steid", "second").await.number.get(), 2);
916 assert_eq!(open(&f, "secret", "elsewhere").await.number.get(), 1);
917 assert_eq!(open(&f, "steid", "third").await.number.get(), 3);
918 }
919
920 // --- reading --------------------------------------------------------------------
921
922 #[tokio::test]
923 async fn a_listing_is_newest_first_with_counts_for_both_states() {
924 let f = fixture().await;
925 open(&f, "steid", "first").await;
926 open(&f, "steid", "second").await;
927 set_state(&f, 1, IssueState::Closed).await.expect("close");
928
929 let open_list = listed(&f, &f.owner, "steid", IssueState::Open)
930 .await
931 .expect("visible");
932
933 assert_eq!(
934 open_list
935 .issues
936 .items
937 .iter()
938 .map(|issue| issue.number.get())
939 .collect::<Vec<_>>(),
940 vec![2]
941 );
942 assert_eq!((open_list.open, open_list.closed), (1, 1));
943 assert_eq!(open_list.state, IssueState::Open);
944
945 let closed_list = listed(&f, &f.owner, "steid", IssueState::Closed)
946 .await
947 .expect("visible");
948
949 assert_eq!(
950 closed_list
951 .issues
952 .items
953 .iter()
954 .map(|issue| issue.title.as_str())
955 .collect::<Vec<_>>(),
956 vec!["first"]
957 );
958 }
959
960 #[tokio::test]
961 async fn a_listing_names_the_author_and_counts_the_comments() {
962 let f = fixture().await;
963 open(&f, "steid", "Blame is slow").await;
964 comment(&f, &f.owner, 1, "still slow")
965 .await
966 .expect("comment");
967
968 let list = listed(&f, &f.stranger, "steid", IssueState::Open)
969 .await
970 .expect("visible");
971 let row = list.issues.items.first().expect("one row");
972
973 assert_eq!(row.author.as_ref().map(OrgName::as_str), Some("acme"));
974 assert_eq!(row.comments, 1);
975 assert!(
976 !list.viewer_is_owner,
977 "an anonymous visitor is offered no controls"
978 );
979 }
980
981 #[tokio::test]
982 async fn an_anonymous_visitor_reads_a_public_repositorys_issues() {
983 let f = fixture().await;
984 open(&f, "steid", "Blame is slow").await;
985
986 assert!(
987 listed(&f, &f.stranger, "steid", IssueState::Open)
988 .await
989 .is_some()
990 );
991 assert!(detail(&f, &f.stranger, "steid", 1).await.is_some());
992 }
993
994 #[tokio::test]
995 async fn a_private_repositorys_issues_are_absent_rather_than_refused() {
996 // Absent, not forbidden: a refusal would confirm the repository exists.
997 let f = fixture().await;
998 open(&f, "secret", "Blame is slow").await;
999
1000 assert!(
1001 listed(&f, &f.stranger, "secret", IssueState::Open)
1002 .await
1003 .is_none()
1004 );
1005 assert!(detail(&f, &f.stranger, "secret", 1).await.is_none());
1006 assert!(
1007 listed(&f, &f.member, "secret", IssueState::Open)
1008 .await
1009 .is_some(),
1010 "a member of the organisation may still read them"
1011 );
1012 }
1013
1014 #[tokio::test]
1015 async fn a_number_that_does_not_exist_reads_as_absent() {
1016 let f = fixture().await;
1017 open(&f, "steid", "Blame is slow").await;
1018
1019 assert!(detail(&f, &f.owner, "steid", 2).await.is_none());
1020 assert!(
1021 detail(&f, &f.owner, "steid", 1).await.is_some(),
1022 "the one that does exist still reads"
1023 );
1024 }
1025
1026 #[tokio::test]
1027 async fn an_issue_carries_its_body_and_its_conversation_forwards() {
1028 let f = fixture().await;
1029 open(&f, "steid", "Blame is slow").await;
1030 comment(&f, &f.owner, 1, "first").await.expect("comment");
1031 comment(&f, &f.owner, 1, "second").await.expect("comment");
1032
1033 let issue = detail(&f, &f.owner, "steid", 1).await.expect("visible");
1034
1035 assert_eq!(issue.body, "the body");
1036 assert_eq!(
1037 issue
1038 .comments
1039 .iter()
1040 .map(|comment| comment.body.as_str())
1041 .collect::<Vec<_>>(),
1042 vec!["first", "second"]
1043 );
1044 assert_eq!(
1045 issue.comments[0].author.as_ref().map(OrgName::as_str),
1046 Some("acme")
1047 );
1048 }
1049
1050 // --- writing --------------------------------------------------------------------
1051
1052 async fn set_state(f: &Fixture, number: u64, state: IssueState) -> Result<()> {
1053 set_issue_state(
1054 &f.owner,
1055 &f.handle,
1056 &repo("steid"),
1057 IssueNumber::from_trusted(number),
1058 state,
1059 at(3_000),
1060 &f.orgs,
1061 &f.memberships,
1062 &f.repos,
1063 &f.issues,
1064 )
1065 .await
1066 }
1067
1068 async fn comment(f: &Fixture, actor: &Actor, number: u64, body: &str) -> Result<()> {
1069 comment_on_issue(
1070 actor,
1071 &f.handle,
1072 &repo("steid"),
1073 IssueNumber::from_trusted(number),
1074 body,
1075 at(4_000),
1076 &f.orgs,
1077 &f.memberships,
1078 &f.repos,
1079 &f.issues,
1080 )
1081 .await
1082 }
1083
1084 #[tokio::test]
1085 async fn closing_and_reopening_move_an_issue_between_the_lists() {
1086 let f = fixture().await;
1087 open(&f, "steid", "Blame is slow").await;
1088
1089 set_state(&f, 1, IssueState::Closed).await.expect("close");
1090 let closed = detail(&f, &f.owner, "steid", 1).await.expect("visible");
1091 assert_eq!(closed.state, IssueState::Closed);
1092 assert_eq!(closed.closed_at, Some(at(3_000)));
1093
1094 set_state(&f, 1, IssueState::Open).await.expect("reopen");
1095 let reopened = detail(&f, &f.owner, "steid", 1).await.expect("visible");
1096 assert_eq!(reopened.state, IssueState::Open);
1097 assert_eq!(reopened.closed_at, None);
1098 }
1099
1100 #[tokio::test]
1101 async fn editing_replaces_the_title_and_body() {
1102 let f = fixture().await;
1103 open(&f, "steid", "Blame is slow").await;
1104
1105 edit_issue(
1106 &f.owner,
1107 &f.handle,
1108 &repo("steid"),
1109 IssueNumber::from_trusted(1),
1110 &IssueEdit {
1111 title: "Blame is very slow".to_owned(),
1112 body: "with numbers".to_owned(),
1113 },
1114 at(5_000),
1115 &f.orgs,
1116 &f.memberships,
1117 &f.repos,
1118 &f.issues,
1119 )
1120 .await
1121 .expect("should edit");
1122
1123 let issue = detail(&f, &f.owner, "steid", 1).await.expect("visible");
1124
1125 assert_eq!(issue.title, "Blame is very slow");
1126 assert_eq!(issue.body, "with numbers");
1127 }
1128
1129 #[tokio::test]
1130 async fn an_issue_needs_a_title_and_a_comment_needs_a_body() {
1131 let f = fixture().await;
1132
1133 let error = create_issue(
1134 &f.owner,
1135 &f.handle,
1136 &repo("steid"),
1137 &NewIssue {
1138 title: " ".to_owned(),
1139 body: "body".to_owned(),
1140 },
1141 at(2_000),
1142 &f.orgs,
1143 &f.memberships,
1144 &f.repos,
1145 &f.issues,
1146 )
1147 .await
1148 .expect_err("should refuse");
1149
1150 assert!(matches!(
1151 error,
1152 Error::Domain(DomainError::Validation { .. })
1153 ));
1154 assert!(
1155 listed(&f, &f.owner, "steid", IssueState::Open)
1156 .await
1157 .expect("visible")
1158 .issues
1159 .items
1160 .is_empty()
1161 );
1162
1163 open(&f, "steid", "Blame is slow").await;
1164 assert!(comment(&f, &f.owner, 1, " ").await.is_err());
1165 }
1166
1167 #[tokio::test]
1168 async fn a_write_aimed_at_a_number_that_is_not_there_is_not_found() {
1169 let f = fixture().await;
1170
1171 assert!(is_not_found(
1172 &set_state(&f, 9, IssueState::Closed)
1173 .await
1174 .expect_err("refuse")
1175 ));
1176 assert!(is_not_found(
1177 &comment(&f, &f.owner, 9, "hello").await.expect_err("refuse")
1178 ));
1179 }
1180
1181 // --- authorization --------------------------------------------------------------
1182
1183 #[tokio::test]
1184 async fn only_the_owner_may_open_an_issue() {
1185 // A member's read access is not permission to add to someone's tracker.
1186 let f = fixture().await;
1187
1188 for actor in [&f.member, &f.stranger] {
1189 let error = create_issue(
1190 actor,
1191 &f.handle,
1192 &repo("steid"),
1193 &NewIssue {
1194 title: "not mine".to_owned(),
1195 body: String::new(),
1196 },
1197 at(2_000),
1198 &f.orgs,
1199 &f.memberships,
1200 &f.repos,
1201 &f.issues,
1202 )
1203 .await
1204 .expect_err("should refuse");
1205
1206 assert!(is_forbidden(&error), "{actor:?} should be forbidden");
1207 }
1208
1209 assert!(
1210 listed(&f, &f.owner, "steid", IssueState::Open)
1211 .await
1212 .expect("visible")
1213 .issues
1214 .items
1215 .is_empty()
1216 );
1217 }
1218
1219 #[tokio::test]
1220 async fn only_the_owner_may_comment_close_or_edit() {
1221 let f = fixture().await;
1222 open(&f, "steid", "Blame is slow").await;
1223
1224 for actor in [&f.member, &f.stranger] {
1225 assert!(is_forbidden(
1226 &comment(&f, actor, 1, "hello").await.expect_err("refuse")
1227 ));
1228
1229 let error = set_issue_state(
1230 actor,
1231 &f.handle,
1232 &repo("steid"),
1233 IssueNumber::from_trusted(1),
1234 IssueState::Closed,
1235 at(3_000),
1236 &f.orgs,
1237 &f.memberships,
1238 &f.repos,
1239 &f.issues,
1240 )
1241 .await
1242 .expect_err("should refuse");
1243 assert!(is_forbidden(&error));
1244
1245 let error = edit_issue(
1246 actor,
1247 &f.handle,
1248 &repo("steid"),
1249 IssueNumber::from_trusted(1),
1250 &IssueEdit {
1251 title: "hijacked".to_owned(),
1252 body: String::new(),
1253 },
1254 at(3_000),
1255 &f.orgs,
1256 &f.memberships,
1257 &f.repos,
1258 &f.issues,
1259 )
1260 .await
1261 .expect_err("should refuse");
1262 assert!(is_forbidden(&error));
1263 }
1264
1265 let issue = detail(&f, &f.owner, "steid", 1).await.expect("visible");
1266 assert_eq!(issue.title, "Blame is slow");
1267 assert_eq!(issue.state, IssueState::Open);
1268 assert!(issue.comments.is_empty());
1269 }
1270
1271 #[tokio::test]
1272 async fn a_write_on_an_invisible_repository_is_not_found_rather_than_forbidden() {
1273 // Forbidden would confirm that a private repository by that name exists.
1274 let f = fixture().await;
1275
1276 let error = create_issue(
1277 &f.stranger,
1278 &f.handle,
1279 &repo("secret"),
1280 &NewIssue {
1281 title: "prying".to_owned(),
1282 body: String::new(),
1283 },
1284 at(2_000),
1285 &f.orgs,
1286 &f.memberships,
1287 &f.repos,
1288 &f.issues,
1289 )
1290 .await
1291 .expect_err("should refuse");
1292
1293 assert!(is_not_found(&error));
1294 }
1295
1296 #[tokio::test]
1297 async fn a_repository_that_does_not_exist_answers_the_same_way_throughout() {
1298 let f = fixture().await;
1299
1300 assert!(
1301 listed(&f, &f.owner, "nothing", IssueState::Open)
1302 .await
1303 .is_none()
1304 );
1305 assert!(detail(&f, &f.owner, "nothing", 1).await.is_none());
1306
1307 let error = create_issue(
1308 &f.owner,
1309 &f.handle,
1310 &repo("nothing"),
1311 &NewIssue {
1312 title: "nowhere".to_owned(),
1313 body: String::new(),
1314 },
1315 at(2_000),
1316 &f.orgs,
1317 &f.memberships,
1318 &f.repos,
1319 &f.issues,
1320 )
1321 .await
1322 .expect_err("should refuse");
1323
1324 assert!(is_not_found(&error));
1325 }
1326}