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