| 1 | |
| 2 | |
| 3 | |
| 4 | |
| 5 | |
| 6 | use std::{ |
| 7 | collections::{HashMap, HashSet}, |
| 8 | sync::{Arc, Mutex}, |
| 9 | time::SystemTime, |
| 10 | }; |
| 11 | |
| 12 | use crate::domain::{ |
| 13 | Email, ImportState, Issue, IssueComment, IssueId, IssueNumber, IssueState, Label, LabelId, |
| 14 | Membership, OrgId, OrgName, Organization, PersonalAccessToken, PullRequest, PullRequestComment, |
| 15 | PullRequestId, PullRequestState, PushEvent, PushEventId, RepoId, RepoName, Repository, Session, |
| 16 | SessionTokenHash, TokenHash, TokenId, User, UserId, Webhook, WebhookDelivery, WebhookId, |
| 17 | repository::{ |
| 18 | IssueCounts, IssueRepository, LabelRepository, MembershipRepository, OrgRepository, |
| 19 | PullRequestCounts, PullRequestRepository, PushEventRepository, RepoRepository, |
| 20 | RepositoryResult, SessionRepository, TokenRepository, UserRepository, |
| 21 | WebhookDeliveryRepository, WebhookRepository, |
| 22 | }, |
| 23 | }; |
| 24 | |
| 25 | |
| 26 | |
| 27 | #[derive(Debug, Default, Clone)] |
| 28 | pub struct InMemoryUserRepo { |
| 29 | users: Arc<Mutex<HashMap<String, User>>>, |
| 30 | } |
| 31 | |
| 32 | impl InMemoryUserRepo { |
| 33 | pub fn new() -> Self { |
| 34 | Self::default() |
| 35 | } |
| 36 | } |
| 37 | |
| 38 | impl UserRepository for InMemoryUserRepo { |
| 39 | async fn find_by_id(&self, id: &UserId) -> RepositoryResult<Option<User>> { |
| 40 | let users = self.users.lock().expect("lock poisoned"); |
| 41 | Ok(users.get(id.as_str()).cloned()) |
| 42 | } |
| 43 | |
| 44 | async fn find_by_email(&self, email: &Email) -> RepositoryResult<Option<User>> { |
| 45 | let users = self.users.lock().expect("lock poisoned"); |
| 46 | Ok(users.values().find(|user| &user.email == email).cloned()) |
| 47 | } |
| 48 | |
| 49 | async fn save(&self, user: &User) -> RepositoryResult<()> { |
| 50 | let mut users = self.users.lock().expect("lock poisoned"); |
| 51 | users.insert(user.id.as_str().to_owned(), user.clone()); |
| 52 | Ok(()) |
| 53 | } |
| 54 | |
| 55 | async fn sole_user(&self) -> RepositoryResult<Option<User>> { |
| 56 | let users = self.users.lock().expect("lock poisoned"); |
| 57 | |
| 58 | match users.len() { |
| 59 | 1 => Ok(users.values().next().cloned()), |
| 60 | _ => Ok(None), |
| 61 | } |
| 62 | } |
| 63 | |
| 64 | async fn any_exist(&self) -> RepositoryResult<bool> { |
| 65 | let users = self.users.lock().expect("lock poisoned"); |
| 66 | Ok(!users.is_empty()) |
| 67 | } |
| 68 | } |
| 69 | |
| 70 | #[derive(Debug, Default, Clone)] |
| 71 | pub struct InMemoryOrgRepo { |
| 72 | orgs: Arc<Mutex<HashMap<String, Organization>>>, |
| 73 | } |
| 74 | |
| 75 | impl InMemoryOrgRepo { |
| 76 | pub fn new() -> Self { |
| 77 | Self::default() |
| 78 | } |
| 79 | } |
| 80 | |
| 81 | impl OrgRepository for InMemoryOrgRepo { |
| 82 | async fn find_by_id(&self, id: &OrgId) -> RepositoryResult<Option<Organization>> { |
| 83 | let orgs = self.orgs.lock().expect("lock poisoned"); |
| 84 | Ok(orgs.get(id.as_str()).cloned()) |
| 85 | } |
| 86 | |
| 87 | async fn find_by_name(&self, name: &OrgName) -> RepositoryResult<Option<Organization>> { |
| 88 | let orgs = self.orgs.lock().expect("lock poisoned"); |
| 89 | Ok(orgs.values().find(|org| &org.name == name).cloned()) |
| 90 | } |
| 91 | |
| 92 | async fn save(&self, org: &Organization) -> RepositoryResult<()> { |
| 93 | let mut orgs = self.orgs.lock().expect("lock poisoned"); |
| 94 | orgs.insert(org.id.as_str().to_owned(), org.clone()); |
| 95 | Ok(()) |
| 96 | } |
| 97 | } |
| 98 | |
| 99 | #[derive(Debug, Default, Clone)] |
| 100 | pub struct InMemoryMembershipRepo { |
| 101 | memberships: Arc<Mutex<HashMap<String, Membership>>>, |
| 102 | } |
| 103 | |
| 104 | impl InMemoryMembershipRepo { |
| 105 | pub fn new() -> Self { |
| 106 | Self::default() |
| 107 | } |
| 108 | } |
| 109 | |
| 110 | impl MembershipRepository for InMemoryMembershipRepo { |
| 111 | async fn find(&self, org_id: &OrgId, user_id: &UserId) -> RepositoryResult<Option<Membership>> { |
| 112 | let memberships = self.memberships.lock().expect("lock poisoned"); |
| 113 | Ok(memberships |
| 114 | .values() |
| 115 | .find(|m| &m.org_id == org_id && &m.user_id == user_id) |
| 116 | .cloned()) |
| 117 | } |
| 118 | |
| 119 | async fn list_for_user(&self, user_id: &UserId) -> RepositoryResult<Vec<Membership>> { |
| 120 | let memberships = self.memberships.lock().expect("lock poisoned"); |
| 121 | Ok(memberships |
| 122 | .values() |
| 123 | .filter(|m| &m.user_id == user_id) |
| 124 | .cloned() |
| 125 | .collect()) |
| 126 | } |
| 127 | |
| 128 | async fn save(&self, membership: &Membership) -> RepositoryResult<()> { |
| 129 | let mut memberships = self.memberships.lock().expect("lock poisoned"); |
| 130 | memberships.insert(membership.id.as_str().to_owned(), membership.clone()); |
| 131 | Ok(()) |
| 132 | } |
| 133 | } |
| 134 | |
| 135 | |
| 136 | #[derive(Debug, Default, Clone)] |
| 137 | pub struct InMemoryTokenRepo { |
| 138 | tokens: Arc<Mutex<HashMap<String, PersonalAccessToken>>>, |
| 139 | } |
| 140 | |
| 141 | impl InMemoryTokenRepo { |
| 142 | pub fn new() -> Self { |
| 143 | Self::default() |
| 144 | } |
| 145 | } |
| 146 | |
| 147 | impl TokenRepository for InMemoryTokenRepo { |
| 148 | async fn find_by_hash( |
| 149 | &self, |
| 150 | hash: &TokenHash, |
| 151 | ) -> RepositoryResult<Option<PersonalAccessToken>> { |
| 152 | let tokens = self.tokens.lock().expect("lock poisoned"); |
| 153 | |
| 154 | Ok(tokens |
| 155 | .values() |
| 156 | .find(|token| token.token_hash.matches(hash)) |
| 157 | .cloned()) |
| 158 | } |
| 159 | |
| 160 | async fn list_by_user(&self, user_id: &UserId) -> RepositoryResult<Vec<PersonalAccessToken>> { |
| 161 | let tokens = self.tokens.lock().expect("lock poisoned"); |
| 162 | |
| 163 | let mut found: Vec<PersonalAccessToken> = tokens |
| 164 | .values() |
| 165 | .filter(|token| &token.user_id == user_id) |
| 166 | .cloned() |
| 167 | .collect(); |
| 168 | |
| 169 | |
| 170 | |
| 171 | found.sort_by(|a, b| { |
| 172 | b.created_at |
| 173 | .cmp(&a.created_at) |
| 174 | .then_with(|| a.id.as_str().cmp(b.id.as_str())) |
| 175 | }); |
| 176 | |
| 177 | Ok(found) |
| 178 | } |
| 179 | |
| 180 | async fn save(&self, token: &PersonalAccessToken) -> RepositoryResult<()> { |
| 181 | let mut tokens = self.tokens.lock().expect("lock poisoned"); |
| 182 | tokens.insert(token.id.as_str().to_owned(), token.clone()); |
| 183 | Ok(()) |
| 184 | } |
| 185 | |
| 186 | async fn touch_last_used(&self, id: &TokenId, at: SystemTime) -> RepositoryResult<()> { |
| 187 | let mut tokens = self.tokens.lock().expect("lock poisoned"); |
| 188 | |
| 189 | if let Some(token) = tokens.get_mut(id.as_str()) { |
| 190 | token.last_used_at = Some(at); |
| 191 | } |
| 192 | |
| 193 | Ok(()) |
| 194 | } |
| 195 | |
| 196 | async fn delete(&self, id: &TokenId) -> RepositoryResult<()> { |
| 197 | let mut tokens = self.tokens.lock().expect("lock poisoned"); |
| 198 | tokens.remove(id.as_str()); |
| 199 | Ok(()) |
| 200 | } |
| 201 | } |
| 202 | |
| 203 | |
| 204 | |
| 205 | |
| 206 | |
| 207 | |
| 208 | #[derive(Debug, Default, Clone)] |
| 209 | pub struct InMemoryIssueRepo { |
| 210 | state: Arc<Mutex<IssueStore>>, |
| 211 | } |
| 212 | |
| 213 | |
| 214 | #[derive(Debug, Default)] |
| 215 | struct IssueStore { |
| 216 | issues: HashMap<String, Issue>, |
| 217 | comments: Vec<IssueComment>, |
| 218 | |
| 219 | |
| 220 | sequences: HashMap<String, u64>, |
| 221 | } |
| 222 | |
| 223 | impl InMemoryIssueRepo { |
| 224 | pub fn new() -> Self { |
| 225 | Self::default() |
| 226 | } |
| 227 | } |
| 228 | |
| 229 | impl IssueRepository for InMemoryIssueRepo { |
| 230 | async fn next_number(&self, repo_id: &RepoId) -> RepositoryResult<IssueNumber> { |
| 231 | let mut state = self.state.lock().expect("lock poisoned"); |
| 232 | let next = state |
| 233 | .sequences |
| 234 | .entry(repo_id.as_str().to_owned()) |
| 235 | .or_insert(1); |
| 236 | let allocated = *next; |
| 237 | *next += 1; |
| 238 | |
| 239 | Ok(IssueNumber::from_trusted(allocated)) |
| 240 | } |
| 241 | |
| 242 | async fn find_by_number( |
| 243 | &self, |
| 244 | repo_id: &RepoId, |
| 245 | number: IssueNumber, |
| 246 | ) -> RepositoryResult<Option<Issue>> { |
| 247 | let state = self.state.lock().expect("lock poisoned"); |
| 248 | |
| 249 | Ok(state |
| 250 | .issues |
| 251 | .values() |
| 252 | .find(|issue| &issue.repo_id == repo_id && issue.number == number) |
| 253 | .cloned()) |
| 254 | } |
| 255 | |
| 256 | async fn list_by_repo( |
| 257 | &self, |
| 258 | repo_id: &RepoId, |
| 259 | state: IssueState, |
| 260 | offset: usize, |
| 261 | limit: usize, |
| 262 | ) -> RepositoryResult<Vec<Issue>> { |
| 263 | let held = self.state.lock().expect("lock poisoned"); |
| 264 | |
| 265 | let mut found: Vec<Issue> = held |
| 266 | .issues |
| 267 | .values() |
| 268 | .filter(|issue| &issue.repo_id == repo_id && issue.state == state) |
| 269 | .cloned() |
| 270 | .collect(); |
| 271 | |
| 272 | |
| 273 | |
| 274 | found.sort_by_key(|issue| std::cmp::Reverse(issue.number)); |
| 275 | |
| 276 | Ok(found.into_iter().skip(offset).take(limit).collect()) |
| 277 | } |
| 278 | |
| 279 | async fn counts(&self, repo_id: &RepoId) -> RepositoryResult<IssueCounts> { |
| 280 | let state = self.state.lock().expect("lock poisoned"); |
| 281 | let mut counts = IssueCounts::default(); |
| 282 | |
| 283 | for issue in state.issues.values().filter(|i| &i.repo_id == repo_id) { |
| 284 | match issue.state { |
| 285 | IssueState::Open => counts.open += 1, |
| 286 | IssueState::Closed => counts.closed += 1, |
| 287 | } |
| 288 | } |
| 289 | |
| 290 | Ok(counts) |
| 291 | } |
| 292 | |
| 293 | async fn comment_counts(&self, repo_id: &RepoId) -> RepositoryResult<Vec<(IssueId, u64)>> { |
| 294 | let state = self.state.lock().expect("lock poisoned"); |
| 295 | |
| 296 | Ok(state |
| 297 | .issues |
| 298 | .values() |
| 299 | .filter(|issue| &issue.repo_id == repo_id) |
| 300 | .map(|issue| { |
| 301 | let total = state |
| 302 | .comments |
| 303 | .iter() |
| 304 | .filter(|comment| comment.issue_id == issue.id) |
| 305 | .count() as u64; |
| 306 | |
| 307 | (issue.id.clone(), total) |
| 308 | }) |
| 309 | .collect()) |
| 310 | } |
| 311 | |
| 312 | async fn save(&self, issue: &Issue) -> RepositoryResult<()> { |
| 313 | let mut state = self.state.lock().expect("lock poisoned"); |
| 314 | state |
| 315 | .issues |
| 316 | .insert(issue.id.as_str().to_owned(), issue.clone()); |
| 317 | Ok(()) |
| 318 | } |
| 319 | |
| 320 | async fn list_comments(&self, issue_id: &IssueId) -> RepositoryResult<Vec<IssueComment>> { |
| 321 | let state = self.state.lock().expect("lock poisoned"); |
| 322 | |
| 323 | let mut found: Vec<IssueComment> = state |
| 324 | .comments |
| 325 | .iter() |
| 326 | .filter(|comment| &comment.issue_id == issue_id) |
| 327 | .cloned() |
| 328 | .collect(); |
| 329 | |
| 330 | |
| 331 | |
| 332 | |
| 333 | found.sort_by_key(|comment| comment.created_at); |
| 334 | |
| 335 | Ok(found) |
| 336 | } |
| 337 | |
| 338 | async fn add_comment(&self, comment: &IssueComment) -> RepositoryResult<()> { |
| 339 | let mut state = self.state.lock().expect("lock poisoned"); |
| 340 | state.comments.push(comment.clone()); |
| 341 | Ok(()) |
| 342 | } |
| 343 | } |
| 344 | |
| 345 | |
| 346 | #[derive(Debug, Default, Clone)] |
| 347 | pub struct InMemoryPushEventRepo { |
| 348 | events: Arc<Mutex<HashMap<String, PushEvent>>>, |
| 349 | } |
| 350 | |
| 351 | impl InMemoryPushEventRepo { |
| 352 | pub fn new() -> Self { |
| 353 | Self::default() |
| 354 | } |
| 355 | } |
| 356 | |
| 357 | impl PushEventRepository for InMemoryPushEventRepo { |
| 358 | async fn find(&self, id: &PushEventId) -> RepositoryResult<Option<PushEvent>> { |
| 359 | let events = self.events.lock().expect("lock poisoned"); |
| 360 | Ok(events.get(id.as_str()).cloned()) |
| 361 | } |
| 362 | |
| 363 | async fn list_by_repo( |
| 364 | &self, |
| 365 | repo_id: &RepoId, |
| 366 | limit: usize, |
| 367 | ) -> RepositoryResult<Vec<PushEvent>> { |
| 368 | let events = self.events.lock().expect("lock poisoned"); |
| 369 | |
| 370 | let mut found: Vec<PushEvent> = events |
| 371 | .values() |
| 372 | .filter(|event| &event.repo_id == repo_id) |
| 373 | .cloned() |
| 374 | .collect(); |
| 375 | |
| 376 | found.sort_by(|a, b| { |
| 377 | b.created_at |
| 378 | .cmp(&a.created_at) |
| 379 | .then_with(|| a.id.as_str().cmp(b.id.as_str())) |
| 380 | }); |
| 381 | found.truncate(limit); |
| 382 | |
| 383 | Ok(found) |
| 384 | } |
| 385 | |
| 386 | async fn list_recent( |
| 387 | &self, |
| 388 | repo_ids: &[RepoId], |
| 389 | limit: usize, |
| 390 | ) -> RepositoryResult<Vec<PushEvent>> { |
| 391 | let events = self.events.lock().expect("lock poisoned"); |
| 392 | |
| 393 | let mut found: Vec<PushEvent> = events |
| 394 | .values() |
| 395 | .filter(|event| repo_ids.contains(&event.repo_id)) |
| 396 | .cloned() |
| 397 | .collect(); |
| 398 | |
| 399 | |
| 400 | |
| 401 | |
| 402 | found.sort_by(|a, b| { |
| 403 | b.created_at |
| 404 | .cmp(&a.created_at) |
| 405 | .then_with(|| a.id.as_str().cmp(b.id.as_str())) |
| 406 | }); |
| 407 | found.truncate(limit); |
| 408 | |
| 409 | Ok(found) |
| 410 | } |
| 411 | |
| 412 | async fn save(&self, event: &PushEvent) -> RepositoryResult<()> { |
| 413 | let mut events = self.events.lock().expect("lock poisoned"); |
| 414 | events.insert(event.id.as_str().to_owned(), event.clone()); |
| 415 | Ok(()) |
| 416 | } |
| 417 | } |
| 418 | |
| 419 | #[derive(Debug, Default, Clone)] |
| 420 | pub struct InMemoryWebhookRepo { |
| 421 | webhooks: Arc<Mutex<HashMap<String, Webhook>>>, |
| 422 | } |
| 423 | |
| 424 | impl InMemoryWebhookRepo { |
| 425 | pub fn new() -> Self { |
| 426 | Self::default() |
| 427 | } |
| 428 | } |
| 429 | |
| 430 | impl WebhookRepository for InMemoryWebhookRepo { |
| 431 | async fn find(&self, id: &WebhookId) -> RepositoryResult<Option<Webhook>> { |
| 432 | let webhooks = self.webhooks.lock().expect("lock poisoned"); |
| 433 | Ok(webhooks.get(id.as_str()).cloned()) |
| 434 | } |
| 435 | |
| 436 | async fn list_by_repo(&self, repo_id: &RepoId) -> RepositoryResult<Vec<Webhook>> { |
| 437 | let webhooks = self.webhooks.lock().expect("lock poisoned"); |
| 438 | |
| 439 | let mut found: Vec<Webhook> = webhooks |
| 440 | .values() |
| 441 | .filter(|webhook| &webhook.repo_id == repo_id) |
| 442 | .cloned() |
| 443 | .collect(); |
| 444 | |
| 445 | |
| 446 | |
| 447 | found.sort_by(|a, b| { |
| 448 | a.created_at |
| 449 | .cmp(&b.created_at) |
| 450 | .then_with(|| a.id.as_str().cmp(b.id.as_str())) |
| 451 | }); |
| 452 | |
| 453 | Ok(found) |
| 454 | } |
| 455 | |
| 456 | async fn save(&self, webhook: &Webhook) -> RepositoryResult<()> { |
| 457 | let mut webhooks = self.webhooks.lock().expect("lock poisoned"); |
| 458 | webhooks.insert(webhook.id.as_str().to_owned(), webhook.clone()); |
| 459 | Ok(()) |
| 460 | } |
| 461 | |
| 462 | async fn delete(&self, id: &WebhookId) -> RepositoryResult<()> { |
| 463 | let mut webhooks = self.webhooks.lock().expect("lock poisoned"); |
| 464 | webhooks.remove(id.as_str()); |
| 465 | Ok(()) |
| 466 | } |
| 467 | } |
| 468 | |
| 469 | #[derive(Debug, Default, Clone)] |
| 470 | pub struct InMemoryWebhookDeliveryRepo { |
| 471 | deliveries: Arc<Mutex<HashMap<String, WebhookDelivery>>>, |
| 472 | } |
| 473 | |
| 474 | impl InMemoryWebhookDeliveryRepo { |
| 475 | pub fn new() -> Self { |
| 476 | Self::default() |
| 477 | } |
| 478 | |
| 479 | fn sorted(&self, webhook_id: &WebhookId) -> Vec<WebhookDelivery> { |
| 480 | let deliveries = self.deliveries.lock().expect("lock poisoned"); |
| 481 | |
| 482 | let mut found: Vec<WebhookDelivery> = deliveries |
| 483 | .values() |
| 484 | .filter(|delivery| &delivery.webhook_id == webhook_id) |
| 485 | .cloned() |
| 486 | .collect(); |
| 487 | |
| 488 | found.sort_by(|a, b| { |
| 489 | b.delivered_at |
| 490 | .cmp(&a.delivered_at) |
| 491 | .then_with(|| b.attempt.cmp(&a.attempt)) |
| 492 | }); |
| 493 | |
| 494 | found |
| 495 | } |
| 496 | } |
| 497 | |
| 498 | impl WebhookDeliveryRepository for InMemoryWebhookDeliveryRepo { |
| 499 | async fn list_by_webhook( |
| 500 | &self, |
| 501 | webhook_id: &WebhookId, |
| 502 | offset: usize, |
| 503 | limit: usize, |
| 504 | ) -> RepositoryResult<Vec<WebhookDelivery>> { |
| 505 | Ok(self |
| 506 | .sorted(webhook_id) |
| 507 | .into_iter() |
| 508 | .skip(offset) |
| 509 | .take(limit) |
| 510 | .collect()) |
| 511 | } |
| 512 | |
| 513 | async fn count_by_webhook(&self, webhook_id: &WebhookId) -> RepositoryResult<usize> { |
| 514 | Ok(self.sorted(webhook_id).len()) |
| 515 | } |
| 516 | |
| 517 | async fn latest_by_webhook( |
| 518 | &self, |
| 519 | webhook_id: &WebhookId, |
| 520 | ) -> RepositoryResult<Option<WebhookDelivery>> { |
| 521 | Ok(self.sorted(webhook_id).into_iter().next()) |
| 522 | } |
| 523 | |
| 524 | async fn save(&self, delivery: &WebhookDelivery) -> RepositoryResult<()> { |
| 525 | let mut deliveries = self.deliveries.lock().expect("lock poisoned"); |
| 526 | deliveries.insert(delivery.id.as_str().to_owned(), delivery.clone()); |
| 527 | Ok(()) |
| 528 | } |
| 529 | } |
| 530 | |
| 531 | |
| 532 | |
| 533 | |
| 534 | |
| 535 | |
| 536 | #[derive(Debug, Default, Clone)] |
| 537 | pub struct InMemoryLabelRepo { |
| 538 | state: Arc<Mutex<LabelStore>>, |
| 539 | } |
| 540 | |
| 541 | |
| 542 | #[derive(Debug, Default)] |
| 543 | struct LabelStore { |
| 544 | labels: HashMap<String, Label>, |
| 545 | |
| 546 | |
| 547 | assigned: HashSet<(String, String)>, |
| 548 | |
| 549 | |
| 550 | assigned_pulls: HashSet<(String, String)>, |
| 551 | } |
| 552 | |
| 553 | impl InMemoryLabelRepo { |
| 554 | pub fn new() -> Self { |
| 555 | Self::default() |
| 556 | } |
| 557 | } |
| 558 | |
| 559 | |
| 560 | fn by_name(mut labels: Vec<Label>) -> Vec<Label> { |
| 561 | labels.sort_by(|left, right| left.name.cmp(&right.name)); |
| 562 | labels |
| 563 | } |
| 564 | |
| 565 | impl LabelRepository for InMemoryLabelRepo { |
| 566 | async fn list_by_repo(&self, repo_id: &RepoId) -> RepositoryResult<Vec<Label>> { |
| 567 | let state = self.state.lock().expect("lock poisoned"); |
| 568 | |
| 569 | Ok(by_name( |
| 570 | state |
| 571 | .labels |
| 572 | .values() |
| 573 | .filter(|label| &label.repo_id == repo_id) |
| 574 | .cloned() |
| 575 | .collect(), |
| 576 | )) |
| 577 | } |
| 578 | |
| 579 | async fn find_by_id(&self, id: &LabelId) -> RepositoryResult<Option<Label>> { |
| 580 | let state = self.state.lock().expect("lock poisoned"); |
| 581 | Ok(state.labels.get(id.as_str()).cloned()) |
| 582 | } |
| 583 | |
| 584 | async fn find_by_name(&self, repo_id: &RepoId, name: &str) -> RepositoryResult<Option<Label>> { |
| 585 | let state = self.state.lock().expect("lock poisoned"); |
| 586 | |
| 587 | Ok(state |
| 588 | .labels |
| 589 | .values() |
| 590 | .find(|label| &label.repo_id == repo_id && label.name == name) |
| 591 | .cloned()) |
| 592 | } |
| 593 | |
| 594 | async fn save(&self, label: &Label) -> RepositoryResult<()> { |
| 595 | let mut state = self.state.lock().expect("lock poisoned"); |
| 596 | state |
| 597 | .labels |
| 598 | .insert(label.id.as_str().to_owned(), label.clone()); |
| 599 | Ok(()) |
| 600 | } |
| 601 | |
| 602 | async fn delete(&self, id: &LabelId) -> RepositoryResult<()> { |
| 603 | let mut state = self.state.lock().expect("lock poisoned"); |
| 604 | |
| 605 | state.labels.remove(id.as_str()); |
| 606 | |
| 607 | |
| 608 | state.assigned.retain(|(_, label)| label != id.as_str()); |
| 609 | state |
| 610 | .assigned_pulls |
| 611 | .retain(|(_, label)| label != id.as_str()); |
| 612 | |
| 613 | Ok(()) |
| 614 | } |
| 615 | |
| 616 | async fn labels_for_issue(&self, issue_id: &IssueId) -> RepositoryResult<Vec<Label>> { |
| 617 | let state = self.state.lock().expect("lock poisoned"); |
| 618 | |
| 619 | Ok(by_name( |
| 620 | state |
| 621 | .assigned |
| 622 | .iter() |
| 623 | .filter(|(issue, _)| issue == issue_id.as_str()) |
| 624 | .filter_map(|(_, label)| state.labels.get(label).cloned()) |
| 625 | .collect(), |
| 626 | )) |
| 627 | } |
| 628 | |
| 629 | async fn labels_for_repo(&self, repo_id: &RepoId) -> RepositoryResult<Vec<(IssueId, Label)>> { |
| 630 | let state = self.state.lock().expect("lock poisoned"); |
| 631 | |
| 632 | let mut pairs: Vec<(IssueId, Label)> = state |
| 633 | .assigned |
| 634 | .iter() |
| 635 | .filter_map(|(issue, label)| { |
| 636 | let label = state.labels.get(label)?; |
| 637 | |
| 638 | (&label.repo_id == repo_id) |
| 639 | .then(|| (IssueId::from_trusted(issue.clone()), label.clone())) |
| 640 | }) |
| 641 | .collect(); |
| 642 | |
| 643 | |
| 644 | |
| 645 | pairs.sort_by(|left, right| { |
| 646 | left.0 |
| 647 | .cmp(&right.0) |
| 648 | .then_with(|| left.1.name.cmp(&right.1.name)) |
| 649 | }); |
| 650 | |
| 651 | Ok(pairs) |
| 652 | } |
| 653 | |
| 654 | async fn issue_counts(&self, repo_id: &RepoId) -> RepositoryResult<Vec<(LabelId, u64)>> { |
| 655 | let state = self.state.lock().expect("lock poisoned"); |
| 656 | |
| 657 | Ok(state |
| 658 | .labels |
| 659 | .values() |
| 660 | .filter(|label| &label.repo_id == repo_id) |
| 661 | .map(|label| { |
| 662 | let total = state |
| 663 | .assigned |
| 664 | .iter() |
| 665 | .filter(|(_, assigned)| assigned == label.id.as_str()) |
| 666 | .count() as u64; |
| 667 | |
| 668 | (label.id.clone(), total) |
| 669 | }) |
| 670 | .collect()) |
| 671 | } |
| 672 | |
| 673 | async fn set_issue_labels( |
| 674 | &self, |
| 675 | issue_id: &IssueId, |
| 676 | labels: &[LabelId], |
| 677 | ) -> RepositoryResult<()> { |
| 678 | let mut state = self.state.lock().expect("lock poisoned"); |
| 679 | |
| 680 | state |
| 681 | .assigned |
| 682 | .retain(|(issue, _)| issue != issue_id.as_str()); |
| 683 | |
| 684 | for label in labels { |
| 685 | state |
| 686 | .assigned |
| 687 | .insert((issue_id.as_str().to_owned(), label.as_str().to_owned())); |
| 688 | } |
| 689 | |
| 690 | Ok(()) |
| 691 | } |
| 692 | |
| 693 | async fn labels_for_pull(&self, pull_id: &PullRequestId) -> RepositoryResult<Vec<Label>> { |
| 694 | let state = self.state.lock().expect("lock poisoned"); |
| 695 | |
| 696 | Ok(by_name( |
| 697 | state |
| 698 | .assigned_pulls |
| 699 | .iter() |
| 700 | .filter(|(pull, _)| pull == pull_id.as_str()) |
| 701 | .filter_map(|(_, label)| state.labels.get(label).cloned()) |
| 702 | .collect(), |
| 703 | )) |
| 704 | } |
| 705 | |
| 706 | async fn labels_for_repo_pulls( |
| 707 | &self, |
| 708 | repo_id: &RepoId, |
| 709 | ) -> RepositoryResult<Vec<(PullRequestId, Label)>> { |
| 710 | let state = self.state.lock().expect("lock poisoned"); |
| 711 | |
| 712 | let mut pairs: Vec<(PullRequestId, Label)> = state |
| 713 | .assigned_pulls |
| 714 | .iter() |
| 715 | .filter_map(|(pull, label)| { |
| 716 | let label = state.labels.get(label)?; |
| 717 | |
| 718 | (&label.repo_id == repo_id) |
| 719 | .then(|| (PullRequestId::from_trusted(pull.clone()), label.clone())) |
| 720 | }) |
| 721 | .collect(); |
| 722 | |
| 723 | pairs.sort_by(|left, right| { |
| 724 | left.0 |
| 725 | .cmp(&right.0) |
| 726 | .then_with(|| left.1.name.cmp(&right.1.name)) |
| 727 | }); |
| 728 | |
| 729 | Ok(pairs) |
| 730 | } |
| 731 | |
| 732 | async fn pull_counts(&self, repo_id: &RepoId) -> RepositoryResult<Vec<(LabelId, u64)>> { |
| 733 | let state = self.state.lock().expect("lock poisoned"); |
| 734 | |
| 735 | Ok(state |
| 736 | .labels |
| 737 | .values() |
| 738 | .filter(|label| &label.repo_id == repo_id) |
| 739 | .map(|label| { |
| 740 | let total = state |
| 741 | .assigned_pulls |
| 742 | .iter() |
| 743 | .filter(|(_, assigned)| assigned == label.id.as_str()) |
| 744 | .count() as u64; |
| 745 | |
| 746 | (label.id.clone(), total) |
| 747 | }) |
| 748 | .collect()) |
| 749 | } |
| 750 | |
| 751 | async fn set_pull_labels( |
| 752 | &self, |
| 753 | pull_id: &PullRequestId, |
| 754 | labels: &[LabelId], |
| 755 | ) -> RepositoryResult<()> { |
| 756 | let mut state = self.state.lock().expect("lock poisoned"); |
| 757 | |
| 758 | state |
| 759 | .assigned_pulls |
| 760 | .retain(|(pull, _)| pull != pull_id.as_str()); |
| 761 | |
| 762 | for label in labels { |
| 763 | state |
| 764 | .assigned_pulls |
| 765 | .insert((pull_id.as_str().to_owned(), label.as_str().to_owned())); |
| 766 | } |
| 767 | |
| 768 | Ok(()) |
| 769 | } |
| 770 | } |
| 771 | |
| 772 | |
| 773 | |
| 774 | |
| 775 | |
| 776 | |
| 777 | |
| 778 | #[derive(Debug, Default, Clone)] |
| 779 | pub struct InMemoryPullRequestRepo { |
| 780 | state: Arc<Mutex<PullRequestStore>>, |
| 781 | } |
| 782 | |
| 783 | #[derive(Debug, Default)] |
| 784 | struct PullRequestStore { |
| 785 | pulls: HashMap<String, PullRequest>, |
| 786 | comments: Vec<PullRequestComment>, |
| 787 | } |
| 788 | |
| 789 | impl InMemoryPullRequestRepo { |
| 790 | pub fn new() -> Self { |
| 791 | Self::default() |
| 792 | } |
| 793 | } |
| 794 | |
| 795 | impl PullRequestRepository for InMemoryPullRequestRepo { |
| 796 | async fn find_by_number( |
| 797 | &self, |
| 798 | repo_id: &RepoId, |
| 799 | number: IssueNumber, |
| 800 | ) -> RepositoryResult<Option<PullRequest>> { |
| 801 | let state = self.state.lock().expect("lock poisoned"); |
| 802 | |
| 803 | Ok(state |
| 804 | .pulls |
| 805 | .values() |
| 806 | .find(|pull| &pull.repo_id == repo_id && pull.number == number) |
| 807 | .cloned()) |
| 808 | } |
| 809 | |
| 810 | async fn list_by_repo( |
| 811 | &self, |
| 812 | repo_id: &RepoId, |
| 813 | state: PullRequestState, |
| 814 | offset: usize, |
| 815 | limit: usize, |
| 816 | ) -> RepositoryResult<Vec<PullRequest>> { |
| 817 | let held = self.state.lock().expect("lock poisoned"); |
| 818 | |
| 819 | let mut found: Vec<PullRequest> = held |
| 820 | .pulls |
| 821 | .values() |
| 822 | .filter(|pull| &pull.repo_id == repo_id && pull.state == state) |
| 823 | .cloned() |
| 824 | .collect(); |
| 825 | |
| 826 | |
| 827 | |
| 828 | found.sort_by_key(|pull| std::cmp::Reverse(pull.number)); |
| 829 | |
| 830 | Ok(found.into_iter().skip(offset).take(limit).collect()) |
| 831 | } |
| 832 | |
| 833 | async fn counts(&self, repo_id: &RepoId) -> RepositoryResult<PullRequestCounts> { |
| 834 | let state = self.state.lock().expect("lock poisoned"); |
| 835 | let mut counts = PullRequestCounts::default(); |
| 836 | |
| 837 | for pull in state.pulls.values().filter(|p| &p.repo_id == repo_id) { |
| 838 | match pull.state { |
| 839 | PullRequestState::Open => counts.open += 1, |
| 840 | PullRequestState::Merged => counts.merged += 1, |
| 841 | PullRequestState::Closed => counts.closed += 1, |
| 842 | } |
| 843 | } |
| 844 | |
| 845 | Ok(counts) |
| 846 | } |
| 847 | |
| 848 | async fn comment_counts( |
| 849 | &self, |
| 850 | repo_id: &RepoId, |
| 851 | ) -> RepositoryResult<Vec<(PullRequestId, u64)>> { |
| 852 | let state = self.state.lock().expect("lock poisoned"); |
| 853 | |
| 854 | Ok(state |
| 855 | .pulls |
| 856 | .values() |
| 857 | .filter(|pull| &pull.repo_id == repo_id) |
| 858 | .map(|pull| { |
| 859 | let total = state |
| 860 | .comments |
| 861 | .iter() |
| 862 | .filter(|comment| comment.pull_request_id == pull.id) |
| 863 | .count() as u64; |
| 864 | |
| 865 | (pull.id.clone(), total) |
| 866 | }) |
| 867 | .collect()) |
| 868 | } |
| 869 | |
| 870 | async fn save(&self, pull: &PullRequest) -> RepositoryResult<()> { |
| 871 | let mut state = self.state.lock().expect("lock poisoned"); |
| 872 | state |
| 873 | .pulls |
| 874 | .insert(pull.id.as_str().to_owned(), pull.clone()); |
| 875 | Ok(()) |
| 876 | } |
| 877 | |
| 878 | async fn list_comments( |
| 879 | &self, |
| 880 | pull_request_id: &PullRequestId, |
| 881 | ) -> RepositoryResult<Vec<PullRequestComment>> { |
| 882 | let state = self.state.lock().expect("lock poisoned"); |
| 883 | |
| 884 | let mut found: Vec<PullRequestComment> = state |
| 885 | .comments |
| 886 | .iter() |
| 887 | .filter(|comment| &comment.pull_request_id == pull_request_id) |
| 888 | .cloned() |
| 889 | .collect(); |
| 890 | |
| 891 | |
| 892 | |
| 893 | found.sort_by_key(|comment| comment.created_at); |
| 894 | |
| 895 | Ok(found) |
| 896 | } |
| 897 | |
| 898 | async fn add_comment(&self, comment: &PullRequestComment) -> RepositoryResult<()> { |
| 899 | let mut state = self.state.lock().expect("lock poisoned"); |
| 900 | state.comments.push(comment.clone()); |
| 901 | Ok(()) |
| 902 | } |
| 903 | } |
| 904 | |
| 905 | #[cfg(test)] |
| 906 | mod tests { |
| 907 | use std::time::Duration; |
| 908 | |
| 909 | use super::*; |
| 910 | |
| 911 | fn at(seconds: u64) -> SystemTime { |
| 912 | SystemTime::UNIX_EPOCH + Duration::from_secs(seconds) |
| 913 | } |
| 914 | use crate::domain::{IssueCommentId, MembershipId, PasswordHash, Role}; |
| 915 | |
| 916 | fn user(email: &str, org_id: &OrgId) -> User { |
| 917 | User::new( |
| 918 | UserId::generate(), |
| 919 | Email::new(email).expect("valid email"), |
| 920 | PasswordHash::from_trusted("$argon2id$test"), |
| 921 | org_id.clone(), |
| 922 | ) |
| 923 | } |
| 924 | |
| 925 | #[tokio::test] |
| 926 | async fn in_memory_the_second_page_of_deliveries_starts_where_the_first_ended() { |
| 927 | use crate::domain::{PushEventId, WebhookDelivery, WebhookDeliveryId, WebhookId}; |
| 928 | |
| 929 | let deliveries = InMemoryWebhookDeliveryRepo::new(); |
| 930 | let hook = WebhookId::generate(); |
| 931 | let event = PushEventId::generate(); |
| 932 | |
| 933 | for attempt in 1..=4u32 { |
| 934 | deliveries |
| 935 | .save(&WebhookDelivery::record( |
| 936 | WebhookDeliveryId::generate(), |
| 937 | hook.clone(), |
| 938 | event.clone(), |
| 939 | attempt, |
| 940 | Some(200), |
| 941 | "ok", |
| 942 | 12, |
| 943 | at(1_000 + u64::from(attempt)), |
| 944 | )) |
| 945 | .await |
| 946 | .expect("save"); |
| 947 | } |
| 948 | |
| 949 | let first = deliveries.list_by_webhook(&hook, 0, 2).await.expect("list"); |
| 950 | let second = deliveries.list_by_webhook(&hook, 2, 2).await.expect("list"); |
| 951 | |
| 952 | |
| 953 | assert_eq!( |
| 954 | first.iter().map(|d| d.attempt).collect::<Vec<_>>(), |
| 955 | vec![4, 3] |
| 956 | ); |
| 957 | assert_eq!( |
| 958 | second.iter().map(|d| d.attempt).collect::<Vec<_>>(), |
| 959 | vec![2, 1] |
| 960 | ); |
| 961 | assert_eq!(deliveries.count_by_webhook(&hook).await.expect("count"), 4); |
| 962 | assert!( |
| 963 | deliveries |
| 964 | .list_by_webhook(&hook, 500, 2) |
| 965 | .await |
| 966 | .expect("list") |
| 967 | .is_empty(), |
| 968 | "an offset past the end is an empty page" |
| 969 | ); |
| 970 | } |
| 971 | |
| 972 | #[tokio::test] |
| 973 | async fn users_are_found_by_id_and_email() { |
| 974 | let repo = InMemoryUserRepo::new(); |
| 975 | let org_id = OrgId::generate(); |
| 976 | let user = user("dev@example.com", &org_id); |
| 977 | repo.save(&user).await.expect("save"); |
| 978 | |
| 979 | let by_id = repo.find_by_id(&user.id).await.expect("lookup"); |
| 980 | let by_email = repo.find_by_email(&user.email).await.expect("lookup"); |
| 981 | |
| 982 | assert_eq!(by_id.as_ref(), Some(&user)); |
| 983 | assert_eq!(by_email.as_ref(), Some(&user)); |
| 984 | } |
| 985 | |
| 986 | #[tokio::test] |
| 987 | async fn missing_users_are_none_not_an_error() { |
| 988 | let repo = InMemoryUserRepo::new(); |
| 989 | |
| 990 | let found = repo.find_by_id(&UserId::generate()).await.expect("lookup"); |
| 991 | |
| 992 | assert_eq!(found, None); |
| 993 | } |
| 994 | |
| 995 | #[tokio::test] |
| 996 | async fn saving_the_same_id_replaces_rather_than_duplicates() { |
| 997 | let repo = InMemoryUserRepo::new(); |
| 998 | let org_id = OrgId::generate(); |
| 999 | let mut user = user("dev@example.com", &org_id); |
| 1000 | repo.save(&user).await.expect("save"); |
| 1001 | |
| 1002 | user.email = Email::new("changed@example.com").expect("valid email"); |
| 1003 | repo.save(&user).await.expect("save"); |
| 1004 | |
| 1005 | assert_eq!( |
| 1006 | repo.find_by_email(&Email::new("dev@example.com").unwrap()) |
| 1007 | .await |
| 1008 | .expect("lookup"), |
| 1009 | None |
| 1010 | ); |
| 1011 | assert!(repo.any_exist().await.expect("any_exist")); |
| 1012 | } |
| 1013 | |
| 1014 | #[tokio::test] |
| 1015 | async fn any_exist_reports_emptiness() { |
| 1016 | let repo = InMemoryUserRepo::new(); |
| 1017 | assert!(!repo.any_exist().await.expect("any_exist")); |
| 1018 | |
| 1019 | repo.save(&user("dev@example.com", &OrgId::generate())) |
| 1020 | .await |
| 1021 | .expect("save"); |
| 1022 | |
| 1023 | assert!(repo.any_exist().await.expect("any_exist")); |
| 1024 | } |
| 1025 | |
| 1026 | #[tokio::test] |
| 1027 | async fn clones_share_storage() { |
| 1028 | let repo = InMemoryUserRepo::new(); |
| 1029 | let clone = repo.clone(); |
| 1030 | |
| 1031 | clone |
| 1032 | .save(&user("dev@example.com", &OrgId::generate())) |
| 1033 | .await |
| 1034 | .expect("save"); |
| 1035 | |
| 1036 | assert!(repo.any_exist().await.expect("any_exist")); |
| 1037 | } |
| 1038 | |
| 1039 | #[tokio::test] |
| 1040 | async fn orgs_are_found_by_id_and_name() { |
| 1041 | let repo = InMemoryOrgRepo::new(); |
| 1042 | let org = Organization::new(OrgId::generate(), "acme", None).expect("valid org"); |
| 1043 | repo.save(&org).await.expect("save"); |
| 1044 | |
| 1045 | assert_eq!( |
| 1046 | repo.find_by_id(&org.id).await.expect("lookup").as_ref(), |
| 1047 | Some(&org) |
| 1048 | ); |
| 1049 | assert_eq!( |
| 1050 | repo.find_by_name(&org.name).await.expect("lookup").as_ref(), |
| 1051 | Some(&org) |
| 1052 | ); |
| 1053 | } |
| 1054 | |
| 1055 | #[tokio::test] |
| 1056 | async fn org_lookup_by_name_respects_normalisation() { |
| 1057 | let repo = InMemoryOrgRepo::new(); |
| 1058 | let org = Organization::new(OrgId::generate(), "Acme", None).expect("valid org"); |
| 1059 | repo.save(&org).await.expect("save"); |
| 1060 | |
| 1061 | let found = repo |
| 1062 | .find_by_name(&OrgName::new("ACME").expect("valid")) |
| 1063 | .await |
| 1064 | .expect("lookup"); |
| 1065 | |
| 1066 | assert_eq!(found.as_ref(), Some(&org)); |
| 1067 | } |
| 1068 | |
| 1069 | #[tokio::test] |
| 1070 | async fn memberships_are_found_by_org_and_user() { |
| 1071 | let repo = InMemoryMembershipRepo::new(); |
| 1072 | let org_id = OrgId::generate(); |
| 1073 | let user_id = UserId::generate(); |
| 1074 | let membership = Membership::new( |
| 1075 | MembershipId::generate(), |
| 1076 | org_id.clone(), |
| 1077 | user_id.clone(), |
| 1078 | Role::Owner, |
| 1079 | ); |
| 1080 | repo.save(&membership).await.expect("save"); |
| 1081 | |
| 1082 | let found = repo.find(&org_id, &user_id).await.expect("lookup"); |
| 1083 | |
| 1084 | assert_eq!(found.as_ref(), Some(&membership)); |
| 1085 | } |
| 1086 | |
| 1087 | #[tokio::test] |
| 1088 | async fn membership_lookup_does_not_match_a_different_user() { |
| 1089 | let repo = InMemoryMembershipRepo::new(); |
| 1090 | let org_id = OrgId::generate(); |
| 1091 | repo.save(&Membership::new( |
| 1092 | MembershipId::generate(), |
| 1093 | org_id.clone(), |
| 1094 | UserId::generate(), |
| 1095 | Role::Owner, |
| 1096 | )) |
| 1097 | .await |
| 1098 | .expect("save"); |
| 1099 | |
| 1100 | let found = repo |
| 1101 | .find(&org_id, &UserId::generate()) |
| 1102 | .await |
| 1103 | .expect("lookup"); |
| 1104 | |
| 1105 | assert_eq!(found, None); |
| 1106 | } |
| 1107 | |
| 1108 | #[tokio::test] |
| 1109 | async fn list_for_user_returns_only_that_users_memberships() { |
| 1110 | let repo = InMemoryMembershipRepo::new(); |
| 1111 | let user_id = UserId::generate(); |
| 1112 | for _ in 0..2 { |
| 1113 | repo.save(&Membership::new( |
| 1114 | MembershipId::generate(), |
| 1115 | OrgId::generate(), |
| 1116 | user_id.clone(), |
| 1117 | Role::Member, |
| 1118 | )) |
| 1119 | .await |
| 1120 | .expect("save"); |
| 1121 | } |
| 1122 | repo.save(&Membership::new( |
| 1123 | MembershipId::generate(), |
| 1124 | OrgId::generate(), |
| 1125 | UserId::generate(), |
| 1126 | Role::Owner, |
| 1127 | )) |
| 1128 | .await |
| 1129 | .expect("save"); |
| 1130 | |
| 1131 | let found = repo.list_for_user(&user_id).await.expect("lookup"); |
| 1132 | |
| 1133 | assert_eq!(found.len(), 2); |
| 1134 | assert!(found.iter().all(|m| m.user_id == user_id)); |
| 1135 | } |
| 1136 | |
| 1137 | |
| 1138 | use crate::domain::{TokenLifetime, TokenSecret}; |
| 1139 | |
| 1140 | fn token_for(user: &UserId, name: &str, at: u64) -> (PersonalAccessToken, TokenSecret) { |
| 1141 | use std::time::Duration; |
| 1142 | |
| 1143 | let secret = TokenSecret::generate(); |
| 1144 | let token = PersonalAccessToken::new( |
| 1145 | TokenId::generate(), |
| 1146 | user.clone(), |
| 1147 | name, |
| 1148 | &secret, |
| 1149 | SystemTime::UNIX_EPOCH + Duration::from_secs(at), |
| 1150 | TokenLifetime::default(), |
| 1151 | ) |
| 1152 | .expect("valid token"); |
| 1153 | |
| 1154 | (token, secret) |
| 1155 | } |
| 1156 | |
| 1157 | #[tokio::test] |
| 1158 | async fn the_fake_finds_a_token_by_its_hash() { |
| 1159 | let tokens = InMemoryTokenRepo::new(); |
| 1160 | let user = UserId::generate(); |
| 1161 | let (token, secret) = token_for(&user, "laptop", 1_000); |
| 1162 | tokens.save(&token).await.expect("save"); |
| 1163 | |
| 1164 | assert_eq!( |
| 1165 | tokens.find_by_hash(&secret.hash()).await.expect("lookup"), |
| 1166 | Some(token) |
| 1167 | ); |
| 1168 | assert_eq!( |
| 1169 | tokens |
| 1170 | .find_by_hash(&TokenSecret::generate().hash()) |
| 1171 | .await |
| 1172 | .expect("lookup"), |
| 1173 | None |
| 1174 | ); |
| 1175 | } |
| 1176 | |
| 1177 | #[tokio::test] |
| 1178 | async fn the_fake_lists_newest_first_for_one_user_only() { |
| 1179 | |
| 1180 | |
| 1181 | let tokens = InMemoryTokenRepo::new(); |
| 1182 | let user = UserId::generate(); |
| 1183 | let other = UserId::generate(); |
| 1184 | |
| 1185 | for (owner, name, at) in [ |
| 1186 | (&user, "old", 1_000), |
| 1187 | (&user, "new", 3_000), |
| 1188 | (&user, "middle", 2_000), |
| 1189 | (&other, "theirs", 4_000), |
| 1190 | ] { |
| 1191 | let (token, _) = token_for(owner, name, at); |
| 1192 | tokens.save(&token).await.expect("save"); |
| 1193 | } |
| 1194 | |
| 1195 | assert_eq!( |
| 1196 | tokens |
| 1197 | .list_by_user(&user) |
| 1198 | .await |
| 1199 | .expect("list") |
| 1200 | .iter() |
| 1201 | .map(|token| token.name.as_str()) |
| 1202 | .collect::<Vec<_>>(), |
| 1203 | vec!["new", "middle", "old"] |
| 1204 | ); |
| 1205 | } |
| 1206 | |
| 1207 | #[tokio::test] |
| 1208 | async fn the_fake_records_a_last_use_on_the_right_token() { |
| 1209 | let tokens = InMemoryTokenRepo::new(); |
| 1210 | let user = UserId::generate(); |
| 1211 | let (mine, mine_secret) = token_for(&user, "mine", 1_000); |
| 1212 | let (untouched, untouched_secret) = token_for(&user, "untouched", 1_000); |
| 1213 | tokens.save(&mine).await.expect("save"); |
| 1214 | tokens.save(&untouched).await.expect("save"); |
| 1215 | |
| 1216 | tokens |
| 1217 | .touch_last_used(&mine.id, at(2_000)) |
| 1218 | .await |
| 1219 | .expect("touch"); |
| 1220 | |
| 1221 | let stored = |secret: TokenSecret| { |
| 1222 | let tokens = tokens.clone(); |
| 1223 | async move { |
| 1224 | tokens |
| 1225 | .find_by_hash(&secret.hash()) |
| 1226 | .await |
| 1227 | .expect("lookup") |
| 1228 | .expect("present") |
| 1229 | } |
| 1230 | }; |
| 1231 | |
| 1232 | assert_eq!(stored(mine_secret).await.last_used_at, Some(at(2_000))); |
| 1233 | assert_eq!(stored(untouched_secret).await.last_used_at, None); |
| 1234 | } |
| 1235 | |
| 1236 | #[tokio::test] |
| 1237 | async fn recording_a_use_of_a_token_that_is_not_there_succeeds() { |
| 1238 | |
| 1239 | |
| 1240 | let tokens = InMemoryTokenRepo::new(); |
| 1241 | |
| 1242 | assert!( |
| 1243 | tokens |
| 1244 | .touch_last_used(&TokenId::generate(), at(1_000)) |
| 1245 | .await |
| 1246 | .is_ok() |
| 1247 | ); |
| 1248 | } |
| 1249 | |
| 1250 | |
| 1251 | |
| 1252 | #[tokio::test] |
| 1253 | async fn the_fake_forgets_a_deleted_repository() { |
| 1254 | let repos = InMemoryRepoRepo::new(); |
| 1255 | let org_id = OrgId::generate(); |
| 1256 | let repo = Repository::new( |
| 1257 | RepoId::generate(), |
| 1258 | org_id.clone(), |
| 1259 | "steid", |
| 1260 | None, |
| 1261 | crate::domain::Visibility::Public, |
| 1262 | at(1_000), |
| 1263 | ) |
| 1264 | .expect("valid repo"); |
| 1265 | repos.save(&repo).await.expect("save"); |
| 1266 | |
| 1267 | repos.delete(&repo.id).await.expect("delete"); |
| 1268 | |
| 1269 | assert_eq!(repos.find_by_id(&repo.id).await.expect("lookup"), None); |
| 1270 | assert!( |
| 1271 | repos |
| 1272 | .find_by_org_and_name(&org_id, &repo.name) |
| 1273 | .await |
| 1274 | .expect("lookup") |
| 1275 | .is_none(), |
| 1276 | "the name should be free again" |
| 1277 | ); |
| 1278 | assert!(repos.list_by_org(&org_id).await.expect("list").is_empty()); |
| 1279 | } |
| 1280 | |
| 1281 | #[tokio::test] |
| 1282 | async fn deleting_a_repository_that_is_not_there_succeeds() { |
| 1283 | |
| 1284 | let repos = InMemoryRepoRepo::new(); |
| 1285 | |
| 1286 | assert!(repos.delete(&RepoId::generate()).await.is_ok()); |
| 1287 | } |
| 1288 | |
| 1289 | #[tokio::test] |
| 1290 | async fn deleting_one_repository_leaves_the_others() { |
| 1291 | let repos = InMemoryRepoRepo::new(); |
| 1292 | let org_id = OrgId::generate(); |
| 1293 | let mut saved = Vec::new(); |
| 1294 | for name in ["alpha", "zebra"] { |
| 1295 | let repo = Repository::new( |
| 1296 | RepoId::generate(), |
| 1297 | org_id.clone(), |
| 1298 | name, |
| 1299 | None, |
| 1300 | crate::domain::Visibility::Public, |
| 1301 | at(1_000), |
| 1302 | ) |
| 1303 | .expect("valid repo"); |
| 1304 | repos.save(&repo).await.expect("save"); |
| 1305 | saved.push(repo); |
| 1306 | } |
| 1307 | |
| 1308 | repos.delete(&saved[0].id).await.expect("delete"); |
| 1309 | |
| 1310 | let listed = repos.list_by_org(&org_id).await.expect("list"); |
| 1311 | assert_eq!( |
| 1312 | listed.iter().map(|r| r.name.as_str()).collect::<Vec<_>>(), |
| 1313 | vec!["zebra"] |
| 1314 | ); |
| 1315 | } |
| 1316 | |
| 1317 | #[tokio::test] |
| 1318 | async fn the_fake_lists_newest_first_breaking_ties_by_name() { |
| 1319 | |
| 1320 | |
| 1321 | |
| 1322 | let repos = InMemoryRepoRepo::new(); |
| 1323 | let org_id = OrgId::generate(); |
| 1324 | for (name, seconds) in [ |
| 1325 | ("alpha", 3_000), |
| 1326 | ("older", 1_000), |
| 1327 | ("newer", 2_000), |
| 1328 | ("also-older", 1_000), |
| 1329 | ] { |
| 1330 | repos |
| 1331 | .save(&repo_at(&org_id, name, seconds)) |
| 1332 | .await |
| 1333 | .expect("save"); |
| 1334 | } |
| 1335 | |
| 1336 | let listed = repos.list_by_org(&org_id).await.expect("list"); |
| 1337 | |
| 1338 | assert_eq!( |
| 1339 | listed.iter().map(|r| r.name.as_str()).collect::<Vec<_>>(), |
| 1340 | vec!["alpha", "newer", "also-older", "older"] |
| 1341 | ); |
| 1342 | } |
| 1343 | |
| 1344 | #[tokio::test] |
| 1345 | async fn touching_moves_a_repository_to_the_supplied_time() { |
| 1346 | let repos = InMemoryRepoRepo::new(); |
| 1347 | let org_id = OrgId::generate(); |
| 1348 | let repo = repo_at(&org_id, "steid", 1_000); |
| 1349 | repos.save(&repo).await.expect("save"); |
| 1350 | |
| 1351 | repos.touch(&repo.id, at(5_000)).await.expect("touch"); |
| 1352 | |
| 1353 | let found = repos |
| 1354 | .find_by_id(&repo.id) |
| 1355 | .await |
| 1356 | .expect("lookup") |
| 1357 | .expect("still there"); |
| 1358 | assert_eq!(found.updated_at, at(5_000)); |
| 1359 | } |
| 1360 | |
| 1361 | #[tokio::test] |
| 1362 | async fn touching_a_repository_that_is_gone_succeeds() { |
| 1363 | |
| 1364 | let repos = InMemoryRepoRepo::new(); |
| 1365 | |
| 1366 | assert!(repos.touch(&RepoId::generate(), at(5_000)).await.is_ok()); |
| 1367 | } |
| 1368 | |
| 1369 | #[tokio::test] |
| 1370 | async fn the_fake_remembers_whether_a_repository_is_pinned() { |
| 1371 | let repos = InMemoryRepoRepo::new(); |
| 1372 | let org_id = OrgId::generate(); |
| 1373 | let mut repo = repo_at(&org_id, "steid", 1_000); |
| 1374 | repo.pinned = true; |
| 1375 | |
| 1376 | repos.save(&repo).await.expect("save"); |
| 1377 | |
| 1378 | assert!( |
| 1379 | repos |
| 1380 | .find_by_id(&repo.id) |
| 1381 | .await |
| 1382 | .expect("lookup") |
| 1383 | .expect("still there") |
| 1384 | .pinned |
| 1385 | ); |
| 1386 | } |
| 1387 | |
| 1388 | fn repo_at(org_id: &OrgId, name: &str, seconds: u64) -> Repository { |
| 1389 | Repository::new( |
| 1390 | RepoId::generate(), |
| 1391 | org_id.clone(), |
| 1392 | name, |
| 1393 | None, |
| 1394 | crate::domain::Visibility::Public, |
| 1395 | at(seconds), |
| 1396 | ) |
| 1397 | .expect("valid repo") |
| 1398 | } |
| 1399 | |
| 1400 | #[tokio::test] |
| 1401 | async fn the_fake_forgets_a_deleted_token() { |
| 1402 | let tokens = InMemoryTokenRepo::new(); |
| 1403 | let user = UserId::generate(); |
| 1404 | let (token, secret) = token_for(&user, "laptop", 1_000); |
| 1405 | tokens.save(&token).await.expect("save"); |
| 1406 | |
| 1407 | tokens.delete(&token.id).await.expect("delete"); |
| 1408 | |
| 1409 | assert!( |
| 1410 | tokens |
| 1411 | .find_by_hash(&secret.hash()) |
| 1412 | .await |
| 1413 | .expect("lookup") |
| 1414 | .is_none() |
| 1415 | ); |
| 1416 | } |
| 1417 | |
| 1418 | |
| 1419 | |
| 1420 | |
| 1421 | |
| 1422 | |
| 1423 | fn an_issue(repo: &RepoId, number: u64, title: &str) -> Issue { |
| 1424 | Issue::new( |
| 1425 | IssueId::generate(), |
| 1426 | repo.clone(), |
| 1427 | IssueNumber::from_trusted(number), |
| 1428 | title, |
| 1429 | "body", |
| 1430 | UserId::generate(), |
| 1431 | at(1_000), |
| 1432 | ) |
| 1433 | .expect("valid issue") |
| 1434 | } |
| 1435 | |
| 1436 | #[tokio::test] |
| 1437 | async fn in_memory_numbering_starts_at_one_and_is_per_repository() { |
| 1438 | let issues = InMemoryIssueRepo::new(); |
| 1439 | let first = RepoId::generate(); |
| 1440 | let second = RepoId::generate(); |
| 1441 | |
| 1442 | assert_eq!(issues.next_number(&first).await.expect("allocate").get(), 1); |
| 1443 | assert_eq!(issues.next_number(&first).await.expect("allocate").get(), 2); |
| 1444 | assert_eq!( |
| 1445 | issues.next_number(&second).await.expect("allocate").get(), |
| 1446 | 1 |
| 1447 | ); |
| 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)] |
| 1589 | pub struct InMemorySessionRepo { |
| 1590 | sessions: Arc<Mutex<HashMap<String, Session>>>, |
| 1591 | } |
| 1592 | |
| 1593 | impl InMemorySessionRepo { |
| 1594 | pub fn new() -> Self { |
| 1595 | Self::default() |
| 1596 | } |
| 1597 | } |
| 1598 | |
| 1599 | impl 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_expired(&self, now: SystemTime) -> RepositoryResult<u64> { |
| 1618 | let mut sessions = self.sessions.lock().expect("lock poisoned"); |
| 1619 | let before = sessions.len(); |
| 1620 | sessions.retain(|_, session| !session.is_expired_at(now)); |
| 1621 | Ok((before - sessions.len()) as u64) |
| 1622 | } |
| 1623 | } |
| 1624 | |
| 1625 | #[derive(Debug, Default, Clone)] |
| 1626 | pub struct InMemoryRepoRepo { |
| 1627 | repos: Arc<Mutex<HashMap<String, Repository>>>, |
| 1628 | } |
| 1629 | |
| 1630 | impl InMemoryRepoRepo { |
| 1631 | pub fn new() -> Self { |
| 1632 | Self::default() |
| 1633 | } |
| 1634 | } |
| 1635 | |
| 1636 | impl RepoRepository for InMemoryRepoRepo { |
| 1637 | async fn find_by_id(&self, id: &RepoId) -> RepositoryResult<Option<Repository>> { |
| 1638 | let repos = self.repos.lock().expect("lock poisoned"); |
| 1639 | Ok(repos.get(id.as_str()).cloned()) |
| 1640 | } |
| 1641 | |
| 1642 | async fn find_by_org_and_name( |
| 1643 | &self, |
| 1644 | org_id: &OrgId, |
| 1645 | name: &RepoName, |
| 1646 | ) -> RepositoryResult<Option<Repository>> { |
| 1647 | let repos = self.repos.lock().expect("lock poisoned"); |
| 1648 | Ok(repos |
| 1649 | .values() |
| 1650 | .find(|repo| &repo.org_id == org_id && &repo.name == name) |
| 1651 | .cloned()) |
| 1652 | } |
| 1653 | |
| 1654 | async fn list_by_org(&self, org_id: &OrgId) -> RepositoryResult<Vec<Repository>> { |
| 1655 | let repos = self.repos.lock().expect("lock poisoned"); |
| 1656 | let mut found: Vec<Repository> = repos |
| 1657 | .values() |
| 1658 | .filter(|repo| &repo.org_id == org_id) |
| 1659 | .cloned() |
| 1660 | .collect(); |
| 1661 | |
| 1662 | |
| 1663 | |
| 1664 | found.sort_by(|a, b| { |
| 1665 | b.updated_at |
| 1666 | .cmp(&a.updated_at) |
| 1667 | .then_with(|| a.name.as_str().cmp(b.name.as_str())) |
| 1668 | }); |
| 1669 | Ok(found) |
| 1670 | } |
| 1671 | |
| 1672 | async fn save(&self, repo: &Repository) -> RepositoryResult<()> { |
| 1673 | let mut repos = self.repos.lock().expect("lock poisoned"); |
| 1674 | repos.insert(repo.id.as_str().to_owned(), repo.clone()); |
| 1675 | Ok(()) |
| 1676 | } |
| 1677 | |
| 1678 | async fn touch(&self, id: &RepoId, now: SystemTime) -> RepositoryResult<()> { |
| 1679 | let mut repos = self.repos.lock().expect("lock poisoned"); |
| 1680 | if let Some(repo) = repos.get_mut(id.as_str()) { |
| 1681 | repo.updated_at = now; |
| 1682 | } |
| 1683 | Ok(()) |
| 1684 | } |
| 1685 | |
| 1686 | async fn fail_interrupted_imports(&self, reason: &str) -> RepositoryResult<u64> { |
| 1687 | let mut repos = self.repos.lock().expect("lock poisoned"); |
| 1688 | let mut swept = 0; |
| 1689 | |
| 1690 | for repo in repos.values_mut() { |
| 1691 | if repo.import_state == Some(ImportState::Importing) { |
| 1692 | repo.fail_import(reason); |
| 1693 | swept += 1; |
| 1694 | } |
| 1695 | } |
| 1696 | |
| 1697 | Ok(swept) |
| 1698 | } |
| 1699 | |
| 1700 | async fn delete(&self, id: &RepoId) -> RepositoryResult<()> { |
| 1701 | let mut repos = self.repos.lock().expect("lock poisoned"); |
| 1702 | repos.remove(id.as_str()); |
| 1703 | Ok(()) |
| 1704 | } |
| 1705 | } |