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,
8 sync::{Arc, Mutex},
9 time::SystemTime,
10};
11
12use crate::domain::{
13 Email, ImportState, Issue, IssueComment, IssueId, IssueNumber, IssueState, Membership, OrgId,
14 OrgName, Organization, PersonalAccessToken, PushEvent, PushEventId, RepoId, RepoName,
15 Repository, Session, SessionTokenHash, TokenHash, TokenId, User, UserId, Webhook,
16 WebhookDelivery, WebhookId,
17 repository::{
18 IssueCounts, IssueRepository, MembershipRepository, OrgRepository, PushEventRepository,
19 RepoRepository, RepositoryResult, SessionRepository, TokenRepository, UserRepository,
20 WebhookDeliveryRepository, WebhookRepository,
21 },
22};
23
24/// Shared, cloneable storage. Cloning shares the same underlying map, so a repository
25/// handed to two use cases sees one set of data.
26#[derive(Debug, Default, Clone)]
27pub struct InMemoryUserRepo {
28 users: Arc<Mutex<HashMap<String, User>>>,
29}
30
31impl InMemoryUserRepo {
32 pub fn new() -> Self {
33 Self::default()
34 }
35}
36
37impl UserRepository for InMemoryUserRepo {
38 async fn find_by_id(&self, id: &UserId) -> RepositoryResult<Option<User>> {
39 let users = self.users.lock().expect("lock poisoned");
40 Ok(users.get(id.as_str()).cloned())
41 }
42
43 async fn find_by_email(&self, email: &Email) -> RepositoryResult<Option<User>> {
44 let users = self.users.lock().expect("lock poisoned");
45 Ok(users.values().find(|user| &user.email == email).cloned())
46 }
47
48 async fn save(&self, user: &User) -> RepositoryResult<()> {
49 let mut users = self.users.lock().expect("lock poisoned");
50 users.insert(user.id.as_str().to_owned(), user.clone());
51 Ok(())
52 }
53
54 async fn sole_user(&self) -> RepositoryResult<Option<User>> {
55 let users = self.users.lock().expect("lock poisoned");
56
57 match users.len() {
58 1 => Ok(users.values().next().cloned()),
59 _ => Ok(None),
60 }
61 }
62
63 async fn any_exist(&self) -> RepositoryResult<bool> {
64 let users = self.users.lock().expect("lock poisoned");
65 Ok(!users.is_empty())
66 }
67}
68
69#[derive(Debug, Default, Clone)]
70pub struct InMemoryOrgRepo {
71 orgs: Arc<Mutex<HashMap<String, Organization>>>,
72}
73
74impl InMemoryOrgRepo {
75 pub fn new() -> Self {
76 Self::default()
77 }
78}
79
80impl OrgRepository for InMemoryOrgRepo {
81 async fn find_by_id(&self, id: &OrgId) -> RepositoryResult<Option<Organization>> {
82 let orgs = self.orgs.lock().expect("lock poisoned");
83 Ok(orgs.get(id.as_str()).cloned())
84 }
85
86 async fn find_by_name(&self, name: &OrgName) -> RepositoryResult<Option<Organization>> {
87 let orgs = self.orgs.lock().expect("lock poisoned");
88 Ok(orgs.values().find(|org| &org.name == name).cloned())
89 }
90
91 async fn save(&self, org: &Organization) -> RepositoryResult<()> {
92 let mut orgs = self.orgs.lock().expect("lock poisoned");
93 orgs.insert(org.id.as_str().to_owned(), org.clone());
94 Ok(())
95 }
96}
97
98#[derive(Debug, Default, Clone)]
99pub struct InMemoryMembershipRepo {
100 memberships: Arc<Mutex<HashMap<String, Membership>>>,
101}
102
103impl InMemoryMembershipRepo {
104 pub fn new() -> Self {
105 Self::default()
106 }
107}
108
109impl MembershipRepository for InMemoryMembershipRepo {
110 async fn find(&self, org_id: &OrgId, user_id: &UserId) -> RepositoryResult<Option<Membership>> {
111 let memberships = self.memberships.lock().expect("lock poisoned");
112 Ok(memberships
113 .values()
114 .find(|m| &m.org_id == org_id && &m.user_id == user_id)
115 .cloned())
116 }
117
118 async fn list_for_user(&self, user_id: &UserId) -> RepositoryResult<Vec<Membership>> {
119 let memberships = self.memberships.lock().expect("lock poisoned");
120 Ok(memberships
121 .values()
122 .filter(|m| &m.user_id == user_id)
123 .cloned()
124 .collect())
125 }
126
127 async fn save(&self, membership: &Membership) -> RepositoryResult<()> {
128 let mut memberships = self.memberships.lock().expect("lock poisoned");
129 memberships.insert(membership.id.as_str().to_owned(), membership.clone());
130 Ok(())
131 }
132}
133
134/// Personal access tokens held in memory.
135#[derive(Debug, Default, Clone)]
136pub struct InMemoryTokenRepo {
137 tokens: Arc<Mutex<HashMap<String, PersonalAccessToken>>>,
138}
139
140impl InMemoryTokenRepo {
141 pub fn new() -> Self {
142 Self::default()
143 }
144}
145
146impl TokenRepository for InMemoryTokenRepo {
147 async fn find_by_hash(
148 &self,
149 hash: &TokenHash,
150 ) -> RepositoryResult<Option<PersonalAccessToken>> {
151 let tokens = self.tokens.lock().expect("lock poisoned");
152
153 Ok(tokens
154 .values()
155 .find(|token| token.token_hash.matches(hash))
156 .cloned())
157 }
158
159 async fn list_by_user(&self, user_id: &UserId) -> RepositoryResult<Vec<PersonalAccessToken>> {
160 let tokens = self.tokens.lock().expect("lock poisoned");
161
162 let mut found: Vec<PersonalAccessToken> = tokens
163 .values()
164 .filter(|token| &token.user_id == user_id)
165 .cloned()
166 .collect();
167
168 // Newest first, with the id breaking ties: two tokens issued in the same second
169 // would otherwise come back in whatever order the map happened to hold them.
170 found.sort_by(|a, b| {
171 b.created_at
172 .cmp(&a.created_at)
173 .then_with(|| a.id.as_str().cmp(b.id.as_str()))
174 });
175
176 Ok(found)
177 }
178
179 async fn save(&self, token: &PersonalAccessToken) -> RepositoryResult<()> {
180 let mut tokens = self.tokens.lock().expect("lock poisoned");
181 tokens.insert(token.id.as_str().to_owned(), token.clone());
182 Ok(())
183 }
184
185 async fn delete(&self, id: &TokenId) -> RepositoryResult<()> {
186 let mut tokens = self.tokens.lock().expect("lock poisoned");
187 tokens.remove(id.as_str());
188 Ok(())
189 }
190}
191
192/// Issues, their comments, and the per-repository number sequence.
193///
194/// One struct for all three because they are one aggregate and one port — and because
195/// allocation has to be atomic, which is only true here if the sequence sits behind the
196/// same lock as everything else.
197#[derive(Debug, Default, Clone)]
198pub struct InMemoryIssueRepo {
199 state: Arc<Mutex<IssueStore>>,
200}
201
202/// The maps behind [`InMemoryIssueRepo`], under one lock.
203#[derive(Debug, Default)]
204struct IssueStore {
205 issues: HashMap<String, Issue>,
206 comments: Vec<IssueComment>,
207 /// The number to hand out *next*, per repository. Absent means nothing has been
208 /// allocated yet, matching the SQLite table having no row.
209 sequences: HashMap<String, u64>,
210}
211
212impl InMemoryIssueRepo {
213 pub fn new() -> Self {
214 Self::default()
215 }
216}
217
218impl IssueRepository for InMemoryIssueRepo {
219 async fn next_number(&self, repo_id: &RepoId) -> RepositoryResult<IssueNumber> {
220 let mut state = self.state.lock().expect("lock poisoned");
221 let next = state
222 .sequences
223 .entry(repo_id.as_str().to_owned())
224 .or_insert(1);
225 let allocated = *next;
226 *next += 1;
227
228 Ok(IssueNumber::from_trusted(allocated))
229 }
230
231 async fn find_by_number(
232 &self,
233 repo_id: &RepoId,
234 number: IssueNumber,
235 ) -> RepositoryResult<Option<Issue>> {
236 let state = self.state.lock().expect("lock poisoned");
237
238 Ok(state
239 .issues
240 .values()
241 .find(|issue| &issue.repo_id == repo_id && issue.number == number)
242 .cloned())
243 }
244
245 async fn list_by_repo(
246 &self,
247 repo_id: &RepoId,
248 state: IssueState,
249 ) -> RepositoryResult<Vec<Issue>> {
250 let held = self.state.lock().expect("lock poisoned");
251
252 let mut found: Vec<Issue> = held
253 .issues
254 .values()
255 .filter(|issue| &issue.repo_id == repo_id && issue.state == state)
256 .cloned()
257 .collect();
258
259 // Newest first, which for a monotonic sequence is descending number — the same
260 // order the SQL says, and one that cannot tie.
261 found.sort_by_key(|issue| std::cmp::Reverse(issue.number));
262
263 Ok(found)
264 }
265
266 async fn counts(&self, repo_id: &RepoId) -> RepositoryResult<IssueCounts> {
267 let state = self.state.lock().expect("lock poisoned");
268 let mut counts = IssueCounts::default();
269
270 for issue in state.issues.values().filter(|i| &i.repo_id == repo_id) {
271 match issue.state {
272 IssueState::Open => counts.open += 1,
273 IssueState::Closed => counts.closed += 1,
274 }
275 }
276
277 Ok(counts)
278 }
279
280 async fn comment_counts(&self, repo_id: &RepoId) -> RepositoryResult<Vec<(IssueId, u64)>> {
281 let state = self.state.lock().expect("lock poisoned");
282
283 Ok(state
284 .issues
285 .values()
286 .filter(|issue| &issue.repo_id == repo_id)
287 .map(|issue| {
288 let total = state
289 .comments
290 .iter()
291 .filter(|comment| comment.issue_id == issue.id)
292 .count() as u64;
293
294 (issue.id.clone(), total)
295 })
296 .collect())
297 }
298
299 async fn save(&self, issue: &Issue) -> RepositoryResult<()> {
300 let mut state = self.state.lock().expect("lock poisoned");
301 state
302 .issues
303 .insert(issue.id.as_str().to_owned(), issue.clone());
304 Ok(())
305 }
306
307 async fn list_comments(&self, issue_id: &IssueId) -> RepositoryResult<Vec<IssueComment>> {
308 let state = self.state.lock().expect("lock poisoned");
309
310 let mut found: Vec<IssueComment> = state
311 .comments
312 .iter()
313 .filter(|comment| &comment.issue_id == issue_id)
314 .cloned()
315 .collect();
316
317 // A stable sort over a vector kept in insertion order, which is what the SQL's
318 // `rowid` tiebreak means: comments posted in the same second read in the order
319 // they were written.
320 found.sort_by_key(|comment| comment.created_at);
321
322 Ok(found)
323 }
324
325 async fn add_comment(&self, comment: &IssueComment) -> RepositoryResult<()> {
326 let mut state = self.state.lock().expect("lock poisoned");
327 state.comments.push(comment.clone());
328 Ok(())
329 }
330}
331
332/// Push events, keyed by id. Ordering is done on read, as in every repo here.
333#[derive(Debug, Default, Clone)]
334pub struct InMemoryPushEventRepo {
335 events: Arc<Mutex<HashMap<String, PushEvent>>>,
336}
337
338impl InMemoryPushEventRepo {
339 pub fn new() -> Self {
340 Self::default()
341 }
342}
343
344impl PushEventRepository for InMemoryPushEventRepo {
345 async fn find(&self, id: &PushEventId) -> RepositoryResult<Option<PushEvent>> {
346 let events = self.events.lock().expect("lock poisoned");
347 Ok(events.get(id.as_str()).cloned())
348 }
349
350 async fn list_by_repo(
351 &self,
352 repo_id: &RepoId,
353 limit: usize,
354 ) -> RepositoryResult<Vec<PushEvent>> {
355 let events = self.events.lock().expect("lock poisoned");
356
357 let mut found: Vec<PushEvent> = events
358 .values()
359 .filter(|event| &event.repo_id == repo_id)
360 .cloned()
361 .collect();
362
363 found.sort_by(|a, b| {
364 b.created_at
365 .cmp(&a.created_at)
366 .then_with(|| a.id.as_str().cmp(b.id.as_str()))
367 });
368 found.truncate(limit);
369
370 Ok(found)
371 }
372
373 async fn save(&self, event: &PushEvent) -> RepositoryResult<()> {
374 let mut events = self.events.lock().expect("lock poisoned");
375 events.insert(event.id.as_str().to_owned(), event.clone());
376 Ok(())
377 }
378}
379
380#[derive(Debug, Default, Clone)]
381pub struct InMemoryWebhookRepo {
382 webhooks: Arc<Mutex<HashMap<String, Webhook>>>,
383}
384
385impl InMemoryWebhookRepo {
386 pub fn new() -> Self {
387 Self::default()
388 }
389}
390
391impl WebhookRepository for InMemoryWebhookRepo {
392 async fn find(&self, id: &WebhookId) -> RepositoryResult<Option<Webhook>> {
393 let webhooks = self.webhooks.lock().expect("lock poisoned");
394 Ok(webhooks.get(id.as_str()).cloned())
395 }
396
397 async fn list_by_repo(&self, repo_id: &RepoId) -> RepositoryResult<Vec<Webhook>> {
398 let webhooks = self.webhooks.lock().expect("lock poisoned");
399
400 let mut found: Vec<Webhook> = webhooks
401 .values()
402 .filter(|webhook| &webhook.repo_id == repo_id)
403 .cloned()
404 .collect();
405
406 // Oldest first, matching SQLite: a list that reshuffles when one hook is edited
407 // is worse than one that grows downward.
408 found.sort_by(|a, b| {
409 a.created_at
410 .cmp(&b.created_at)
411 .then_with(|| a.id.as_str().cmp(b.id.as_str()))
412 });
413
414 Ok(found)
415 }
416
417 async fn save(&self, webhook: &Webhook) -> RepositoryResult<()> {
418 let mut webhooks = self.webhooks.lock().expect("lock poisoned");
419 webhooks.insert(webhook.id.as_str().to_owned(), webhook.clone());
420 Ok(())
421 }
422
423 async fn delete(&self, id: &WebhookId) -> RepositoryResult<()> {
424 let mut webhooks = self.webhooks.lock().expect("lock poisoned");
425 webhooks.remove(id.as_str());
426 Ok(())
427 }
428}
429
430#[derive(Debug, Default, Clone)]
431pub struct InMemoryWebhookDeliveryRepo {
432 deliveries: Arc<Mutex<HashMap<String, WebhookDelivery>>>,
433}
434
435impl InMemoryWebhookDeliveryRepo {
436 pub fn new() -> Self {
437 Self::default()
438 }
439
440 fn sorted(&self, webhook_id: &WebhookId) -> Vec<WebhookDelivery> {
441 let deliveries = self.deliveries.lock().expect("lock poisoned");
442
443 let mut found: Vec<WebhookDelivery> = deliveries
444 .values()
445 .filter(|delivery| &delivery.webhook_id == webhook_id)
446 .cloned()
447 .collect();
448
449 found.sort_by(|a, b| {
450 b.delivered_at
451 .cmp(&a.delivered_at)
452 .then_with(|| b.attempt.cmp(&a.attempt))
453 });
454
455 found
456 }
457}
458
459impl WebhookDeliveryRepository for InMemoryWebhookDeliveryRepo {
460 async fn list_by_webhook(
461 &self,
462 webhook_id: &WebhookId,
463 limit: usize,
464 ) -> RepositoryResult<Vec<WebhookDelivery>> {
465 let mut found = self.sorted(webhook_id);
466 found.truncate(limit);
467
468 Ok(found)
469 }
470
471 async fn latest_by_webhook(
472 &self,
473 webhook_id: &WebhookId,
474 ) -> RepositoryResult<Option<WebhookDelivery>> {
475 Ok(self.sorted(webhook_id).into_iter().next())
476 }
477
478 async fn save(&self, delivery: &WebhookDelivery) -> RepositoryResult<()> {
479 let mut deliveries = self.deliveries.lock().expect("lock poisoned");
480 deliveries.insert(delivery.id.as_str().to_owned(), delivery.clone());
481 Ok(())
482 }
483}
484
485#[cfg(test)]
486mod tests {
487 use std::time::Duration;
488
489 use super::*;
490
491 fn at(seconds: u64) -> SystemTime {
492 SystemTime::UNIX_EPOCH + Duration::from_secs(seconds)
493 }
494 use crate::domain::{IssueCommentId, MembershipId, PasswordHash, Role};
495
496 fn user(email: &str, org_id: &OrgId) -> User {
497 User::new(
498 UserId::generate(),
499 Email::new(email).expect("valid email"),
500 PasswordHash::from_trusted("$argon2id$test"),
501 org_id.clone(),
502 )
503 }
504
505 #[tokio::test]
506 async fn users_are_found_by_id_and_email() {
507 let repo = InMemoryUserRepo::new();
508 let org_id = OrgId::generate();
509 let user = user("dev@example.com", &org_id);
510 repo.save(&user).await.expect("save");
511
512 let by_id = repo.find_by_id(&user.id).await.expect("lookup");
513 let by_email = repo.find_by_email(&user.email).await.expect("lookup");
514
515 assert_eq!(by_id.as_ref(), Some(&user));
516 assert_eq!(by_email.as_ref(), Some(&user));
517 }
518
519 #[tokio::test]
520 async fn missing_users_are_none_not_an_error() {
521 let repo = InMemoryUserRepo::new();
522
523 let found = repo.find_by_id(&UserId::generate()).await.expect("lookup");
524
525 assert_eq!(found, None);
526 }
527
528 #[tokio::test]
529 async fn saving_the_same_id_replaces_rather_than_duplicates() {
530 let repo = InMemoryUserRepo::new();
531 let org_id = OrgId::generate();
532 let mut user = user("dev@example.com", &org_id);
533 repo.save(&user).await.expect("save");
534
535 user.email = Email::new("changed@example.com").expect("valid email");
536 repo.save(&user).await.expect("save");
537
538 assert_eq!(
539 repo.find_by_email(&Email::new("dev@example.com").unwrap())
540 .await
541 .expect("lookup"),
542 None
543 );
544 assert!(repo.any_exist().await.expect("any_exist"));
545 }
546
547 #[tokio::test]
548 async fn any_exist_reports_emptiness() {
549 let repo = InMemoryUserRepo::new();
550 assert!(!repo.any_exist().await.expect("any_exist"));
551
552 repo.save(&user("dev@example.com", &OrgId::generate()))
553 .await
554 .expect("save");
555
556 assert!(repo.any_exist().await.expect("any_exist"));
557 }
558
559 #[tokio::test]
560 async fn clones_share_storage() {
561 let repo = InMemoryUserRepo::new();
562 let clone = repo.clone();
563
564 clone
565 .save(&user("dev@example.com", &OrgId::generate()))
566 .await
567 .expect("save");
568
569 assert!(repo.any_exist().await.expect("any_exist"));
570 }
571
572 #[tokio::test]
573 async fn orgs_are_found_by_id_and_name() {
574 let repo = InMemoryOrgRepo::new();
575 let org = Organization::new(OrgId::generate(), "acme", None).expect("valid org");
576 repo.save(&org).await.expect("save");
577
578 assert_eq!(
579 repo.find_by_id(&org.id).await.expect("lookup").as_ref(),
580 Some(&org)
581 );
582 assert_eq!(
583 repo.find_by_name(&org.name).await.expect("lookup").as_ref(),
584 Some(&org)
585 );
586 }
587
588 #[tokio::test]
589 async fn org_lookup_by_name_respects_normalisation() {
590 let repo = InMemoryOrgRepo::new();
591 let org = Organization::new(OrgId::generate(), "Acme", None).expect("valid org");
592 repo.save(&org).await.expect("save");
593
594 let found = repo
595 .find_by_name(&OrgName::new("ACME").expect("valid"))
596 .await
597 .expect("lookup");
598
599 assert_eq!(found.as_ref(), Some(&org));
600 }
601
602 #[tokio::test]
603 async fn memberships_are_found_by_org_and_user() {
604 let repo = InMemoryMembershipRepo::new();
605 let org_id = OrgId::generate();
606 let user_id = UserId::generate();
607 let membership = Membership::new(
608 MembershipId::generate(),
609 org_id.clone(),
610 user_id.clone(),
611 Role::Owner,
612 );
613 repo.save(&membership).await.expect("save");
614
615 let found = repo.find(&org_id, &user_id).await.expect("lookup");
616
617 assert_eq!(found.as_ref(), Some(&membership));
618 }
619
620 #[tokio::test]
621 async fn membership_lookup_does_not_match_a_different_user() {
622 let repo = InMemoryMembershipRepo::new();
623 let org_id = OrgId::generate();
624 repo.save(&Membership::new(
625 MembershipId::generate(),
626 org_id.clone(),
627 UserId::generate(),
628 Role::Owner,
629 ))
630 .await
631 .expect("save");
632
633 let found = repo
634 .find(&org_id, &UserId::generate())
635 .await
636 .expect("lookup");
637
638 assert_eq!(found, None);
639 }
640
641 #[tokio::test]
642 async fn list_for_user_returns_only_that_users_memberships() {
643 let repo = InMemoryMembershipRepo::new();
644 let user_id = UserId::generate();
645 for _ in 0..2 {
646 repo.save(&Membership::new(
647 MembershipId::generate(),
648 OrgId::generate(),
649 user_id.clone(),
650 Role::Member,
651 ))
652 .await
653 .expect("save");
654 }
655 repo.save(&Membership::new(
656 MembershipId::generate(),
657 OrgId::generate(),
658 UserId::generate(),
659 Role::Owner,
660 ))
661 .await
662 .expect("save");
663
664 let found = repo.list_for_user(&user_id).await.expect("lookup");
665
666 assert_eq!(found.len(), 2);
667 assert!(found.iter().all(|m| m.user_id == user_id));
668 }
669 // --- InMemoryTokenRepo -------------------------------------------------------
670
671 use crate::domain::TokenSecret;
672
673 fn token_for(user: &UserId, name: &str, at: u64) -> (PersonalAccessToken, TokenSecret) {
674 use std::time::Duration;
675
676 let secret = TokenSecret::generate();
677 let token = PersonalAccessToken::new(
678 TokenId::generate(),
679 user.clone(),
680 name,
681 &secret,
682 SystemTime::UNIX_EPOCH + Duration::from_secs(at),
683 )
684 .expect("valid token");
685
686 (token, secret)
687 }
688
689 #[tokio::test]
690 async fn the_fake_finds_a_token_by_its_hash() {
691 let tokens = InMemoryTokenRepo::new();
692 let user = UserId::generate();
693 let (token, secret) = token_for(&user, "laptop", 1_000);
694 tokens.save(&token).await.expect("save");
695
696 assert_eq!(
697 tokens.find_by_hash(&secret.hash()).await.expect("lookup"),
698 Some(token)
699 );
700 assert_eq!(
701 tokens
702 .find_by_hash(&TokenSecret::generate().hash())
703 .await
704 .expect("lookup"),
705 None
706 );
707 }
708
709 #[tokio::test]
710 async fn the_fake_lists_newest_first_for_one_user_only() {
711 // Mirrors the SQLite ordering. A fake that lists in a different order lets a use
712 // case pass here and surprise someone in production.
713 let tokens = InMemoryTokenRepo::new();
714 let user = UserId::generate();
715 let other = UserId::generate();
716
717 for (owner, name, at) in [
718 (&user, "old", 1_000),
719 (&user, "new", 3_000),
720 (&user, "middle", 2_000),
721 (&other, "theirs", 4_000),
722 ] {
723 let (token, _) = token_for(owner, name, at);
724 tokens.save(&token).await.expect("save");
725 }
726
727 assert_eq!(
728 tokens
729 .list_by_user(&user)
730 .await
731 .expect("list")
732 .iter()
733 .map(|token| token.name.as_str())
734 .collect::<Vec<_>>(),
735 vec!["new", "middle", "old"]
736 );
737 }
738
739 // --- InMemoryRepoRepo --------------------------------------------------------
740
741 #[tokio::test]
742 async fn the_fake_forgets_a_deleted_repository() {
743 let repos = InMemoryRepoRepo::new();
744 let org_id = OrgId::generate();
745 let repo = Repository::new(
746 RepoId::generate(),
747 org_id.clone(),
748 "steid",
749 None,
750 crate::domain::Visibility::Public,
751 at(1_000),
752 )
753 .expect("valid repo");
754 repos.save(&repo).await.expect("save");
755
756 repos.delete(&repo.id).await.expect("delete");
757
758 assert_eq!(repos.find_by_id(&repo.id).await.expect("lookup"), None);
759 assert!(
760 repos
761 .find_by_org_and_name(&org_id, &repo.name)
762 .await
763 .expect("lookup")
764 .is_none(),
765 "the name should be free again"
766 );
767 assert!(repos.list_by_org(&org_id).await.expect("list").is_empty());
768 }
769
770 #[tokio::test]
771 async fn deleting_a_repository_that_is_not_there_succeeds() {
772 // Idempotent: a second click on a delete button must not become an error.
773 let repos = InMemoryRepoRepo::new();
774
775 assert!(repos.delete(&RepoId::generate()).await.is_ok());
776 }
777
778 #[tokio::test]
779 async fn deleting_one_repository_leaves_the_others() {
780 let repos = InMemoryRepoRepo::new();
781 let org_id = OrgId::generate();
782 let mut saved = Vec::new();
783 for name in ["alpha", "zebra"] {
784 let repo = Repository::new(
785 RepoId::generate(),
786 org_id.clone(),
787 name,
788 None,
789 crate::domain::Visibility::Public,
790 at(1_000),
791 )
792 .expect("valid repo");
793 repos.save(&repo).await.expect("save");
794 saved.push(repo);
795 }
796
797 repos.delete(&saved[0].id).await.expect("delete");
798
799 let listed = repos.list_by_org(&org_id).await.expect("list");
800 assert_eq!(
801 listed.iter().map(|r| r.name.as_str()).collect::<Vec<_>>(),
802 vec!["zebra"]
803 );
804 }
805
806 #[tokio::test]
807 async fn the_fake_lists_newest_first_breaking_ties_by_name() {
808 // The order the profile renders. It must match `SqliteRepoRepo::list_by_org`
809 // exactly — a fake that sorted differently would let a use case pass here and
810 // surprise someone in production.
811 let repos = InMemoryRepoRepo::new();
812 let org_id = OrgId::generate();
813 for (name, seconds) in [
814 ("alpha", 3_000),
815 ("older", 1_000),
816 ("newer", 2_000),
817 ("also-older", 1_000),
818 ] {
819 repos
820 .save(&repo_at(&org_id, name, seconds))
821 .await
822 .expect("save");
823 }
824
825 let listed = repos.list_by_org(&org_id).await.expect("list");
826
827 assert_eq!(
828 listed.iter().map(|r| r.name.as_str()).collect::<Vec<_>>(),
829 vec!["alpha", "newer", "also-older", "older"]
830 );
831 }
832
833 #[tokio::test]
834 async fn touching_moves_a_repository_to_the_supplied_time() {
835 let repos = InMemoryRepoRepo::new();
836 let org_id = OrgId::generate();
837 let repo = repo_at(&org_id, "steid", 1_000);
838 repos.save(&repo).await.expect("save");
839
840 repos.touch(&repo.id, at(5_000)).await.expect("touch");
841
842 let found = repos
843 .find_by_id(&repo.id)
844 .await
845 .expect("lookup")
846 .expect("still there");
847 assert_eq!(found.updated_at, at(5_000));
848 }
849
850 #[tokio::test]
851 async fn touching_a_repository_that_is_gone_succeeds() {
852 // A push can outlive a delete; there is nothing useful the caller could do.
853 let repos = InMemoryRepoRepo::new();
854
855 assert!(repos.touch(&RepoId::generate(), at(5_000)).await.is_ok());
856 }
857
858 #[tokio::test]
859 async fn the_fake_remembers_whether_a_repository_is_pinned() {
860 let repos = InMemoryRepoRepo::new();
861 let org_id = OrgId::generate();
862 let mut repo = repo_at(&org_id, "steid", 1_000);
863 repo.pinned = true;
864
865 repos.save(&repo).await.expect("save");
866
867 assert!(
868 repos
869 .find_by_id(&repo.id)
870 .await
871 .expect("lookup")
872 .expect("still there")
873 .pinned
874 );
875 }
876
877 fn repo_at(org_id: &OrgId, name: &str, seconds: u64) -> Repository {
878 Repository::new(
879 RepoId::generate(),
880 org_id.clone(),
881 name,
882 None,
883 crate::domain::Visibility::Public,
884 at(seconds),
885 )
886 .expect("valid repo")
887 }
888
889 #[tokio::test]
890 async fn the_fake_forgets_a_deleted_token() {
891 let tokens = InMemoryTokenRepo::new();
892 let user = UserId::generate();
893 let (token, secret) = token_for(&user, "laptop", 1_000);
894 tokens.save(&token).await.expect("save");
895
896 tokens.delete(&token.id).await.expect("delete");
897
898 assert!(
899 tokens
900 .find_by_hash(&secret.hash())
901 .await
902 .expect("lookup")
903 .is_none()
904 );
905 }
906
907 // --- InMemoryIssueRepo --------------------------------------------------------
908
909 /// The same contract the SQLite tests assert, on the fake the use cases run against.
910 /// A fake that ordered or numbered differently would let a use case pass here and
911 /// surprise someone in production.
912 fn an_issue(repo: &RepoId, number: u64, title: &str) -> Issue {
913 Issue::new(
914 IssueId::generate(),
915 repo.clone(),
916 IssueNumber::from_trusted(number),
917 title,
918 "body",
919 UserId::generate(),
920 at(1_000),
921 )
922 .expect("valid issue")
923 }
924
925 #[tokio::test]
926 async fn in_memory_numbering_starts_at_one_and_is_per_repository() {
927 let issues = InMemoryIssueRepo::new();
928 let first = RepoId::generate();
929 let second = RepoId::generate();
930
931 assert_eq!(issues.next_number(&first).await.expect("allocate").get(), 1);
932 assert_eq!(issues.next_number(&first).await.expect("allocate").get(), 2);
933 assert_eq!(
934 issues.next_number(&second).await.expect("allocate").get(),
935 1
936 );
937 }
938
939 #[tokio::test]
940 async fn in_memory_issues_round_trip_and_stay_under_their_repository() {
941 let issues = InMemoryIssueRepo::new();
942 let repo = RepoId::generate();
943 let issue = an_issue(&repo, 1, "Blame is slow");
944 issues.save(&issue).await.expect("save");
945
946 assert_eq!(
947 issues
948 .find_by_number(&repo, IssueNumber::from_trusted(1))
949 .await
950 .expect("lookup"),
951 Some(issue)
952 );
953 assert!(
954 issues
955 .find_by_number(&RepoId::generate(), IssueNumber::from_trusted(1))
956 .await
957 .expect("lookup")
958 .is_none()
959 );
960 }
961
962 #[tokio::test]
963 async fn in_memory_listing_is_filtered_by_state_and_newest_first() {
964 let issues = InMemoryIssueRepo::new();
965 let repo = RepoId::generate();
966 let mut second = an_issue(&repo, 2, "issue 2");
967 for issue in [
968 an_issue(&repo, 1, "issue 1"),
969 second.clone(),
970 an_issue(&repo, 3, "issue 3"),
971 ] {
972 issues.save(&issue).await.expect("save");
973 }
974 second.close(at(2_000));
975 issues.save(&second).await.expect("close");
976
977 assert_eq!(
978 issues
979 .list_by_repo(&repo, IssueState::Open)
980 .await
981 .expect("list")
982 .iter()
983 .map(|issue| issue.number.get())
984 .collect::<Vec<_>>(),
985 vec![3, 1]
986 );
987 assert_eq!(
988 issues.counts(&repo).await.expect("counts"),
989 IssueCounts { open: 2, closed: 1 }
990 );
991 }
992
993 #[tokio::test]
994 async fn in_memory_comments_read_forwards_and_are_counted_per_issue() {
995 let issues = InMemoryIssueRepo::new();
996 let repo = RepoId::generate();
997 let issue = an_issue(&repo, 1, "Blame is slow");
998 let quiet = an_issue(&repo, 2, "Nobody replied");
999 issues.save(&issue).await.expect("save");
1000 issues.save(&quiet).await.expect("save");
1001
1002 for (seconds, body) in [(3_000, "second"), (2_000, "first")] {
1003 issues
1004 .add_comment(
1005 &IssueComment::new(
1006 IssueCommentId::generate(),
1007 issue.id.clone(),
1008 UserId::generate(),
1009 body,
1010 at(seconds),
1011 )
1012 .expect("valid comment"),
1013 )
1014 .await
1015 .expect("comment");
1016 }
1017
1018 assert_eq!(
1019 issues
1020 .list_comments(&issue.id)
1021 .await
1022 .expect("list")
1023 .iter()
1024 .map(|comment| comment.body.as_str())
1025 .collect::<Vec<_>>(),
1026 vec!["first", "second"]
1027 );
1028
1029 let mut counts = issues.comment_counts(&repo).await.expect("counts");
1030 counts.sort_by_key(|(id, _)| id.as_str().to_owned());
1031 let mut expected = vec![(issue.id.clone(), 2), (quiet.id.clone(), 0)];
1032 expected.sort_by_key(|(id, _)| id.as_str().to_owned());
1033
1034 assert_eq!(counts, expected);
1035 }
1036}
1037
1038#[derive(Debug, Default, Clone)]
1039pub struct InMemorySessionRepo {
1040 sessions: Arc<Mutex<HashMap<String, Session>>>,
1041}
1042
1043impl InMemorySessionRepo {
1044 pub fn new() -> Self {
1045 Self::default()
1046 }
1047}
1048
1049impl SessionRepository for InMemorySessionRepo {
1050 async fn find(&self, token_hash: &SessionTokenHash) -> RepositoryResult<Option<Session>> {
1051 let sessions = self.sessions.lock().expect("lock poisoned");
1052 Ok(sessions.get(token_hash.as_str()).cloned())
1053 }
1054
1055 async fn save(&self, session: &Session) -> RepositoryResult<()> {
1056 let mut sessions = self.sessions.lock().expect("lock poisoned");
1057 sessions.insert(session.token_hash.as_str().to_owned(), session.clone());
1058 Ok(())
1059 }
1060
1061 async fn delete(&self, token_hash: &SessionTokenHash) -> RepositoryResult<()> {
1062 let mut sessions = self.sessions.lock().expect("lock poisoned");
1063 sessions.remove(token_hash.as_str());
1064 Ok(())
1065 }
1066
1067 async fn delete_expired(&self, now: SystemTime) -> RepositoryResult<u64> {
1068 let mut sessions = self.sessions.lock().expect("lock poisoned");
1069 let before = sessions.len();
1070 sessions.retain(|_, session| !session.is_expired_at(now));
1071 Ok((before - sessions.len()) as u64)
1072 }
1073}
1074
1075#[derive(Debug, Default, Clone)]
1076pub struct InMemoryRepoRepo {
1077 repos: Arc<Mutex<HashMap<String, Repository>>>,
1078}
1079
1080impl InMemoryRepoRepo {
1081 pub fn new() -> Self {
1082 Self::default()
1083 }
1084}
1085
1086impl RepoRepository for InMemoryRepoRepo {
1087 async fn find_by_id(&self, id: &RepoId) -> RepositoryResult<Option<Repository>> {
1088 let repos = self.repos.lock().expect("lock poisoned");
1089 Ok(repos.get(id.as_str()).cloned())
1090 }
1091
1092 async fn find_by_org_and_name(
1093 &self,
1094 org_id: &OrgId,
1095 name: &RepoName,
1096 ) -> RepositoryResult<Option<Repository>> {
1097 let repos = self.repos.lock().expect("lock poisoned");
1098 Ok(repos
1099 .values()
1100 .find(|repo| &repo.org_id == org_id && &repo.name == name)
1101 .cloned())
1102 }
1103
1104 async fn list_by_org(&self, org_id: &OrgId) -> RepositoryResult<Vec<Repository>> {
1105 let repos = self.repos.lock().expect("lock poisoned");
1106 let mut found: Vec<Repository> = repos
1107 .values()
1108 .filter(|repo| &repo.org_id == org_id)
1109 .cloned()
1110 .collect();
1111 // Sorted exactly as the SQL is — newest first, name ascending as a tiebreak.
1112 // A fake that ordered differently would let a use case pass in tests and
1113 // surprise someone in production.
1114 found.sort_by(|a, b| {
1115 b.updated_at
1116 .cmp(&a.updated_at)
1117 .then_with(|| a.name.as_str().cmp(b.name.as_str()))
1118 });
1119 Ok(found)
1120 }
1121
1122 async fn save(&self, repo: &Repository) -> RepositoryResult<()> {
1123 let mut repos = self.repos.lock().expect("lock poisoned");
1124 repos.insert(repo.id.as_str().to_owned(), repo.clone());
1125 Ok(())
1126 }
1127
1128 async fn touch(&self, id: &RepoId, now: SystemTime) -> RepositoryResult<()> {
1129 let mut repos = self.repos.lock().expect("lock poisoned");
1130 if let Some(repo) = repos.get_mut(id.as_str()) {
1131 repo.updated_at = now;
1132 }
1133 Ok(())
1134 }
1135
1136 async fn fail_interrupted_imports(&self, reason: &str) -> RepositoryResult<u64> {
1137 let mut repos = self.repos.lock().expect("lock poisoned");
1138 let mut swept = 0;
1139
1140 for repo in repos.values_mut() {
1141 if repo.import_state == Some(ImportState::Importing) {
1142 repo.fail_import(reason);
1143 swept += 1;
1144 }
1145 }
1146
1147 Ok(swept)
1148 }
1149
1150 async fn delete(&self, id: &RepoId) -> RepositoryResult<()> {
1151 let mut repos = self.repos.lock().expect("lock poisoned");
1152 repos.remove(id.as_str());
1153 Ok(())
1154 }
1155}