steid

@jamesgill /

1//! In-memory repository implementations.
2//!
3//! These exist so use cases can be tested without a database. Attempt #2 reached 60
4//! tests this way and they stayed fast enough to run on every change.
5
6use std::{
7 collections::{HashMap, HashSet},
8 sync::{Arc, Mutex},
9 time::SystemTime,
10};
11
12use crate::domain::{
13 Email, ImportState, Issue, IssueComment, IssueId, IssueNumber, IssueState, Label, LabelId,
14 Membership, OrgId, OrgName, Organization, PasswordReset, PersonalAccessToken, PullRequest,
15 PullRequestComment, PullRequestId, PullRequestState, PushEvent, PushEventId, RepoId, RepoName,
16 Repository, ResetHash, ResetId, Session, SessionTokenHash, TokenHash, TokenId, User, UserId,
17 Webhook, WebhookDelivery, WebhookId,
18 repository::{
19 IssueCounts, IssueRepository, LabelRepository, MembershipRepository, OrgRepository,
20 PasswordResetRepository, PullRequestCounts, PullRequestRepository, PushEventRepository,
21 RepoRepository, RepositoryResult, SessionRepository, TokenRepository, UserRepository,
22 WebhookDeliveryRepository, WebhookRepository,
23 },
24};
25
26/// Shared, cloneable storage. Cloning shares the same underlying map, so a repository
27/// handed to two use cases sees one set of data.
28#[derive(Debug, Default, Clone)]
29pub struct InMemoryUserRepo {
30 users: Arc<Mutex<HashMap<String, User>>>,
31}
32
33impl InMemoryUserRepo {
34 pub fn new() -> Self {
35 Self::default()
36 }
37}
38
39impl UserRepository for InMemoryUserRepo {
40 async fn find_by_id(&self, id: &UserId) -> RepositoryResult<Option<User>> {
41 let users = self.users.lock().expect("lock poisoned");
42 Ok(users.get(id.as_str()).cloned())
43 }
44
45 async fn find_by_email(&self, email: &Email) -> RepositoryResult<Option<User>> {
46 let users = self.users.lock().expect("lock poisoned");
47 Ok(users.values().find(|user| &user.email == email).cloned())
48 }
49
50 async fn find_by_personal_org(&self, org_id: &OrgId) -> RepositoryResult<Option<User>> {
51 let users = self.users.lock().expect("lock poisoned");
52 Ok(users
53 .values()
54 .find(|user| &user.personal_org_id == org_id)
55 .cloned())
56 }
57
58 async fn save(&self, user: &User) -> RepositoryResult<()> {
59 let mut users = self.users.lock().expect("lock poisoned");
60 users.insert(user.id.as_str().to_owned(), user.clone());
61 Ok(())
62 }
63
64 async fn sole_user(&self) -> RepositoryResult<Option<User>> {
65 let users = self.users.lock().expect("lock poisoned");
66
67 match users.len() {
68 1 => Ok(users.values().next().cloned()),
69 _ => Ok(None),
70 }
71 }
72
73 async fn any_exist(&self) -> RepositoryResult<bool> {
74 let users = self.users.lock().expect("lock poisoned");
75 Ok(!users.is_empty())
76 }
77
78 async fn count(&self) -> RepositoryResult<u64> {
79 let users = self.users.lock().expect("lock poisoned");
80 Ok(users.len() as u64)
81 }
82}
83
84#[derive(Debug, Default, Clone)]
85pub struct InMemoryOrgRepo {
86 orgs: Arc<Mutex<HashMap<String, Organization>>>,
87}
88
89impl InMemoryOrgRepo {
90 pub fn new() -> Self {
91 Self::default()
92 }
93}
94
95impl OrgRepository for InMemoryOrgRepo {
96 async fn find_by_id(&self, id: &OrgId) -> RepositoryResult<Option<Organization>> {
97 let orgs = self.orgs.lock().expect("lock poisoned");
98 Ok(orgs.get(id.as_str()).cloned())
99 }
100
101 async fn find_by_name(&self, name: &OrgName) -> RepositoryResult<Option<Organization>> {
102 let orgs = self.orgs.lock().expect("lock poisoned");
103 Ok(orgs.values().find(|org| &org.name == name).cloned())
104 }
105
106 async fn save(&self, org: &Organization) -> RepositoryResult<()> {
107 let mut orgs = self.orgs.lock().expect("lock poisoned");
108 orgs.insert(org.id.as_str().to_owned(), org.clone());
109 Ok(())
110 }
111
112 async fn count(&self) -> RepositoryResult<u64> {
113 let orgs = self.orgs.lock().expect("lock poisoned");
114 Ok(orgs.len() as u64)
115 }
116}
117
118#[derive(Debug, Default, Clone)]
119pub struct InMemoryMembershipRepo {
120 memberships: Arc<Mutex<HashMap<String, Membership>>>,
121}
122
123impl InMemoryMembershipRepo {
124 pub fn new() -> Self {
125 Self::default()
126 }
127}
128
129impl MembershipRepository for InMemoryMembershipRepo {
130 async fn find(&self, org_id: &OrgId, user_id: &UserId) -> RepositoryResult<Option<Membership>> {
131 let memberships = self.memberships.lock().expect("lock poisoned");
132 Ok(memberships
133 .values()
134 .find(|m| &m.org_id == org_id && &m.user_id == user_id)
135 .cloned())
136 }
137
138 async fn list_for_user(&self, user_id: &UserId) -> RepositoryResult<Vec<Membership>> {
139 let memberships = self.memberships.lock().expect("lock poisoned");
140 Ok(memberships
141 .values()
142 .filter(|m| &m.user_id == user_id)
143 .cloned()
144 .collect())
145 }
146
147 async fn save(&self, membership: &Membership) -> RepositoryResult<()> {
148 let mut memberships = self.memberships.lock().expect("lock poisoned");
149 memberships.insert(membership.id.as_str().to_owned(), membership.clone());
150 Ok(())
151 }
152}
153
154/// Personal access tokens held in memory.
155#[derive(Debug, Default, Clone)]
156pub struct InMemoryTokenRepo {
157 tokens: Arc<Mutex<HashMap<String, PersonalAccessToken>>>,
158}
159
160impl InMemoryTokenRepo {
161 pub fn new() -> Self {
162 Self::default()
163 }
164}
165
166impl TokenRepository for InMemoryTokenRepo {
167 async fn find_by_hash(
168 &self,
169 hash: &TokenHash,
170 ) -> RepositoryResult<Option<PersonalAccessToken>> {
171 let tokens = self.tokens.lock().expect("lock poisoned");
172
173 Ok(tokens
174 .values()
175 .find(|token| token.token_hash.matches(hash))
176 .cloned())
177 }
178
179 async fn list_by_user(&self, user_id: &UserId) -> RepositoryResult<Vec<PersonalAccessToken>> {
180 let tokens = self.tokens.lock().expect("lock poisoned");
181
182 let mut found: Vec<PersonalAccessToken> = tokens
183 .values()
184 .filter(|token| &token.user_id == user_id)
185 .cloned()
186 .collect();
187
188 // Newest first, with the id breaking ties: two tokens issued in the same second
189 // would otherwise come back in whatever order the map happened to hold them.
190 found.sort_by(|a, b| {
191 b.created_at
192 .cmp(&a.created_at)
193 .then_with(|| a.id.as_str().cmp(b.id.as_str()))
194 });
195
196 Ok(found)
197 }
198
199 async fn save(&self, token: &PersonalAccessToken) -> RepositoryResult<()> {
200 let mut tokens = self.tokens.lock().expect("lock poisoned");
201 tokens.insert(token.id.as_str().to_owned(), token.clone());
202 Ok(())
203 }
204
205 async fn touch_last_used(&self, id: &TokenId, at: SystemTime) -> RepositoryResult<()> {
206 let mut tokens = self.tokens.lock().expect("lock poisoned");
207
208 if let Some(token) = tokens.get_mut(id.as_str()) {
209 token.last_used_at = Some(at);
210 }
211
212 Ok(())
213 }
214
215 async fn delete(&self, id: &TokenId) -> RepositoryResult<()> {
216 let mut tokens = self.tokens.lock().expect("lock poisoned");
217 tokens.remove(id.as_str());
218 Ok(())
219 }
220}
221
222/// Issues and their comments.
223///
224/// One struct for both because they are one aggregate and one port. The number sequence
225/// used to live here too; it is the repository's, and moved to [`InMemoryRepoRepo`].
226#[derive(Debug, Default, Clone)]
227pub struct InMemoryIssueRepo {
228 state: Arc<Mutex<IssueStore>>,
229}
230
231/// The maps behind [`InMemoryIssueRepo`], under one lock.
232#[derive(Debug, Default)]
233struct IssueStore {
234 issues: HashMap<String, Issue>,
235 comments: Vec<IssueComment>,
236}
237
238impl InMemoryIssueRepo {
239 pub fn new() -> Self {
240 Self::default()
241 }
242}
243
244impl IssueRepository for InMemoryIssueRepo {
245 async fn find_by_number(
246 &self,
247 repo_id: &RepoId,
248 number: IssueNumber,
249 ) -> RepositoryResult<Option<Issue>> {
250 let state = self.state.lock().expect("lock poisoned");
251
252 Ok(state
253 .issues
254 .values()
255 .find(|issue| &issue.repo_id == repo_id && issue.number == number)
256 .cloned())
257 }
258
259 async fn list_by_repo(
260 &self,
261 repo_id: &RepoId,
262 state: IssueState,
263 offset: usize,
264 limit: usize,
265 ) -> RepositoryResult<Vec<Issue>> {
266 let held = self.state.lock().expect("lock poisoned");
267
268 let mut found: Vec<Issue> = held
269 .issues
270 .values()
271 .filter(|issue| &issue.repo_id == repo_id && issue.state == state)
272 .cloned()
273 .collect();
274
275 // Newest first, which for a monotonic sequence is descending number — the same
276 // order the SQL says, and one that cannot tie.
277 found.sort_by_key(|issue| std::cmp::Reverse(issue.number));
278
279 Ok(found.into_iter().skip(offset).take(limit).collect())
280 }
281
282 async fn counts(&self, repo_id: &RepoId) -> RepositoryResult<IssueCounts> {
283 let state = self.state.lock().expect("lock poisoned");
284 let mut counts = IssueCounts::default();
285
286 for issue in state.issues.values().filter(|i| &i.repo_id == repo_id) {
287 match issue.state {
288 IssueState::Open => counts.open += 1,
289 IssueState::Closed => counts.closed += 1,
290 }
291 }
292
293 Ok(counts)
294 }
295
296 async fn comment_counts(&self, repo_id: &RepoId) -> RepositoryResult<Vec<(IssueId, u64)>> {
297 let state = self.state.lock().expect("lock poisoned");
298
299 Ok(state
300 .issues
301 .values()
302 .filter(|issue| &issue.repo_id == repo_id)
303 .map(|issue| {
304 let total = state
305 .comments
306 .iter()
307 .filter(|comment| comment.issue_id == issue.id)
308 .count() as u64;
309
310 (issue.id.clone(), total)
311 })
312 .collect())
313 }
314
315 async fn save(&self, issue: &Issue) -> RepositoryResult<()> {
316 let mut state = self.state.lock().expect("lock poisoned");
317 state
318 .issues
319 .insert(issue.id.as_str().to_owned(), issue.clone());
320 Ok(())
321 }
322
323 async fn list_comments(&self, issue_id: &IssueId) -> RepositoryResult<Vec<IssueComment>> {
324 let state = self.state.lock().expect("lock poisoned");
325
326 let mut found: Vec<IssueComment> = state
327 .comments
328 .iter()
329 .filter(|comment| &comment.issue_id == issue_id)
330 .cloned()
331 .collect();
332
333 // A stable sort over a vector kept in insertion order, which is what the SQL's
334 // `rowid` tiebreak means: comments posted in the same second read in the order
335 // they were written.
336 found.sort_by_key(|comment| comment.created_at);
337
338 Ok(found)
339 }
340
341 async fn add_comment(&self, comment: &IssueComment) -> RepositoryResult<()> {
342 let mut state = self.state.lock().expect("lock poisoned");
343 state.comments.push(comment.clone());
344 Ok(())
345 }
346}
347
348/// Push events, keyed by id. Ordering is done on read, as in every repo here.
349#[derive(Debug, Default, Clone)]
350pub struct InMemoryPushEventRepo {
351 events: Arc<Mutex<HashMap<String, PushEvent>>>,
352}
353
354impl InMemoryPushEventRepo {
355 pub fn new() -> Self {
356 Self::default()
357 }
358}
359
360impl PushEventRepository for InMemoryPushEventRepo {
361 async fn find(&self, id: &PushEventId) -> RepositoryResult<Option<PushEvent>> {
362 let events = self.events.lock().expect("lock poisoned");
363 Ok(events.get(id.as_str()).cloned())
364 }
365
366 async fn list_by_repo(
367 &self,
368 repo_id: &RepoId,
369 limit: usize,
370 ) -> RepositoryResult<Vec<PushEvent>> {
371 let events = self.events.lock().expect("lock poisoned");
372
373 let mut found: Vec<PushEvent> = events
374 .values()
375 .filter(|event| &event.repo_id == repo_id)
376 .cloned()
377 .collect();
378
379 found.sort_by(|a, b| {
380 b.created_at
381 .cmp(&a.created_at)
382 .then_with(|| a.id.as_str().cmp(b.id.as_str()))
383 });
384 found.truncate(limit);
385
386 Ok(found)
387 }
388
389 async fn list_recent(
390 &self,
391 repo_ids: &[RepoId],
392 limit: usize,
393 ) -> RepositoryResult<Vec<PushEvent>> {
394 let events = self.events.lock().expect("lock poisoned");
395
396 let mut found: Vec<PushEvent> = events
397 .values()
398 .filter(|event| repo_ids.contains(&event.repo_id))
399 .cloned()
400 .collect();
401
402 // The same order `list_by_repo` uses, including the tie-break: a `git push
403 // --all` writes every event in one second, and without the id the order is
404 // whatever the map iterated in.
405 found.sort_by(|a, b| {
406 b.created_at
407 .cmp(&a.created_at)
408 .then_with(|| a.id.as_str().cmp(b.id.as_str()))
409 });
410 found.truncate(limit);
411
412 Ok(found)
413 }
414
415 async fn save(&self, event: &PushEvent) -> RepositoryResult<()> {
416 let mut events = self.events.lock().expect("lock poisoned");
417 events.insert(event.id.as_str().to_owned(), event.clone());
418 Ok(())
419 }
420}
421
422#[derive(Debug, Default, Clone)]
423pub struct InMemoryWebhookRepo {
424 webhooks: Arc<Mutex<HashMap<String, Webhook>>>,
425}
426
427impl InMemoryWebhookRepo {
428 pub fn new() -> Self {
429 Self::default()
430 }
431}
432
433impl WebhookRepository for InMemoryWebhookRepo {
434 async fn find(&self, id: &WebhookId) -> RepositoryResult<Option<Webhook>> {
435 let webhooks = self.webhooks.lock().expect("lock poisoned");
436 Ok(webhooks.get(id.as_str()).cloned())
437 }
438
439 async fn list_by_repo(&self, repo_id: &RepoId) -> RepositoryResult<Vec<Webhook>> {
440 let webhooks = self.webhooks.lock().expect("lock poisoned");
441
442 let mut found: Vec<Webhook> = webhooks
443 .values()
444 .filter(|webhook| &webhook.repo_id == repo_id)
445 .cloned()
446 .collect();
447
448 // Oldest first, matching SQLite: a list that reshuffles when one hook is edited
449 // is worse than one that grows downward.
450 found.sort_by(|a, b| {
451 a.created_at
452 .cmp(&b.created_at)
453 .then_with(|| a.id.as_str().cmp(b.id.as_str()))
454 });
455
456 Ok(found)
457 }
458
459 async fn save(&self, webhook: &Webhook) -> RepositoryResult<()> {
460 let mut webhooks = self.webhooks.lock().expect("lock poisoned");
461 webhooks.insert(webhook.id.as_str().to_owned(), webhook.clone());
462 Ok(())
463 }
464
465 async fn delete(&self, id: &WebhookId) -> RepositoryResult<()> {
466 let mut webhooks = self.webhooks.lock().expect("lock poisoned");
467 webhooks.remove(id.as_str());
468 Ok(())
469 }
470}
471
472#[derive(Debug, Default, Clone)]
473pub struct InMemoryWebhookDeliveryRepo {
474 deliveries: Arc<Mutex<HashMap<String, WebhookDelivery>>>,
475}
476
477impl InMemoryWebhookDeliveryRepo {
478 pub fn new() -> Self {
479 Self::default()
480 }
481
482 fn sorted(&self, webhook_id: &WebhookId) -> Vec<WebhookDelivery> {
483 let deliveries = self.deliveries.lock().expect("lock poisoned");
484
485 let mut found: Vec<WebhookDelivery> = deliveries
486 .values()
487 .filter(|delivery| &delivery.webhook_id == webhook_id)
488 .cloned()
489 .collect();
490
491 found.sort_by(|a, b| {
492 b.delivered_at
493 .cmp(&a.delivered_at)
494 .then_with(|| b.attempt.cmp(&a.attempt))
495 });
496
497 found
498 }
499}
500
501impl WebhookDeliveryRepository for InMemoryWebhookDeliveryRepo {
502 async fn list_by_webhook(
503 &self,
504 webhook_id: &WebhookId,
505 offset: usize,
506 limit: usize,
507 ) -> RepositoryResult<Vec<WebhookDelivery>> {
508 Ok(self
509 .sorted(webhook_id)
510 .into_iter()
511 .skip(offset)
512 .take(limit)
513 .collect())
514 }
515
516 async fn count_by_webhook(&self, webhook_id: &WebhookId) -> RepositoryResult<usize> {
517 Ok(self.sorted(webhook_id).len())
518 }
519
520 async fn latest_by_webhook(
521 &self,
522 webhook_id: &WebhookId,
523 ) -> RepositoryResult<Option<WebhookDelivery>> {
524 Ok(self.sorted(webhook_id).into_iter().next())
525 }
526
527 async fn save(&self, delivery: &WebhookDelivery) -> RepositoryResult<()> {
528 let mut deliveries = self.deliveries.lock().expect("lock poisoned");
529 deliveries.insert(delivery.id.as_str().to_owned(), delivery.clone());
530 Ok(())
531 }
532}
533
534/// Labels and the issues carrying them.
535///
536/// One struct for both because they are one port — and because replacing an issue's set
537/// has to be atomic against a concurrent read, which is only true here if the
538/// assignments sit behind the same lock as the labels themselves.
539#[derive(Debug, Default, Clone)]
540pub struct InMemoryLabelRepo {
541 state: Arc<Mutex<LabelStore>>,
542}
543
544/// The maps behind [`InMemoryLabelRepo`], under one lock.
545#[derive(Debug, Default)]
546struct LabelStore {
547 labels: HashMap<String, Label>,
548 /// `(issue_id, label_id)` pairs — the join table, kept as a set for the same reason
549 /// the SQL makes the pair the primary key.
550 assigned: HashSet<(String, String)>,
551 /// `(pull_request_id, label_id)` pairs. A second set rather than a `kind` column,
552 /// mirroring the two tables — see `pull_request_labels`.
553 assigned_pulls: HashSet<(String, String)>,
554}
555
556impl InMemoryLabelRepo {
557 pub fn new() -> Self {
558 Self::default()
559 }
560}
561
562/// Sorted by name, which is what both implementations promise.
563fn by_name(mut labels: Vec<Label>) -> Vec<Label> {
564 labels.sort_by(|left, right| left.name.cmp(&right.name));
565 labels
566}
567
568impl LabelRepository for InMemoryLabelRepo {
569 async fn list_by_repo(&self, repo_id: &RepoId) -> RepositoryResult<Vec<Label>> {
570 let state = self.state.lock().expect("lock poisoned");
571
572 Ok(by_name(
573 state
574 .labels
575 .values()
576 .filter(|label| &label.repo_id == repo_id)
577 .cloned()
578 .collect(),
579 ))
580 }
581
582 async fn find_by_id(&self, id: &LabelId) -> RepositoryResult<Option<Label>> {
583 let state = self.state.lock().expect("lock poisoned");
584 Ok(state.labels.get(id.as_str()).cloned())
585 }
586
587 async fn find_by_name(&self, repo_id: &RepoId, name: &str) -> RepositoryResult<Option<Label>> {
588 let state = self.state.lock().expect("lock poisoned");
589
590 Ok(state
591 .labels
592 .values()
593 .find(|label| &label.repo_id == repo_id && label.name == name)
594 .cloned())
595 }
596
597 async fn save(&self, label: &Label) -> RepositoryResult<()> {
598 let mut state = self.state.lock().expect("lock poisoned");
599 state
600 .labels
601 .insert(label.id.as_str().to_owned(), label.clone());
602 Ok(())
603 }
604
605 async fn delete(&self, id: &LabelId) -> RepositoryResult<()> {
606 let mut state = self.state.lock().expect("lock poisoned");
607
608 state.labels.remove(id.as_str());
609 // What `on delete cascade` on the join tables does: the issues and the pull
610 // requests stay, they stop wearing this.
611 state.assigned.retain(|(_, label)| label != id.as_str());
612 state
613 .assigned_pulls
614 .retain(|(_, label)| label != id.as_str());
615
616 Ok(())
617 }
618
619 async fn labels_for_issue(&self, issue_id: &IssueId) -> RepositoryResult<Vec<Label>> {
620 let state = self.state.lock().expect("lock poisoned");
621
622 Ok(by_name(
623 state
624 .assigned
625 .iter()
626 .filter(|(issue, _)| issue == issue_id.as_str())
627 .filter_map(|(_, label)| state.labels.get(label).cloned())
628 .collect(),
629 ))
630 }
631
632 async fn labels_for_repo(&self, repo_id: &RepoId) -> RepositoryResult<Vec<(IssueId, Label)>> {
633 let state = self.state.lock().expect("lock poisoned");
634
635 let mut pairs: Vec<(IssueId, Label)> = state
636 .assigned
637 .iter()
638 .filter_map(|(issue, label)| {
639 let label = state.labels.get(label)?;
640
641 (&label.repo_id == repo_id)
642 .then(|| (IssueId::from_trusted(issue.clone()), label.clone()))
643 })
644 .collect();
645
646 // Grouped by issue and by name within it, so a caller building a per-issue map
647 // gets each row's pills in the same order the issue page shows them.
648 pairs.sort_by(|left, right| {
649 left.0
650 .cmp(&right.0)
651 .then_with(|| left.1.name.cmp(&right.1.name))
652 });
653
654 Ok(pairs)
655 }
656
657 async fn issue_counts(&self, repo_id: &RepoId) -> RepositoryResult<Vec<(LabelId, u64)>> {
658 let state = self.state.lock().expect("lock poisoned");
659
660 Ok(state
661 .labels
662 .values()
663 .filter(|label| &label.repo_id == repo_id)
664 .map(|label| {
665 let total = state
666 .assigned
667 .iter()
668 .filter(|(_, assigned)| assigned == label.id.as_str())
669 .count() as u64;
670
671 (label.id.clone(), total)
672 })
673 .collect())
674 }
675
676 async fn set_issue_labels(
677 &self,
678 issue_id: &IssueId,
679 labels: &[LabelId],
680 ) -> RepositoryResult<()> {
681 let mut state = self.state.lock().expect("lock poisoned");
682
683 state
684 .assigned
685 .retain(|(issue, _)| issue != issue_id.as_str());
686
687 for label in labels {
688 state
689 .assigned
690 .insert((issue_id.as_str().to_owned(), label.as_str().to_owned()));
691 }
692
693 Ok(())
694 }
695
696 async fn labels_for_pull(&self, pull_id: &PullRequestId) -> RepositoryResult<Vec<Label>> {
697 let state = self.state.lock().expect("lock poisoned");
698
699 Ok(by_name(
700 state
701 .assigned_pulls
702 .iter()
703 .filter(|(pull, _)| pull == pull_id.as_str())
704 .filter_map(|(_, label)| state.labels.get(label).cloned())
705 .collect(),
706 ))
707 }
708
709 async fn labels_for_repo_pulls(
710 &self,
711 repo_id: &RepoId,
712 ) -> RepositoryResult<Vec<(PullRequestId, Label)>> {
713 let state = self.state.lock().expect("lock poisoned");
714
715 let mut pairs: Vec<(PullRequestId, Label)> = state
716 .assigned_pulls
717 .iter()
718 .filter_map(|(pull, label)| {
719 let label = state.labels.get(label)?;
720
721 (&label.repo_id == repo_id)
722 .then(|| (PullRequestId::from_trusted(pull.clone()), label.clone()))
723 })
724 .collect();
725
726 pairs.sort_by(|left, right| {
727 left.0
728 .cmp(&right.0)
729 .then_with(|| left.1.name.cmp(&right.1.name))
730 });
731
732 Ok(pairs)
733 }
734
735 async fn pull_counts(&self, repo_id: &RepoId) -> RepositoryResult<Vec<(LabelId, u64)>> {
736 let state = self.state.lock().expect("lock poisoned");
737
738 Ok(state
739 .labels
740 .values()
741 .filter(|label| &label.repo_id == repo_id)
742 .map(|label| {
743 let total = state
744 .assigned_pulls
745 .iter()
746 .filter(|(_, assigned)| assigned == label.id.as_str())
747 .count() as u64;
748
749 (label.id.clone(), total)
750 })
751 .collect())
752 }
753
754 async fn set_pull_labels(
755 &self,
756 pull_id: &PullRequestId,
757 labels: &[LabelId],
758 ) -> RepositoryResult<()> {
759 let mut state = self.state.lock().expect("lock poisoned");
760
761 state
762 .assigned_pulls
763 .retain(|(pull, _)| pull != pull_id.as_str());
764
765 for label in labels {
766 state
767 .assigned_pulls
768 .insert((pull_id.as_str().to_owned(), label.as_str().to_owned()));
769 }
770
771 Ok(())
772 }
773}
774
775/// Pull requests and their comments, under one lock — the shape
776/// [`InMemoryIssueRepo`] has, and for the same reason: the two are read together often
777/// enough that two locks would only be two chances to take them in the wrong order.
778///
779/// **No sequence here.** Numbers come from [`InMemoryRepoRepo::next_number`], which is
780/// the repository's one allocator, shared with issues.
781#[derive(Debug, Default, Clone)]
782pub struct InMemoryPullRequestRepo {
783 state: Arc<Mutex<PullRequestStore>>,
784}
785
786#[derive(Debug, Default)]
787struct PullRequestStore {
788 pulls: HashMap<String, PullRequest>,
789 comments: Vec<PullRequestComment>,
790}
791
792impl InMemoryPullRequestRepo {
793 pub fn new() -> Self {
794 Self::default()
795 }
796}
797
798impl PullRequestRepository for InMemoryPullRequestRepo {
799 async fn find_by_number(
800 &self,
801 repo_id: &RepoId,
802 number: IssueNumber,
803 ) -> RepositoryResult<Option<PullRequest>> {
804 let state = self.state.lock().expect("lock poisoned");
805
806 Ok(state
807 .pulls
808 .values()
809 .find(|pull| &pull.repo_id == repo_id && pull.number == number)
810 .cloned())
811 }
812
813 async fn list_by_repo(
814 &self,
815 repo_id: &RepoId,
816 state: PullRequestState,
817 offset: usize,
818 limit: usize,
819 ) -> RepositoryResult<Vec<PullRequest>> {
820 let held = self.state.lock().expect("lock poisoned");
821
822 let mut found: Vec<PullRequest> = held
823 .pulls
824 .values()
825 .filter(|pull| &pull.repo_id == repo_id && pull.state == state)
826 .cloned()
827 .collect();
828
829 // Newest first, which for a monotonic sequence is descending number — the same
830 // order the SQL says, and one that cannot tie.
831 found.sort_by_key(|pull| std::cmp::Reverse(pull.number));
832
833 Ok(found.into_iter().skip(offset).take(limit).collect())
834 }
835
836 async fn counts(&self, repo_id: &RepoId) -> RepositoryResult<PullRequestCounts> {
837 let state = self.state.lock().expect("lock poisoned");
838 let mut counts = PullRequestCounts::default();
839
840 for pull in state.pulls.values().filter(|p| &p.repo_id == repo_id) {
841 match pull.state {
842 PullRequestState::Open => counts.open += 1,
843 PullRequestState::Merged => counts.merged += 1,
844 PullRequestState::Closed => counts.closed += 1,
845 }
846 }
847
848 Ok(counts)
849 }
850
851 async fn comment_counts(
852 &self,
853 repo_id: &RepoId,
854 ) -> RepositoryResult<Vec<(PullRequestId, u64)>> {
855 let state = self.state.lock().expect("lock poisoned");
856
857 Ok(state
858 .pulls
859 .values()
860 .filter(|pull| &pull.repo_id == repo_id)
861 .map(|pull| {
862 let total = state
863 .comments
864 .iter()
865 .filter(|comment| comment.pull_request_id == pull.id)
866 .count() as u64;
867
868 (pull.id.clone(), total)
869 })
870 .collect())
871 }
872
873 async fn save(&self, pull: &PullRequest) -> RepositoryResult<()> {
874 let mut state = self.state.lock().expect("lock poisoned");
875 state
876 .pulls
877 .insert(pull.id.as_str().to_owned(), pull.clone());
878 Ok(())
879 }
880
881 async fn list_comments(
882 &self,
883 pull_request_id: &PullRequestId,
884 ) -> RepositoryResult<Vec<PullRequestComment>> {
885 let state = self.state.lock().expect("lock poisoned");
886
887 let mut found: Vec<PullRequestComment> = state
888 .comments
889 .iter()
890 .filter(|comment| &comment.pull_request_id == pull_request_id)
891 .cloned()
892 .collect();
893
894 // A stable sort over a vector kept in insertion order, which is what the SQL's
895 // `rowid` tiebreak means.
896 found.sort_by_key(|comment| comment.created_at);
897
898 Ok(found)
899 }
900
901 async fn add_comment(&self, comment: &PullRequestComment) -> RepositoryResult<()> {
902 let mut state = self.state.lock().expect("lock poisoned");
903 state.comments.push(comment.clone());
904 Ok(())
905 }
906}
907
908#[cfg(test)]
909mod tests {
910 use std::time::Duration;
911
912 use super::*;
913
914 fn at(seconds: u64) -> SystemTime {
915 SystemTime::UNIX_EPOCH + Duration::from_secs(seconds)
916 }
917 use crate::domain::{IssueCommentId, MembershipId, PasswordHash, Role};
918
919 fn user(email: &str, org_id: &OrgId) -> User {
920 User::new(
921 UserId::generate(),
922 Email::new(email).expect("valid email"),
923 PasswordHash::from_trusted("$argon2id$test"),
924 org_id.clone(),
925 )
926 }
927
928 #[tokio::test]
929 async fn in_memory_the_second_page_of_deliveries_starts_where_the_first_ended() {
930 use crate::domain::{PushEventId, WebhookDelivery, WebhookDeliveryId, WebhookId};
931
932 let deliveries = InMemoryWebhookDeliveryRepo::new();
933 let hook = WebhookId::generate();
934 let event = PushEventId::generate();
935
936 for attempt in 1..=4u32 {
937 deliveries
938 .save(&WebhookDelivery::record(
939 WebhookDeliveryId::generate(),
940 hook.clone(),
941 event.clone(),
942 attempt,
943 Some(200),
944 "ok",
945 12,
946 at(1_000 + u64::from(attempt)),
947 ))
948 .await
949 .expect("save");
950 }
951
952 let first = deliveries.list_by_webhook(&hook, 0, 2).await.expect("list");
953 let second = deliveries.list_by_webhook(&hook, 2, 2).await.expect("list");
954
955 // Newest first, so the attempts count down across the pages.
956 assert_eq!(
957 first.iter().map(|d| d.attempt).collect::<Vec<_>>(),
958 vec![4, 3]
959 );
960 assert_eq!(
961 second.iter().map(|d| d.attempt).collect::<Vec<_>>(),
962 vec![2, 1]
963 );
964 assert_eq!(deliveries.count_by_webhook(&hook).await.expect("count"), 4);
965 assert!(
966 deliveries
967 .list_by_webhook(&hook, 500, 2)
968 .await
969 .expect("list")
970 .is_empty(),
971 "an offset past the end is an empty page"
972 );
973 }
974
975 #[tokio::test]
976 async fn users_are_found_by_id_and_email() {
977 let repo = InMemoryUserRepo::new();
978 let org_id = OrgId::generate();
979 let user = user("dev@example.com", &org_id);
980 repo.save(&user).await.expect("save");
981
982 let by_id = repo.find_by_id(&user.id).await.expect("lookup");
983 let by_email = repo.find_by_email(&user.email).await.expect("lookup");
984
985 assert_eq!(by_id.as_ref(), Some(&user));
986 assert_eq!(by_email.as_ref(), Some(&user));
987 }
988
989 #[tokio::test]
990 async fn missing_users_are_none_not_an_error() {
991 let repo = InMemoryUserRepo::new();
992
993 let found = repo.find_by_id(&UserId::generate()).await.expect("lookup");
994
995 assert_eq!(found, None);
996 }
997
998 #[tokio::test]
999 async fn saving_the_same_id_replaces_rather_than_duplicates() {
1000 let repo = InMemoryUserRepo::new();
1001 let org_id = OrgId::generate();
1002 let mut user = user("dev@example.com", &org_id);
1003 repo.save(&user).await.expect("save");
1004
1005 user.email = Email::new("changed@example.com").expect("valid email");
1006 repo.save(&user).await.expect("save");
1007
1008 assert_eq!(
1009 repo.find_by_email(&Email::new("dev@example.com").unwrap())
1010 .await
1011 .expect("lookup"),
1012 None
1013 );
1014 assert!(repo.any_exist().await.expect("any_exist"));
1015 }
1016
1017 #[tokio::test]
1018 async fn any_exist_reports_emptiness() {
1019 let repo = InMemoryUserRepo::new();
1020 assert!(!repo.any_exist().await.expect("any_exist"));
1021
1022 repo.save(&user("dev@example.com", &OrgId::generate()))
1023 .await
1024 .expect("save");
1025
1026 assert!(repo.any_exist().await.expect("any_exist"));
1027 }
1028
1029 #[tokio::test]
1030 async fn clones_share_storage() {
1031 let repo = InMemoryUserRepo::new();
1032 let clone = repo.clone();
1033
1034 clone
1035 .save(&user("dev@example.com", &OrgId::generate()))
1036 .await
1037 .expect("save");
1038
1039 assert!(repo.any_exist().await.expect("any_exist"));
1040 }
1041
1042 #[tokio::test]
1043 async fn orgs_are_found_by_id_and_name() {
1044 let repo = InMemoryOrgRepo::new();
1045 let org = Organization::new(OrgId::generate(), "acme", None).expect("valid org");
1046 repo.save(&org).await.expect("save");
1047
1048 assert_eq!(
1049 repo.find_by_id(&org.id).await.expect("lookup").as_ref(),
1050 Some(&org)
1051 );
1052 assert_eq!(
1053 repo.find_by_name(&org.name).await.expect("lookup").as_ref(),
1054 Some(&org)
1055 );
1056 }
1057
1058 #[tokio::test]
1059 async fn org_lookup_by_name_respects_normalisation() {
1060 let repo = InMemoryOrgRepo::new();
1061 let org = Organization::new(OrgId::generate(), "Acme", None).expect("valid org");
1062 repo.save(&org).await.expect("save");
1063
1064 let found = repo
1065 .find_by_name(&OrgName::new("ACME").expect("valid"))
1066 .await
1067 .expect("lookup");
1068
1069 assert_eq!(found.as_ref(), Some(&org));
1070 }
1071
1072 #[tokio::test]
1073 async fn memberships_are_found_by_org_and_user() {
1074 let repo = InMemoryMembershipRepo::new();
1075 let org_id = OrgId::generate();
1076 let user_id = UserId::generate();
1077 let membership = Membership::new(
1078 MembershipId::generate(),
1079 org_id.clone(),
1080 user_id.clone(),
1081 Role::Owner,
1082 );
1083 repo.save(&membership).await.expect("save");
1084
1085 let found = repo.find(&org_id, &user_id).await.expect("lookup");
1086
1087 assert_eq!(found.as_ref(), Some(&membership));
1088 }
1089
1090 #[tokio::test]
1091 async fn membership_lookup_does_not_match_a_different_user() {
1092 let repo = InMemoryMembershipRepo::new();
1093 let org_id = OrgId::generate();
1094 repo.save(&Membership::new(
1095 MembershipId::generate(),
1096 org_id.clone(),
1097 UserId::generate(),
1098 Role::Owner,
1099 ))
1100 .await
1101 .expect("save");
1102
1103 let found = repo
1104 .find(&org_id, &UserId::generate())
1105 .await
1106 .expect("lookup");
1107
1108 assert_eq!(found, None);
1109 }
1110
1111 #[tokio::test]
1112 async fn list_for_user_returns_only_that_users_memberships() {
1113 let repo = InMemoryMembershipRepo::new();
1114 let user_id = UserId::generate();
1115 for _ in 0..2 {
1116 repo.save(&Membership::new(
1117 MembershipId::generate(),
1118 OrgId::generate(),
1119 user_id.clone(),
1120 Role::Member,
1121 ))
1122 .await
1123 .expect("save");
1124 }
1125 repo.save(&Membership::new(
1126 MembershipId::generate(),
1127 OrgId::generate(),
1128 UserId::generate(),
1129 Role::Owner,
1130 ))
1131 .await
1132 .expect("save");
1133
1134 let found = repo.list_for_user(&user_id).await.expect("lookup");
1135
1136 assert_eq!(found.len(), 2);
1137 assert!(found.iter().all(|m| m.user_id == user_id));
1138 }
1139 // --- InMemoryTokenRepo -------------------------------------------------------
1140
1141 use crate::domain::{TokenLifetime, TokenSecret};
1142
1143 fn token_for(user: &UserId, name: &str, at: u64) -> (PersonalAccessToken, TokenSecret) {
1144 use std::time::Duration;
1145
1146 let secret = TokenSecret::generate();
1147 let token = PersonalAccessToken::new(
1148 TokenId::generate(),
1149 user.clone(),
1150 name,
1151 &secret,
1152 SystemTime::UNIX_EPOCH + Duration::from_secs(at),
1153 TokenLifetime::default(),
1154 )
1155 .expect("valid token");
1156
1157 (token, secret)
1158 }
1159
1160 #[tokio::test]
1161 async fn the_fake_finds_a_token_by_its_hash() {
1162 let tokens = InMemoryTokenRepo::new();
1163 let user = UserId::generate();
1164 let (token, secret) = token_for(&user, "laptop", 1_000);
1165 tokens.save(&token).await.expect("save");
1166
1167 assert_eq!(
1168 tokens.find_by_hash(&secret.hash()).await.expect("lookup"),
1169 Some(token)
1170 );
1171 assert_eq!(
1172 tokens
1173 .find_by_hash(&TokenSecret::generate().hash())
1174 .await
1175 .expect("lookup"),
1176 None
1177 );
1178 }
1179
1180 #[tokio::test]
1181 async fn the_fake_lists_newest_first_for_one_user_only() {
1182 // Mirrors the SQLite ordering. A fake that lists in a different order lets a use
1183 // case pass here and surprise someone in production.
1184 let tokens = InMemoryTokenRepo::new();
1185 let user = UserId::generate();
1186 let other = UserId::generate();
1187
1188 for (owner, name, at) in [
1189 (&user, "old", 1_000),
1190 (&user, "new", 3_000),
1191 (&user, "middle", 2_000),
1192 (&other, "theirs", 4_000),
1193 ] {
1194 let (token, _) = token_for(owner, name, at);
1195 tokens.save(&token).await.expect("save");
1196 }
1197
1198 assert_eq!(
1199 tokens
1200 .list_by_user(&user)
1201 .await
1202 .expect("list")
1203 .iter()
1204 .map(|token| token.name.as_str())
1205 .collect::<Vec<_>>(),
1206 vec!["new", "middle", "old"]
1207 );
1208 }
1209
1210 #[tokio::test]
1211 async fn the_fake_records_a_last_use_on_the_right_token() {
1212 let tokens = InMemoryTokenRepo::new();
1213 let user = UserId::generate();
1214 let (mine, mine_secret) = token_for(&user, "mine", 1_000);
1215 let (untouched, untouched_secret) = token_for(&user, "untouched", 1_000);
1216 tokens.save(&mine).await.expect("save");
1217 tokens.save(&untouched).await.expect("save");
1218
1219 tokens
1220 .touch_last_used(&mine.id, at(2_000))
1221 .await
1222 .expect("touch");
1223
1224 let stored = |secret: TokenSecret| {
1225 let tokens = tokens.clone();
1226 async move {
1227 tokens
1228 .find_by_hash(&secret.hash())
1229 .await
1230 .expect("lookup")
1231 .expect("present")
1232 }
1233 };
1234
1235 assert_eq!(stored(mine_secret).await.last_used_at, Some(at(2_000)));
1236 assert_eq!(stored(untouched_secret).await.last_used_at, None);
1237 }
1238
1239 #[tokio::test]
1240 async fn recording_a_use_of_a_token_that_is_not_there_succeeds() {
1241 // Revoked between the lookup and the write. Failing here would fail a clone
1242 // over a display timestamp.
1243 let tokens = InMemoryTokenRepo::new();
1244
1245 assert!(
1246 tokens
1247 .touch_last_used(&TokenId::generate(), at(1_000))
1248 .await
1249 .is_ok()
1250 );
1251 }
1252
1253 // --- InMemoryRepoRepo --------------------------------------------------------
1254
1255 #[tokio::test]
1256 async fn the_fake_forgets_a_deleted_repository() {
1257 let repos = InMemoryRepoRepo::new();
1258 let org_id = OrgId::generate();
1259 let repo = Repository::new(
1260 RepoId::generate(),
1261 org_id.clone(),
1262 "steid",
1263 None,
1264 crate::domain::Visibility::Public,
1265 at(1_000),
1266 )
1267 .expect("valid repo");
1268 repos.save(&repo).await.expect("save");
1269
1270 repos.delete(&repo.id).await.expect("delete");
1271
1272 assert_eq!(repos.find_by_id(&repo.id).await.expect("lookup"), None);
1273 assert!(
1274 repos
1275 .find_by_org_and_name(&org_id, &repo.name)
1276 .await
1277 .expect("lookup")
1278 .is_none(),
1279 "the name should be free again"
1280 );
1281 assert!(repos.list_by_org(&org_id).await.expect("list").is_empty());
1282 }
1283
1284 #[tokio::test]
1285 async fn deleting_a_repository_that_is_not_there_succeeds() {
1286 // Idempotent: a second click on a delete button must not become an error.
1287 let repos = InMemoryRepoRepo::new();
1288
1289 assert!(repos.delete(&RepoId::generate()).await.is_ok());
1290 }
1291
1292 #[tokio::test]
1293 async fn deleting_one_repository_leaves_the_others() {
1294 let repos = InMemoryRepoRepo::new();
1295 let org_id = OrgId::generate();
1296 let mut saved = Vec::new();
1297 for name in ["alpha", "zebra"] {
1298 let repo = Repository::new(
1299 RepoId::generate(),
1300 org_id.clone(),
1301 name,
1302 None,
1303 crate::domain::Visibility::Public,
1304 at(1_000),
1305 )
1306 .expect("valid repo");
1307 repos.save(&repo).await.expect("save");
1308 saved.push(repo);
1309 }
1310
1311 repos.delete(&saved[0].id).await.expect("delete");
1312
1313 let listed = repos.list_by_org(&org_id).await.expect("list");
1314 assert_eq!(
1315 listed.iter().map(|r| r.name.as_str()).collect::<Vec<_>>(),
1316 vec!["zebra"]
1317 );
1318 }
1319
1320 #[tokio::test]
1321 async fn the_fake_lists_newest_first_breaking_ties_by_name() {
1322 // The order the profile renders. It must match `SqliteRepoRepo::list_by_org`
1323 // exactly — a fake that sorted differently would let a use case pass here and
1324 // surprise someone in production.
1325 let repos = InMemoryRepoRepo::new();
1326 let org_id = OrgId::generate();
1327 for (name, seconds) in [
1328 ("alpha", 3_000),
1329 ("older", 1_000),
1330 ("newer", 2_000),
1331 ("also-older", 1_000),
1332 ] {
1333 repos
1334 .save(&repo_at(&org_id, name, seconds))
1335 .await
1336 .expect("save");
1337 }
1338
1339 let listed = repos.list_by_org(&org_id).await.expect("list");
1340
1341 assert_eq!(
1342 listed.iter().map(|r| r.name.as_str()).collect::<Vec<_>>(),
1343 vec!["alpha", "newer", "also-older", "older"]
1344 );
1345 }
1346
1347 #[tokio::test]
1348 async fn touching_moves_a_repository_to_the_supplied_time() {
1349 let repos = InMemoryRepoRepo::new();
1350 let org_id = OrgId::generate();
1351 let repo = repo_at(&org_id, "steid", 1_000);
1352 repos.save(&repo).await.expect("save");
1353
1354 repos.touch(&repo.id, at(5_000)).await.expect("touch");
1355
1356 let found = repos
1357 .find_by_id(&repo.id)
1358 .await
1359 .expect("lookup")
1360 .expect("still there");
1361 assert_eq!(found.updated_at, at(5_000));
1362 }
1363
1364 #[tokio::test]
1365 async fn touching_a_repository_that_is_gone_succeeds() {
1366 // A push can outlive a delete; there is nothing useful the caller could do.
1367 let repos = InMemoryRepoRepo::new();
1368
1369 assert!(repos.touch(&RepoId::generate(), at(5_000)).await.is_ok());
1370 }
1371
1372 #[tokio::test]
1373 async fn the_fake_remembers_whether_a_repository_is_pinned() {
1374 let repos = InMemoryRepoRepo::new();
1375 let org_id = OrgId::generate();
1376 let mut repo = repo_at(&org_id, "steid", 1_000);
1377 repo.pinned = true;
1378
1379 repos.save(&repo).await.expect("save");
1380
1381 assert!(
1382 repos
1383 .find_by_id(&repo.id)
1384 .await
1385 .expect("lookup")
1386 .expect("still there")
1387 .pinned
1388 );
1389 }
1390
1391 fn repo_at(org_id: &OrgId, name: &str, seconds: u64) -> Repository {
1392 Repository::new(
1393 RepoId::generate(),
1394 org_id.clone(),
1395 name,
1396 None,
1397 crate::domain::Visibility::Public,
1398 at(seconds),
1399 )
1400 .expect("valid repo")
1401 }
1402
1403 #[tokio::test]
1404 async fn the_fake_forgets_a_deleted_token() {
1405 let tokens = InMemoryTokenRepo::new();
1406 let user = UserId::generate();
1407 let (token, secret) = token_for(&user, "laptop", 1_000);
1408 tokens.save(&token).await.expect("save");
1409
1410 tokens.delete(&token.id).await.expect("delete");
1411
1412 assert!(
1413 tokens
1414 .find_by_hash(&secret.hash())
1415 .await
1416 .expect("lookup")
1417 .is_none()
1418 );
1419 }
1420
1421 // --- InMemoryIssueRepo --------------------------------------------------------
1422
1423 /// The same contract the SQLite tests assert, on the fake the use cases run against.
1424 /// A fake that ordered or numbered differently would let a use case pass here and
1425 /// surprise someone in production.
1426 fn an_issue(repo: &RepoId, number: u64, title: &str) -> Issue {
1427 Issue::new(
1428 IssueId::generate(),
1429 repo.clone(),
1430 IssueNumber::from_trusted(number),
1431 title,
1432 "body",
1433 UserId::generate(),
1434 at(1_000),
1435 )
1436 .expect("valid issue")
1437 }
1438
1439 #[tokio::test]
1440 async fn in_memory_numbering_starts_at_one_and_is_per_repository() {
1441 let repos = InMemoryRepoRepo::new();
1442 let first = RepoId::generate();
1443 let second = RepoId::generate();
1444
1445 assert_eq!(repos.next_number(&first).await.expect("allocate").get(), 1);
1446 assert_eq!(repos.next_number(&first).await.expect("allocate").get(), 2);
1447 assert_eq!(repos.next_number(&second).await.expect("allocate").get(), 1);
1448 }
1449
1450 #[tokio::test]
1451 async fn in_memory_issues_round_trip_and_stay_under_their_repository() {
1452 let issues = InMemoryIssueRepo::new();
1453 let repo = RepoId::generate();
1454 let issue = an_issue(&repo, 1, "Blame is slow");
1455 issues.save(&issue).await.expect("save");
1456
1457 assert_eq!(
1458 issues
1459 .find_by_number(&repo, IssueNumber::from_trusted(1))
1460 .await
1461 .expect("lookup"),
1462 Some(issue)
1463 );
1464 assert!(
1465 issues
1466 .find_by_number(&RepoId::generate(), IssueNumber::from_trusted(1))
1467 .await
1468 .expect("lookup")
1469 .is_none()
1470 );
1471 }
1472
1473 #[tokio::test]
1474 async fn in_memory_the_second_page_of_issues_starts_where_the_first_ended() {
1475 let issues = InMemoryIssueRepo::new();
1476 let repo = RepoId::generate();
1477
1478 for number in 1..=5 {
1479 issues
1480 .save(&an_issue(&repo, number, &format!("issue {number}")))
1481 .await
1482 .expect("save");
1483 }
1484
1485 let first = issues
1486 .list_by_repo(&repo, IssueState::Open, 0, 2)
1487 .await
1488 .expect("list");
1489 let second = issues
1490 .list_by_repo(&repo, IssueState::Open, 2, 2)
1491 .await
1492 .expect("list");
1493
1494 assert_eq!(
1495 first.iter().map(|i| i.number.get()).collect::<Vec<_>>(),
1496 vec![5, 4]
1497 );
1498 assert_eq!(
1499 second.iter().map(|i| i.number.get()).collect::<Vec<_>>(),
1500 vec![3, 2]
1501 );
1502 assert!(
1503 issues
1504 .list_by_repo(&repo, IssueState::Open, 500, 2)
1505 .await
1506 .expect("list")
1507 .is_empty(),
1508 "an offset past the end is an empty page, not an error"
1509 );
1510 }
1511
1512 #[tokio::test]
1513 async fn in_memory_listing_is_filtered_by_state_and_newest_first() {
1514 let issues = InMemoryIssueRepo::new();
1515 let repo = RepoId::generate();
1516 let mut second = an_issue(&repo, 2, "issue 2");
1517 for issue in [
1518 an_issue(&repo, 1, "issue 1"),
1519 second.clone(),
1520 an_issue(&repo, 3, "issue 3"),
1521 ] {
1522 issues.save(&issue).await.expect("save");
1523 }
1524 second.close(at(2_000));
1525 issues.save(&second).await.expect("close");
1526
1527 assert_eq!(
1528 issues
1529 .list_by_repo(&repo, IssueState::Open, 0, 50)
1530 .await
1531 .expect("list")
1532 .iter()
1533 .map(|issue| issue.number.get())
1534 .collect::<Vec<_>>(),
1535 vec![3, 1]
1536 );
1537 assert_eq!(
1538 issues.counts(&repo).await.expect("counts"),
1539 IssueCounts { open: 2, closed: 1 }
1540 );
1541 }
1542
1543 #[tokio::test]
1544 async fn in_memory_comments_read_forwards_and_are_counted_per_issue() {
1545 let issues = InMemoryIssueRepo::new();
1546 let repo = RepoId::generate();
1547 let issue = an_issue(&repo, 1, "Blame is slow");
1548 let quiet = an_issue(&repo, 2, "Nobody replied");
1549 issues.save(&issue).await.expect("save");
1550 issues.save(&quiet).await.expect("save");
1551
1552 for (seconds, body) in [(3_000, "second"), (2_000, "first")] {
1553 issues
1554 .add_comment(
1555 &IssueComment::new(
1556 IssueCommentId::generate(),
1557 issue.id.clone(),
1558 UserId::generate(),
1559 body,
1560 at(seconds),
1561 )
1562 .expect("valid comment"),
1563 )
1564 .await
1565 .expect("comment");
1566 }
1567
1568 assert_eq!(
1569 issues
1570 .list_comments(&issue.id)
1571 .await
1572 .expect("list")
1573 .iter()
1574 .map(|comment| comment.body.as_str())
1575 .collect::<Vec<_>>(),
1576 vec!["first", "second"]
1577 );
1578
1579 let mut counts = issues.comment_counts(&repo).await.expect("counts");
1580 counts.sort_by_key(|(id, _)| id.as_str().to_owned());
1581 let mut expected = vec![(issue.id.clone(), 2), (quiet.id.clone(), 0)];
1582 expected.sort_by_key(|(id, _)| id.as_str().to_owned());
1583
1584 assert_eq!(counts, expected);
1585 }
1586}
1587
1588#[derive(Debug, Default, Clone)]
1589pub struct InMemorySessionRepo {
1590 sessions: Arc<Mutex<HashMap<String, Session>>>,
1591}
1592
1593impl InMemorySessionRepo {
1594 pub fn new() -> Self {
1595 Self::default()
1596 }
1597}
1598
1599impl SessionRepository for InMemorySessionRepo {
1600 async fn find(&self, token_hash: &SessionTokenHash) -> RepositoryResult<Option<Session>> {
1601 let sessions = self.sessions.lock().expect("lock poisoned");
1602 Ok(sessions.get(token_hash.as_str()).cloned())
1603 }
1604
1605 async fn save(&self, session: &Session) -> RepositoryResult<()> {
1606 let mut sessions = self.sessions.lock().expect("lock poisoned");
1607 sessions.insert(session.token_hash.as_str().to_owned(), session.clone());
1608 Ok(())
1609 }
1610
1611 async fn delete(&self, token_hash: &SessionTokenHash) -> RepositoryResult<()> {
1612 let mut sessions = self.sessions.lock().expect("lock poisoned");
1613 sessions.remove(token_hash.as_str());
1614 Ok(())
1615 }
1616
1617 async fn delete_by_user(
1618 &self,
1619 user_id: &UserId,
1620 except: Option<&SessionTokenHash>,
1621 ) -> RepositoryResult<u64> {
1622 let mut sessions = self.sessions.lock().expect("lock poisoned");
1623 let before = sessions.len();
1624
1625 sessions.retain(|hash, session| {
1626 &session.user_id != user_id || except.is_some_and(|kept| kept.as_str() == hash)
1627 });
1628
1629 Ok((before - sessions.len()) as u64)
1630 }
1631
1632 async fn delete_expired(&self, now: SystemTime) -> RepositoryResult<u64> {
1633 let mut sessions = self.sessions.lock().expect("lock poisoned");
1634 let before = sessions.len();
1635 sessions.retain(|_, session| !session.is_expired_at(now));
1636 Ok((before - sessions.len()) as u64)
1637 }
1638}
1639
1640#[derive(Debug, Default, Clone)]
1641pub struct InMemoryRepoRepo {
1642 repos: Arc<Mutex<HashMap<String, Repository>>>,
1643 /// The number to hand out *next*, per repository. Absent means nothing has been
1644 /// allocated yet, matching the SQLite table having no row. Its own lock: allocating
1645 /// a number must not wait on a listing, and nothing reads the two together.
1646 sequences: Arc<Mutex<HashMap<String, u64>>>,
1647}
1648
1649impl InMemoryRepoRepo {
1650 pub fn new() -> Self {
1651 Self::default()
1652 }
1653}
1654
1655impl RepoRepository for InMemoryRepoRepo {
1656 async fn next_number(&self, repo_id: &RepoId) -> RepositoryResult<IssueNumber> {
1657 let mut sequences = self.sequences.lock().expect("lock poisoned");
1658 let next = sequences.entry(repo_id.as_str().to_owned()).or_insert(1);
1659 let allocated = *next;
1660 *next += 1;
1661
1662 Ok(IssueNumber::from_trusted(allocated))
1663 }
1664
1665 async fn find_by_id(&self, id: &RepoId) -> RepositoryResult<Option<Repository>> {
1666 let repos = self.repos.lock().expect("lock poisoned");
1667 Ok(repos.get(id.as_str()).cloned())
1668 }
1669
1670 async fn find_by_org_and_name(
1671 &self,
1672 org_id: &OrgId,
1673 name: &RepoName,
1674 ) -> RepositoryResult<Option<Repository>> {
1675 let repos = self.repos.lock().expect("lock poisoned");
1676 Ok(repos
1677 .values()
1678 .find(|repo| &repo.org_id == org_id && &repo.name == name)
1679 .cloned())
1680 }
1681
1682 async fn list_by_org(&self, org_id: &OrgId) -> RepositoryResult<Vec<Repository>> {
1683 let repos = self.repos.lock().expect("lock poisoned");
1684 let mut found: Vec<Repository> = repos
1685 .values()
1686 .filter(|repo| &repo.org_id == org_id)
1687 .cloned()
1688 .collect();
1689 // Sorted exactly as the SQL is — newest first, name ascending as a tiebreak.
1690 // A fake that ordered differently would let a use case pass in tests and
1691 // surprise someone in production.
1692 found.sort_by(|a, b| {
1693 b.updated_at
1694 .cmp(&a.updated_at)
1695 .then_with(|| a.name.as_str().cmp(b.name.as_str()))
1696 });
1697 Ok(found)
1698 }
1699
1700 async fn save(&self, repo: &Repository) -> RepositoryResult<()> {
1701 let mut repos = self.repos.lock().expect("lock poisoned");
1702 repos.insert(repo.id.as_str().to_owned(), repo.clone());
1703 Ok(())
1704 }
1705
1706 async fn touch(&self, id: &RepoId, now: SystemTime) -> RepositoryResult<()> {
1707 let mut repos = self.repos.lock().expect("lock poisoned");
1708 if let Some(repo) = repos.get_mut(id.as_str()) {
1709 repo.updated_at = now;
1710 }
1711 Ok(())
1712 }
1713
1714 async fn fail_interrupted_imports(&self, reason: &str) -> RepositoryResult<u64> {
1715 let mut repos = self.repos.lock().expect("lock poisoned");
1716 let mut swept = 0;
1717
1718 for repo in repos.values_mut() {
1719 if repo.import_state == Some(ImportState::Importing) {
1720 repo.fail_import(reason);
1721 swept += 1;
1722 }
1723 }
1724
1725 Ok(swept)
1726 }
1727
1728 async fn delete(&self, id: &RepoId) -> RepositoryResult<()> {
1729 let mut repos = self.repos.lock().expect("lock poisoned");
1730 repos.remove(id.as_str());
1731 Ok(())
1732 }
1733
1734 async fn count(&self) -> RepositoryResult<u64> {
1735 let repos = self.repos.lock().expect("lock poisoned");
1736 Ok(repos.len() as u64)
1737 }
1738}
1739
1740/// One-shot password reset tokens.
1741///
1742/// Appended at the end of the file, where the last several implementations already
1743/// live: this module's `mod tests` sits in the middle rather than at the bottom.
1744#[derive(Debug, Default, Clone)]
1745pub struct InMemoryPasswordResetRepo {
1746 resets: Arc<Mutex<HashMap<String, PasswordReset>>>,
1747}
1748
1749impl InMemoryPasswordResetRepo {
1750 pub fn new() -> Self {
1751 Self::default()
1752 }
1753}
1754
1755impl PasswordResetRepository for InMemoryPasswordResetRepo {
1756 async fn find_by_hash(&self, hash: &ResetHash) -> RepositoryResult<Option<PasswordReset>> {
1757 let resets = self.resets.lock().expect("lock poisoned");
1758
1759 Ok(resets
1760 .values()
1761 .find(|reset| reset.token_hash.matches(hash))
1762 .cloned())
1763 }
1764
1765 async fn save(&self, reset: &PasswordReset) -> RepositoryResult<()> {
1766 let mut resets = self.resets.lock().expect("lock poisoned");
1767 resets.insert(reset.id.as_str().to_owned(), reset.clone());
1768 Ok(())
1769 }
1770
1771 async fn mark_used(&self, id: &ResetId, at: SystemTime) -> RepositoryResult<()> {
1772 let mut resets = self.resets.lock().expect("lock poisoned");
1773
1774 if let Some(reset) = resets.get_mut(id.as_str()) {
1775 reset.used_at = Some(at);
1776 }
1777
1778 Ok(())
1779 }
1780
1781 async fn invalidate_for_user(&self, user_id: &UserId, at: SystemTime) -> RepositoryResult<u64> {
1782 let mut resets = self.resets.lock().expect("lock poisoned");
1783 let mut invalidated = 0;
1784
1785 // Only the unused ones, so a count means "links that were still worth
1786 // something" — and so an already-spent row keeps the moment it was spent.
1787 for reset in resets
1788 .values_mut()
1789 .filter(|reset| &reset.user_id == user_id && reset.used_at.is_none())
1790 {
1791 reset.used_at = Some(at);
1792 invalidated += 1;
1793 }
1794
1795 Ok(invalidated)
1796 }
1797}