steid

@jamesgill /

1//! SQLite repository implementations.
2//!
3//! Rows are reassembled with `from_trusted`: they were validated on the way in, and
4//! re-validating them would make a tightened rule turn old rows unreadable.
5
6use std::time::{Duration, SystemTime};
7
8use sqlx::{Row, SqlitePool, sqlite::SqliteRow};
9
10use crate::domain::{
11 Email, ImportSource, ImportState, Issue, IssueComment, IssueCommentId, IssueId, IssueNumber,
12 IssueState, Membership, MembershipId, ObjectId, OrgId, OrgName, Organization, PasswordHash,
13 PersonalAccessToken, PushEvent, PushEventId, RefName, RepoId, RepoName, Repository, Role,
14 Session, SessionTokenHash, TokenHash, TokenId, User, UserId, Visibility, Webhook,
15 WebhookDelivery, WebhookDeliveryId, WebhookId, WebhookSecret, WebhookUrl,
16 repository::{
17 IssueCounts, IssueRepository, MembershipRepository, OrgRepository, PushEventRepository,
18 RepoRepository, RepositoryError, RepositoryResult, SessionRepository, TokenRepository,
19 UserRepository, WebhookDeliveryRepository, WebhookRepository,
20 },
21};
22
23fn backend(error: sqlx::Error) -> RepositoryError {
24 RepositoryError::backend(error)
25}
26
27#[derive(Debug, Clone)]
28pub struct SqliteUserRepo {
29 pool: SqlitePool,
30}
31
32impl SqliteUserRepo {
33 pub fn new(pool: SqlitePool) -> Self {
34 Self { pool }
35 }
36
37 fn map(row: &SqliteRow) -> User {
38 User::new(
39 UserId::from_trusted(row.get::<String, _>("id")),
40 Email::from_trusted(row.get::<String, _>("email")),
41 PasswordHash::from_trusted(row.get::<String, _>("password_hash")),
42 OrgId::from_trusted(row.get::<String, _>("personal_org_id")),
43 )
44 }
45}
46
47impl UserRepository for SqliteUserRepo {
48 async fn find_by_id(&self, id: &UserId) -> RepositoryResult<Option<User>> {
49 let row = sqlx::query("select * from users where id = ?")
50 .bind(id.as_str())
51 .fetch_optional(&self.pool)
52 .await
53 .map_err(backend)?;
54
55 Ok(row.as_ref().map(Self::map))
56 }
57
58 async fn find_by_email(&self, email: &Email) -> RepositoryResult<Option<User>> {
59 let row = sqlx::query("select * from users where email = ?")
60 .bind(email.as_str())
61 .fetch_optional(&self.pool)
62 .await
63 .map_err(backend)?;
64
65 Ok(row.as_ref().map(Self::map))
66 }
67
68 async fn save(&self, user: &User) -> RepositoryResult<()> {
69 sqlx::query(
70 "insert into users (id, email, password_hash, personal_org_id)
71 values (?, ?, ?, ?)
72 on conflict (id) do update set
73 email = excluded.email,
74 password_hash = excluded.password_hash,
75 personal_org_id = excluded.personal_org_id",
76 )
77 .bind(user.id.as_str())
78 .bind(user.email.as_str())
79 .bind(user.password_hash.as_str())
80 .bind(user.personal_org_id.as_str())
81 .execute(&self.pool)
82 .await
83 .map_err(backend)?;
84
85 Ok(())
86 }
87
88 async fn sole_user(&self) -> RepositoryResult<Option<User>> {
89 // `limit 2`, not `limit 1`: the query has to be able to see a second user in
90 // order to refuse, and `limit 1` would silently pick one.
91 let rows = sqlx::query("select * from users limit 2")
92 .fetch_all(&self.pool)
93 .await
94 .map_err(backend)?;
95
96 match rows.as_slice() {
97 [row] => Ok(Some(Self::map(row))),
98 _ => Ok(None),
99 }
100 }
101
102 async fn any_exist(&self) -> RepositoryResult<bool> {
103 let count: i64 = sqlx::query_scalar("select exists (select 1 from users)")
104 .fetch_one(&self.pool)
105 .await
106 .map_err(backend)?;
107
108 Ok(count != 0)
109 }
110}
111
112#[derive(Debug, Clone)]
113pub struct SqliteOrgRepo {
114 pool: SqlitePool,
115}
116
117impl SqliteOrgRepo {
118 pub fn new(pool: SqlitePool) -> Self {
119 Self { pool }
120 }
121
122 fn map(row: &SqliteRow) -> Organization {
123 Organization::from_trusted(
124 OrgId::from_trusted(row.get::<String, _>("id")),
125 OrgName::from_trusted(row.get::<String, _>("name")),
126 row.get::<Option<String>, _>("display_name"),
127 row.get::<Option<String>, _>("bio"),
128 )
129 }
130}
131
132impl OrgRepository for SqliteOrgRepo {
133 async fn find_by_id(&self, id: &OrgId) -> RepositoryResult<Option<Organization>> {
134 let row = sqlx::query("select * from orgs where id = ?")
135 .bind(id.as_str())
136 .fetch_optional(&self.pool)
137 .await
138 .map_err(backend)?;
139
140 Ok(row.as_ref().map(Self::map))
141 }
142
143 async fn find_by_name(&self, name: &OrgName) -> RepositoryResult<Option<Organization>> {
144 let row = sqlx::query("select * from orgs where name = ?")
145 .bind(name.as_str())
146 .fetch_optional(&self.pool)
147 .await
148 .map_err(backend)?;
149
150 Ok(row.as_ref().map(Self::map))
151 }
152
153 async fn save(&self, org: &Organization) -> RepositoryResult<()> {
154 sqlx::query(
155 "insert into orgs (id, name, display_name, bio)
156 values (?, ?, ?, ?)
157 on conflict (id) do update set
158 name = excluded.name,
159 display_name = excluded.display_name,
160 bio = excluded.bio",
161 )
162 .bind(org.id.as_str())
163 .bind(org.name.as_str())
164 .bind(org.display_name.as_deref())
165 .bind(org.bio.as_deref())
166 .execute(&self.pool)
167 .await
168 .map_err(backend)?;
169
170 Ok(())
171 }
172}
173
174#[derive(Debug, Clone)]
175pub struct SqliteMembershipRepo {
176 pool: SqlitePool,
177}
178
179impl SqliteMembershipRepo {
180 pub fn new(pool: SqlitePool) -> Self {
181 Self { pool }
182 }
183
184 /// An unparseable role is a storage fault, not a missing membership, so it
185 /// surfaces rather than silently downgrading the member's access.
186 fn map(row: &SqliteRow) -> RepositoryResult<Membership> {
187 let raw: String = row.get("role");
188 let role: Role = raw
189 .parse()
190 .map_err(|error| RepositoryError::backend(format!("{error}")))?;
191
192 Ok(Membership::new(
193 MembershipId::from_trusted(row.get::<String, _>("id")),
194 OrgId::from_trusted(row.get::<String, _>("org_id")),
195 UserId::from_trusted(row.get::<String, _>("user_id")),
196 role,
197 ))
198 }
199}
200
201impl MembershipRepository for SqliteMembershipRepo {
202 async fn find(&self, org_id: &OrgId, user_id: &UserId) -> RepositoryResult<Option<Membership>> {
203 let row = sqlx::query("select * from memberships where org_id = ? and user_id = ?")
204 .bind(org_id.as_str())
205 .bind(user_id.as_str())
206 .fetch_optional(&self.pool)
207 .await
208 .map_err(backend)?;
209
210 row.as_ref().map(Self::map).transpose()
211 }
212
213 async fn list_for_user(&self, user_id: &UserId) -> RepositoryResult<Vec<Membership>> {
214 let rows = sqlx::query("select * from memberships where user_id = ?")
215 .bind(user_id.as_str())
216 .fetch_all(&self.pool)
217 .await
218 .map_err(backend)?;
219
220 rows.iter().map(Self::map).collect()
221 }
222
223 async fn save(&self, membership: &Membership) -> RepositoryResult<()> {
224 sqlx::query(
225 "insert into memberships (id, org_id, user_id, role)
226 values (?, ?, ?, ?)
227 on conflict (id) do update set role = excluded.role",
228 )
229 .bind(membership.id.as_str())
230 .bind(membership.org_id.as_str())
231 .bind(membership.user_id.as_str())
232 .bind(membership.role.as_str())
233 .execute(&self.pool)
234 .await
235 .map_err(backend)?;
236
237 Ok(())
238 }
239}
240
241#[derive(Debug, Clone)]
242pub struct SqliteSessionRepo {
243 pool: SqlitePool,
244}
245
246impl SqliteSessionRepo {
247 pub fn new(pool: SqlitePool) -> Self {
248 Self { pool }
249 }
250}
251
252/// Unix seconds. Times before the epoch cannot occur here — sessions always expire in
253/// the future — so saturating at 0 is safe rather than lossy.
254fn to_unix(time: SystemTime) -> i64 {
255 time.duration_since(SystemTime::UNIX_EPOCH)
256 .map(|d| d.as_secs() as i64)
257 .unwrap_or(0)
258}
259
260fn from_unix(seconds: i64) -> SystemTime {
261 SystemTime::UNIX_EPOCH + Duration::from_secs(seconds.max(0) as u64)
262}
263
264impl SessionRepository for SqliteSessionRepo {
265 async fn find(&self, token_hash: &SessionTokenHash) -> RepositoryResult<Option<Session>> {
266 let row = sqlx::query("select * from sessions where token_hash = ?")
267 .bind(token_hash.as_str())
268 .fetch_optional(&self.pool)
269 .await
270 .map_err(backend)?;
271
272 Ok(row.map(|row| {
273 Session::new(
274 SessionTokenHash::from_trusted(row.get::<String, _>("token_hash")),
275 UserId::from_trusted(row.get::<String, _>("user_id")),
276 from_unix(row.get::<i64, _>("expires_at")),
277 )
278 }))
279 }
280
281 async fn save(&self, session: &Session) -> RepositoryResult<()> {
282 sqlx::query(
283 "insert into sessions (token_hash, user_id, expires_at)
284 values (?, ?, ?)
285 on conflict (token_hash) do update set
286 user_id = excluded.user_id,
287 expires_at = excluded.expires_at",
288 )
289 .bind(session.token_hash.as_str())
290 .bind(session.user_id.as_str())
291 .bind(to_unix(session.expires_at))
292 .execute(&self.pool)
293 .await
294 .map_err(backend)?;
295
296 Ok(())
297 }
298
299 async fn delete(&self, token_hash: &SessionTokenHash) -> RepositoryResult<()> {
300 sqlx::query("delete from sessions where token_hash = ?")
301 .bind(token_hash.as_str())
302 .execute(&self.pool)
303 .await
304 .map_err(backend)?;
305
306 Ok(())
307 }
308
309 async fn delete_expired(&self, now: SystemTime) -> RepositoryResult<u64> {
310 let result = sqlx::query("delete from sessions where expires_at <= ?")
311 .bind(to_unix(now))
312 .execute(&self.pool)
313 .await
314 .map_err(backend)?;
315
316 Ok(result.rows_affected())
317 }
318}
319
320#[derive(Debug, Clone)]
321pub struct SqliteRepoRepo {
322 pool: SqlitePool,
323}
324
325impl SqliteRepoRepo {
326 pub fn new(pool: SqlitePool) -> Self {
327 Self { pool }
328 }
329
330 /// An unparseable visibility is a storage fault, not a default.
331 ///
332 /// Falling back to `Public` would publish a repository whose row we cannot read;
333 /// falling back to `Private` would hide a public one. Neither is a guess worth
334 /// making, so the row surfaces as an error.
335 fn map(row: &SqliteRow) -> RepositoryResult<Repository> {
336 let raw: String = row.get("visibility");
337 let visibility: Visibility = raw
338 .parse()
339 .map_err(|error| RepositoryError::backend(format!("{error}")))?;
340
341 // An unparseable import state is a fault for the same reason an unparseable
342 // visibility is: both possible defaults are wrong. `None` would serve a
343 // half-cloned repository as finished; `Failed` would bury a working one.
344 let import_state: Option<ImportState> = row
345 .get::<Option<String>, _>("import_state")
346 .map(|raw| raw.parse())
347 .transpose()
348 .map_err(|error| RepositoryError::backend(format!("{error}")))?;
349
350 Ok(Repository::from_trusted(
351 RepoId::from_trusted(row.get::<String, _>("id")),
352 OrgId::from_trusted(row.get::<String, _>("org_id")),
353 RepoName::from_trusted(row.get::<String, _>("name")),
354 row.get::<Option<String>, _>("description"),
355 visibility,
356 from_unix(row.get::<i64, _>("updated_at")),
357 row.get::<i64, _>("pinned") != 0,
358 row.get::<i64, _>("archived") != 0,
359 )
360 .with_import(
361 import_state,
362 row.get::<Option<String>, _>("import_source")
363 .map(ImportSource::from_trusted),
364 row.get::<Option<String>, _>("import_error"),
365 ))
366 }
367}
368
369impl RepoRepository for SqliteRepoRepo {
370 async fn find_by_id(&self, id: &RepoId) -> RepositoryResult<Option<Repository>> {
371 let row = sqlx::query("select * from repositories where id = ?")
372 .bind(id.as_str())
373 .fetch_optional(&self.pool)
374 .await
375 .map_err(backend)?;
376
377 row.as_ref().map(Self::map).transpose()
378 }
379
380 async fn find_by_org_and_name(
381 &self,
382 org_id: &OrgId,
383 name: &RepoName,
384 ) -> RepositoryResult<Option<Repository>> {
385 let row = sqlx::query("select * from repositories where org_id = ? and name = ?")
386 .bind(org_id.as_str())
387 .bind(name.as_str())
388 .fetch_optional(&self.pool)
389 .await
390 .map_err(backend)?;
391
392 row.as_ref().map(Self::map).transpose()
393 }
394
395 async fn list_by_org(&self, org_id: &OrgId) -> RepositoryResult<Vec<Repository>> {
396 // Newest first, name ascending as the tiebreak — `InMemoryRepoRepo::list_by_org`
397 // sorts identically, deliberately.
398 let rows = sqlx::query(
399 "select * from repositories where org_id = ? order by updated_at desc, name asc",
400 )
401 .bind(org_id.as_str())
402 .fetch_all(&self.pool)
403 .await
404 .map_err(backend)?;
405
406 rows.iter().map(Self::map).collect()
407 }
408
409 async fn save(&self, repo: &Repository) -> RepositoryResult<()> {
410 sqlx::query(
411 "insert into repositories
412 (id, org_id, name, description, visibility, updated_at, pinned, archived,
413 import_state, import_source, import_error)
414 values (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
415 on conflict (id) do update set
416 org_id = excluded.org_id,
417 name = excluded.name,
418 description = excluded.description,
419 visibility = excluded.visibility,
420 updated_at = excluded.updated_at,
421 pinned = excluded.pinned,
422 archived = excluded.archived,
423 import_state = excluded.import_state,
424 import_source = excluded.import_source,
425 import_error = excluded.import_error",
426 )
427 .bind(repo.id.as_str())
428 .bind(repo.org_id.as_str())
429 .bind(repo.name.as_str())
430 .bind(repo.description.as_deref())
431 .bind(repo.visibility.as_str())
432 .bind(to_unix(repo.updated_at))
433 .bind(i64::from(repo.pinned))
434 .bind(i64::from(repo.archived))
435 .bind(repo.import_state.map(ImportState::as_str))
436 .bind(repo.import_source.as_ref().map(ImportSource::as_str))
437 .bind(repo.import_error.as_deref())
438 .execute(&self.pool)
439 .await
440 .map_err(backend)?;
441
442 Ok(())
443 }
444
445 async fn touch(&self, id: &RepoId, now: SystemTime) -> RepositoryResult<()> {
446 // A column update rather than a read-modify-write, so two pushes racing each
447 // other cannot restore an older timestamp.
448 sqlx::query("update repositories set updated_at = ? where id = ?")
449 .bind(to_unix(now))
450 .bind(id.as_str())
451 .execute(&self.pool)
452 .await
453 .map_err(backend)?;
454
455 Ok(())
456 }
457
458 async fn fail_interrupted_imports(&self, reason: &str) -> RepositoryResult<u64> {
459 let result = sqlx::query(
460 "update repositories
461 set import_state = ?, import_error = ?
462 where import_state = ?",
463 )
464 .bind(ImportState::Failed.as_str())
465 .bind(reason)
466 .bind(ImportState::Importing.as_str())
467 .execute(&self.pool)
468 .await
469 .map_err(backend)?;
470
471 Ok(result.rows_affected())
472 }
473
474 async fn delete(&self, id: &RepoId) -> RepositoryResult<()> {
475 sqlx::query("delete from repositories where id = ?")
476 .bind(id.as_str())
477 .execute(&self.pool)
478 .await
479 .map_err(backend)?;
480
481 Ok(())
482 }
483}
484
485#[derive(Debug, Clone)]
486pub struct SqliteTokenRepo {
487 pool: SqlitePool,
488}
489
490impl SqliteTokenRepo {
491 pub fn new(pool: SqlitePool) -> Self {
492 Self { pool }
493 }
494
495 /// `from_trusted`, because these values were validated on the way in. Revalidating
496 /// stored rows means a tightened rule turns old rows unreadable.
497 fn hydrate(row: &SqliteRow) -> PersonalAccessToken {
498 PersonalAccessToken::from_trusted(
499 TokenId::from_trusted(row.get::<String, _>("id")),
500 UserId::from_trusted(row.get::<String, _>("user_id")),
501 row.get::<String, _>("name"),
502 row.get::<String, _>("prefix"),
503 TokenHash::from_trusted(row.get::<String, _>("token_hash")),
504 from_unix(row.get::<i64, _>("created_at")),
505 )
506 }
507}
508
509impl TokenRepository for SqliteTokenRepo {
510 async fn find_by_hash(
511 &self,
512 hash: &TokenHash,
513 ) -> RepositoryResult<Option<PersonalAccessToken>> {
514 // Matched in SQL by the hash, which is safe to compare with `=`: it is a digest,
515 // not the secret. The constant-time comparison guards the value a client
516 // presents, and that never reaches the database.
517 let row = sqlx::query("select * from tokens where token_hash = ?")
518 .bind(hash.as_str())
519 .fetch_optional(&self.pool)
520 .await
521 .map_err(backend)?;
522
523 Ok(row.as_ref().map(Self::hydrate))
524 }
525
526 async fn list_by_user(&self, user_id: &UserId) -> RepositoryResult<Vec<PersonalAccessToken>> {
527 let rows =
528 sqlx::query("select * from tokens where user_id = ? order by created_at desc, id asc")
529 .bind(user_id.as_str())
530 .fetch_all(&self.pool)
531 .await
532 .map_err(backend)?;
533
534 Ok(rows.iter().map(Self::hydrate).collect())
535 }
536
537 async fn save(&self, token: &PersonalAccessToken) -> RepositoryResult<()> {
538 sqlx::query(
539 "insert into tokens (id, user_id, name, prefix, token_hash, created_at)
540 values (?, ?, ?, ?, ?, ?)
541 on conflict (id) do update set
542 name = excluded.name",
543 )
544 .bind(token.id.as_str())
545 .bind(token.user_id.as_str())
546 .bind(&token.name)
547 .bind(&token.prefix)
548 .bind(token.token_hash.as_str())
549 .bind(to_unix(token.created_at))
550 .execute(&self.pool)
551 .await
552 .map_err(backend)?;
553
554 Ok(())
555 }
556
557 async fn delete(&self, id: &TokenId) -> RepositoryResult<()> {
558 sqlx::query("delete from tokens where id = ?")
559 .bind(id.as_str())
560 .execute(&self.pool)
561 .await
562 .map_err(backend)?;
563
564 Ok(())
565 }
566}
567
568// --- Issues ------------------------------------------------------------------------
569
570#[derive(Debug, Clone)]
571pub struct SqliteIssueRepo {
572 pool: SqlitePool,
573}
574
575impl SqliteIssueRepo {
576 pub fn new(pool: SqlitePool) -> Self {
577 Self { pool }
578 }
579
580 /// `from_trusted` throughout, including the state: the value was a valid
581 /// [`IssueState`] on the way in, and parsing it here would turn a tightened rule
582 /// into unreadable rows.
583 fn hydrate(row: &SqliteRow) -> Issue {
584 Issue::from_trusted(
585 IssueId::from_trusted(row.get::<String, _>("id")),
586 RepoId::from_trusted(row.get::<String, _>("repo_id")),
587 IssueNumber::from_trusted(row.get::<i64, _>("number").max(1) as u64),
588 row.get::<String, _>("title"),
589 row.get::<String, _>("body"),
590 // The one place a stored value is parsed rather than trusted, because
591 // `IssueState` has no `from_trusted` to give it — and there is nothing
592 // sensible to reconstruct an unknown state as. An unreadable row would be a
593 // bug in a migration, not in user input.
594 row.get::<String, _>("state")
595 .parse()
596 .unwrap_or(IssueState::Open),
597 UserId::from_trusted(row.get::<String, _>("author_id")),
598 from_unix(row.get::<i64, _>("created_at")),
599 from_unix(row.get::<i64, _>("updated_at")),
600 row.get::<Option<i64>, _>("closed_at").map(from_unix),
601 )
602 }
603
604 fn hydrate_comment(row: &SqliteRow) -> IssueComment {
605 IssueComment::from_trusted(
606 IssueCommentId::from_trusted(row.get::<String, _>("id")),
607 IssueId::from_trusted(row.get::<String, _>("issue_id")),
608 UserId::from_trusted(row.get::<String, _>("author_id")),
609 row.get::<String, _>("body"),
610 from_unix(row.get::<i64, _>("created_at")),
611 )
612 }
613}
614
615impl IssueRepository for SqliteIssueRepo {
616 /// One statement, so the read-modify-write is atomic without an explicit
617 /// transaction: SQLite serialises writers, and `on conflict … do update` sees the
618 /// row it is about to replace.
619 ///
620 /// `next_number` holds the number to hand out *next*, so the returned value is
621 /// always one past the allocation — on the insert branch it is 2 and the allocation
622 /// is 1, on the update branch it is `n + 1` and the allocation is `n`. Subtracting
623 /// one covers both without the statement having to know which branch it took.
624 async fn next_number(&self, repo_id: &RepoId) -> RepositoryResult<IssueNumber> {
625 let row = sqlx::query(
626 "insert into repo_sequences (repo_id, next_number) values (?, 2)
627 on conflict (repo_id) do update set next_number = next_number + 1
628 returning next_number",
629 )
630 .bind(repo_id.as_str())
631 .fetch_one(&self.pool)
632 .await
633 .map_err(backend)?;
634
635 let allocated = row.get::<i64, _>("next_number").saturating_sub(1).max(1);
636
637 Ok(IssueNumber::from_trusted(allocated as u64))
638 }
639
640 async fn find_by_number(
641 &self,
642 repo_id: &RepoId,
643 number: IssueNumber,
644 ) -> RepositoryResult<Option<Issue>> {
645 let row = sqlx::query("select * from issues where repo_id = ? and number = ?")
646 .bind(repo_id.as_str())
647 .bind(number.get() as i64)
648 .fetch_optional(&self.pool)
649 .await
650 .map_err(backend)?;
651
652 Ok(row.as_ref().map(Self::hydrate))
653 }
654
655 async fn list_by_repo(
656 &self,
657 repo_id: &RepoId,
658 state: IssueState,
659 ) -> RepositoryResult<Vec<Issue>> {
660 // Newest first is descending *number*, not descending `created_at`: the
661 // sequence is monotonic, so it orders identically and cannot tie.
662 let rows = sqlx::query(
663 "select * from issues where repo_id = ? and state = ? order by number desc",
664 )
665 .bind(repo_id.as_str())
666 .bind(state.as_str())
667 .fetch_all(&self.pool)
668 .await
669 .map_err(backend)?;
670
671 Ok(rows.iter().map(Self::hydrate).collect())
672 }
673
674 async fn counts(&self, repo_id: &RepoId) -> RepositoryResult<IssueCounts> {
675 let rows = sqlx::query(
676 "select state, count(*) as total from issues where repo_id = ? group by state",
677 )
678 .bind(repo_id.as_str())
679 .fetch_all(&self.pool)
680 .await
681 .map_err(backend)?;
682
683 let mut counts = IssueCounts::default();
684
685 for row in &rows {
686 let total = row.get::<i64, _>("total").max(0) as u64;
687
688 match row.get::<String, _>("state").parse() {
689 Ok(IssueState::Open) => counts.open = total,
690 Ok(IssueState::Closed) => counts.closed = total,
691 // A state neither implementation can name is not counted as either. It
692 // would take a hand-edited row to reach this.
693 Err(_) => {}
694 }
695 }
696
697 Ok(counts)
698 }
699
700 async fn comment_counts(&self, repo_id: &RepoId) -> RepositoryResult<Vec<(IssueId, u64)>> {
701 // A left join so an issue with no comments still gets a row: the caller builds a
702 // lookup out of this, and a missing key and a zero would have to be handled
703 // identically anyway.
704 let rows = sqlx::query(
705 "select issues.id as issue_id, count(issue_comments.id) as total
706 from issues
707 left join issue_comments on issue_comments.issue_id = issues.id
708 where issues.repo_id = ?
709 group by issues.id",
710 )
711 .bind(repo_id.as_str())
712 .fetch_all(&self.pool)
713 .await
714 .map_err(backend)?;
715
716 Ok(rows
717 .iter()
718 .map(|row| {
719 (
720 IssueId::from_trusted(row.get::<String, _>("issue_id")),
721 row.get::<i64, _>("total").max(0) as u64,
722 )
723 })
724 .collect())
725 }
726
727 async fn save(&self, issue: &Issue) -> RepositoryResult<()> {
728 // `number`, `repo_id` and `author_id` are absent from the update list on
729 // purpose: an issue's identity is its number on its repository, and an edit that
730 // could move it would break every link ever written to it.
731 sqlx::query(
732 "insert into issues
733 (id, repo_id, number, title, body, state, author_id, created_at, updated_at, closed_at)
734 values (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
735 on conflict (id) do update set
736 title = excluded.title,
737 body = excluded.body,
738 state = excluded.state,
739 updated_at = excluded.updated_at,
740 closed_at = excluded.closed_at",
741 )
742 .bind(issue.id.as_str())
743 .bind(issue.repo_id.as_str())
744 .bind(issue.number.get() as i64)
745 .bind(&issue.title)
746 .bind(&issue.body)
747 .bind(issue.state.as_str())
748 .bind(issue.author_id.as_str())
749 .bind(to_unix(issue.created_at))
750 .bind(to_unix(issue.updated_at))
751 .bind(issue.closed_at.map(to_unix))
752 .execute(&self.pool)
753 .await
754 .map_err(backend)?;
755
756 Ok(())
757 }
758
759 async fn list_comments(&self, issue_id: &IssueId) -> RepositoryResult<Vec<IssueComment>> {
760 // `rowid` breaks a tie, which is insertion order — two comments posted in the
761 // same second read in the order they were written. The id would not do: it is a
762 // random UUID, so a tie would come back in an arbitrary order and a conversation
763 // would occasionally read backwards.
764 let rows = sqlx::query(
765 "select * from issue_comments where issue_id = ? order by created_at asc, rowid asc",
766 )
767 .bind(issue_id.as_str())
768 .fetch_all(&self.pool)
769 .await
770 .map_err(backend)?;
771
772 Ok(rows.iter().map(Self::hydrate_comment).collect())
773 }
774
775 async fn add_comment(&self, comment: &IssueComment) -> RepositoryResult<()> {
776 sqlx::query(
777 "insert into issue_comments (id, issue_id, author_id, body, created_at)
778 values (?, ?, ?, ?, ?)",
779 )
780 .bind(comment.id.as_str())
781 .bind(comment.issue_id.as_str())
782 .bind(comment.author_id.as_str())
783 .bind(&comment.body)
784 .bind(to_unix(comment.created_at))
785 .execute(&self.pool)
786 .await
787 .map_err(backend)?;
788
789 Ok(())
790 }
791}
792
793#[derive(Debug, Clone)]
794pub struct SqlitePushEventRepo {
795 pool: SqlitePool,
796}
797
798impl SqlitePushEventRepo {
799 pub fn new(pool: SqlitePool) -> Self {
800 Self { pool }
801 }
802
803 fn hydrate(row: &SqliteRow) -> PushEvent {
804 PushEvent::from_trusted(
805 PushEventId::from_trusted(row.get::<String, _>("id")),
806 RepoId::from_trusted(row.get::<String, _>("repo_id")),
807 RefName::from_trusted(row.get::<String, _>("ref_name")),
808 ObjectId::from_trusted(row.get::<String, _>("before_id")),
809 ObjectId::from_trusted(row.get::<String, _>("after_id")),
810 row.get::<Option<String>, _>("pusher_id")
811 .map(UserId::from_trusted),
812 from_unix(row.get::<i64, _>("created_at")),
813 )
814 }
815}
816
817impl PushEventRepository for SqlitePushEventRepo {
818 async fn find(&self, id: &PushEventId) -> RepositoryResult<Option<PushEvent>> {
819 let row = sqlx::query("select * from push_events where id = ?")
820 .bind(id.as_str())
821 .fetch_optional(&self.pool)
822 .await
823 .map_err(backend)?;
824
825 Ok(row.as_ref().map(Self::hydrate))
826 }
827
828 async fn list_by_repo(
829 &self,
830 repo_id: &RepoId,
831 limit: usize,
832 ) -> RepositoryResult<Vec<PushEvent>> {
833 // The id breaks the tie, as it does for tokens: a `git push --all` writes every
834 // event in the same second, and without it the order is whatever SQLite felt
835 // like.
836 let rows = sqlx::query(
837 "select * from push_events where repo_id = ?
838 order by created_at desc, id asc
839 limit ?",
840 )
841 .bind(repo_id.as_str())
842 .bind(limit as i64)
843 .fetch_all(&self.pool)
844 .await
845 .map_err(backend)?;
846
847 Ok(rows.iter().map(Self::hydrate).collect())
848 }
849
850 async fn save(&self, event: &PushEvent) -> RepositoryResult<()> {
851 sqlx::query(
852 "insert into push_events
853 (id, repo_id, ref_name, before_id, after_id, pusher_id, created_at)
854 values (?, ?, ?, ?, ?, ?, ?)
855 on conflict (id) do nothing",
856 )
857 .bind(event.id.as_str())
858 .bind(event.repo_id.as_str())
859 .bind(event.ref_name.as_str())
860 .bind(event.before.as_str())
861 .bind(event.after.as_str())
862 .bind(event.pusher.as_ref().map(|id| id.as_str()))
863 .bind(to_unix(event.created_at))
864 .execute(&self.pool)
865 .await
866 .map_err(backend)?;
867
868 Ok(())
869 }
870}
871
872#[derive(Debug, Clone)]
873pub struct SqliteWebhookRepo {
874 pool: SqlitePool,
875}
876
877impl SqliteWebhookRepo {
878 pub fn new(pool: SqlitePool) -> Self {
879 Self { pool }
880 }
881
882 fn hydrate(row: &SqliteRow) -> Webhook {
883 Webhook::from_trusted(
884 WebhookId::from_trusted(row.get::<String, _>("id")),
885 RepoId::from_trusted(row.get::<String, _>("repo_id")),
886 WebhookUrl::from_trusted(row.get::<String, _>("url")),
887 WebhookSecret::from_trusted(row.get::<String, _>("secret")),
888 row.get::<i64, _>("active") != 0,
889 from_unix(row.get::<i64, _>("created_at")),
890 )
891 }
892}
893
894impl WebhookRepository for SqliteWebhookRepo {
895 async fn find(&self, id: &WebhookId) -> RepositoryResult<Option<Webhook>> {
896 let row = sqlx::query("select * from webhooks where id = ?")
897 .bind(id.as_str())
898 .fetch_optional(&self.pool)
899 .await
900 .map_err(backend)?;
901
902 Ok(row.as_ref().map(Self::hydrate))
903 }
904
905 async fn list_by_repo(&self, repo_id: &RepoId) -> RepositoryResult<Vec<Webhook>> {
906 let rows =
907 sqlx::query("select * from webhooks where repo_id = ? order by created_at asc, id asc")
908 .bind(repo_id.as_str())
909 .fetch_all(&self.pool)
910 .await
911 .map_err(backend)?;
912
913 Ok(rows.iter().map(Self::hydrate).collect())
914 }
915
916 async fn save(&self, webhook: &Webhook) -> RepositoryResult<()> {
917 sqlx::query(
918 "insert into webhooks (id, repo_id, url, secret, active, created_at)
919 values (?, ?, ?, ?, ?, ?)
920 on conflict (id) do update set
921 url = excluded.url,
922 active = excluded.active",
923 )
924 .bind(webhook.id.as_str())
925 .bind(webhook.repo_id.as_str())
926 .bind(webhook.url.as_str())
927 .bind(webhook.secret.reveal())
928 .bind(i64::from(webhook.active))
929 .bind(to_unix(webhook.created_at))
930 .execute(&self.pool)
931 .await
932 .map_err(backend)?;
933
934 Ok(())
935 }
936
937 async fn delete(&self, id: &WebhookId) -> RepositoryResult<()> {
938 sqlx::query("delete from webhooks where id = ?")
939 .bind(id.as_str())
940 .execute(&self.pool)
941 .await
942 .map_err(backend)?;
943
944 Ok(())
945 }
946}
947
948#[derive(Debug, Clone)]
949pub struct SqliteWebhookDeliveryRepo {
950 pool: SqlitePool,
951}
952
953impl SqliteWebhookDeliveryRepo {
954 pub fn new(pool: SqlitePool) -> Self {
955 Self { pool }
956 }
957
958 fn hydrate(row: &SqliteRow) -> WebhookDelivery {
959 WebhookDelivery::from_trusted(
960 WebhookDeliveryId::from_trusted(row.get::<String, _>("id")),
961 WebhookId::from_trusted(row.get::<String, _>("webhook_id")),
962 PushEventId::from_trusted(row.get::<String, _>("event_id")),
963 row.get::<i64, _>("attempt") as u32,
964 row.get::<Option<i64>, _>("status_code")
965 .map(|code| code as u16),
966 row.get::<String, _>("response"),
967 row.get::<i64, _>("duration_ms").max(0) as u64,
968 from_unix(row.get::<i64, _>("delivered_at")),
969 row.get::<i64, _>("ok") != 0,
970 )
971 }
972}
973
974impl WebhookDeliveryRepository for SqliteWebhookDeliveryRepo {
975 async fn list_by_webhook(
976 &self,
977 webhook_id: &WebhookId,
978 limit: usize,
979 ) -> RepositoryResult<Vec<WebhookDelivery>> {
980 // Attempt descending as the tiebreak, not the id: three attempts against a dead
981 // endpoint can land in the same second only when the failure is instant, and
982 // when they do the useful order is last-tried-first.
983 let rows = sqlx::query(
984 "select * from webhook_deliveries where webhook_id = ?
985 order by delivered_at desc, attempt desc
986 limit ?",
987 )
988 .bind(webhook_id.as_str())
989 .bind(limit as i64)
990 .fetch_all(&self.pool)
991 .await
992 .map_err(backend)?;
993
994 Ok(rows.iter().map(Self::hydrate).collect())
995 }
996
997 async fn latest_by_webhook(
998 &self,
999 webhook_id: &WebhookId,
1000 ) -> RepositoryResult<Option<WebhookDelivery>> {
1001 let row = sqlx::query(
1002 "select * from webhook_deliveries where webhook_id = ?
1003 order by delivered_at desc, attempt desc
1004 limit 1",
1005 )
1006 .bind(webhook_id.as_str())
1007 .fetch_optional(&self.pool)
1008 .await
1009 .map_err(backend)?;
1010
1011 Ok(row.as_ref().map(Self::hydrate))
1012 }
1013
1014 async fn save(&self, delivery: &WebhookDelivery) -> RepositoryResult<()> {
1015 sqlx::query(
1016 "insert into webhook_deliveries
1017 (id, webhook_id, event_id, attempt, status_code, response,
1018 duration_ms, delivered_at, ok)
1019 values (?, ?, ?, ?, ?, ?, ?, ?, ?)
1020 on conflict (id) do nothing",
1021 )
1022 .bind(delivery.id.as_str())
1023 .bind(delivery.webhook_id.as_str())
1024 .bind(delivery.event_id.as_str())
1025 .bind(i64::from(delivery.attempt))
1026 .bind(delivery.status.map(i64::from))
1027 .bind(&delivery.response)
1028 .bind(delivery.duration_ms as i64)
1029 .bind(to_unix(delivery.delivered_at))
1030 .bind(i64::from(delivery.ok))
1031 .execute(&self.pool)
1032 .await
1033 .map_err(backend)?;
1034
1035 Ok(())
1036 }
1037}
1038
1039#[cfg(test)]
1040mod tests {
1041 use super::*;
1042
1043 fn at(seconds: u64) -> SystemTime {
1044 SystemTime::UNIX_EPOCH + Duration::from_secs(seconds)
1045 }
1046 use crate::{
1047 application::{OwnerSpec, claim_instance, port::PasswordHasher},
1048 domain::{PrivateTargets, SetupToken, TokenSecret},
1049 infrastructure::{database::test_support::test_pool, password::StubHasher},
1050 };
1051
1052 struct Repos {
1053 users: SqliteUserRepo,
1054 orgs: SqliteOrgRepo,
1055 memberships: SqliteMembershipRepo,
1056 }
1057
1058 async fn repos() -> Repos {
1059 let pool = test_pool().await;
1060 Repos {
1061 users: SqliteUserRepo::new(pool.clone()),
1062 orgs: SqliteOrgRepo::new(pool.clone()),
1063 memberships: SqliteMembershipRepo::new(pool),
1064 }
1065 }
1066
1067 async fn saved_org(repos: &Repos, name: &str) -> Organization {
1068 let org = Organization::new(OrgId::generate(), name, None).expect("valid org");
1069 repos.orgs.save(&org).await.expect("save org");
1070 org
1071 }
1072
1073 async fn saved_user(repos: &Repos, email: &str, org: &Organization) -> User {
1074 let user = User::new(
1075 UserId::generate(),
1076 Email::new(email).expect("valid email"),
1077 PasswordHash::from_trusted("$argon2id$test"),
1078 org.id.clone(),
1079 );
1080 repos.users.save(&user).await.expect("save user");
1081 user
1082 }
1083
1084 #[tokio::test]
1085 async fn a_saved_user_round_trips() {
1086 let repos = repos().await;
1087 let org = saved_org(&repos, "james").await;
1088 let user = saved_user(&repos, "dev@example.com", &org).await;
1089
1090 let found = repos
1091 .users
1092 .find_by_id(&user.id)
1093 .await
1094 .expect("lookup")
1095 .expect("user should exist");
1096
1097 assert_eq!(found, user);
1098 }
1099
1100 #[tokio::test]
1101 async fn users_are_found_by_email_case_insensitively() {
1102 let repos = repos().await;
1103 let org = saved_org(&repos, "james").await;
1104 saved_user(&repos, "dev@example.com", &org).await;
1105
1106 // Email lowercases on construction, but a row written before that rule would
1107 // still need finding.
1108 let found = repos
1109 .users
1110 .find_by_email(&Email::from_trusted("DEV@EXAMPLE.COM"))
1111 .await
1112 .expect("lookup");
1113
1114 assert!(found.is_some(), "collate nocase should make this match");
1115 }
1116
1117 #[tokio::test]
1118 async fn an_org_round_trips_with_its_display_name() {
1119 let repos = repos().await;
1120 let org = Organization::new(OrgId::generate(), "acme", Some("Acme".to_owned()))
1121 .expect("valid org");
1122 repos.orgs.save(&org).await.expect("save");
1123
1124 let found = repos
1125 .orgs
1126 .find_by_name(&org.name)
1127 .await
1128 .expect("lookup")
1129 .expect("org should exist");
1130
1131 assert_eq!(found, org);
1132 assert_eq!(found.label(), "Acme");
1133 }
1134
1135 #[tokio::test]
1136 async fn a_missing_org_is_none_not_an_error() {
1137 let repos = repos().await;
1138
1139 let found = repos
1140 .orgs
1141 .find_by_name(&OrgName::new("nobody").unwrap())
1142 .await
1143 .expect("lookup");
1144
1145 assert_eq!(found, None);
1146 }
1147
1148 #[tokio::test]
1149 async fn a_membership_round_trips_with_its_role() {
1150 let repos = repos().await;
1151 let org = saved_org(&repos, "james").await;
1152 let user = saved_user(&repos, "dev@example.com", &org).await;
1153 let membership = Membership::new(
1154 MembershipId::generate(),
1155 org.id.clone(),
1156 user.id.clone(),
1157 Role::Owner,
1158 );
1159 repos.memberships.save(&membership).await.expect("save");
1160
1161 let found = repos
1162 .memberships
1163 .find(&org.id, &user.id)
1164 .await
1165 .expect("lookup")
1166 .expect("membership should exist");
1167
1168 assert_eq!(found, membership);
1169 assert!(found.can_write());
1170 }
1171
1172 #[tokio::test]
1173 async fn an_unreadable_role_surfaces_rather_than_downgrading_access() {
1174 let repos = repos().await;
1175 let pool = test_pool().await;
1176 let memberships = SqliteMembershipRepo::new(pool.clone());
1177 let org = Organization::new(OrgId::generate(), "james", None).expect("valid org");
1178 SqliteOrgRepo::new(pool.clone())
1179 .save(&org)
1180 .await
1181 .expect("save org");
1182 let user = User::new(
1183 UserId::generate(),
1184 Email::new("dev@example.com").expect("valid email"),
1185 PasswordHash::from_trusted("$argon2id$test"),
1186 org.id.clone(),
1187 );
1188 SqliteUserRepo::new(pool.clone())
1189 .save(&user)
1190 .await
1191 .expect("save user");
1192
1193 sqlx::query("insert into memberships (id, org_id, user_id, role) values (?, ?, ?, 'wat')")
1194 .bind(MembershipId::generate().as_str())
1195 .bind(org.id.as_str())
1196 .bind(user.id.as_str())
1197 .execute(&pool)
1198 .await
1199 .expect("insert");
1200
1201 let result = memberships.find(&org.id, &user.id).await;
1202
1203 assert!(
1204 result.is_err(),
1205 "a role we can't parse must not read as no membership"
1206 );
1207 drop(repos);
1208 }
1209
1210 #[tokio::test]
1211 async fn saving_a_user_before_its_org_is_refused() {
1212 let repos = repos().await;
1213 let orphan = User::new(
1214 UserId::generate(),
1215 Email::new("dev@example.com").expect("valid email"),
1216 PasswordHash::from_trusted("$argon2id$test"),
1217 OrgId::generate(),
1218 );
1219
1220 let result = repos.users.save(&orphan).await;
1221
1222 assert!(
1223 result.is_err(),
1224 "the foreign key should reject a user whose org doesn't exist"
1225 );
1226 }
1227
1228 #[tokio::test]
1229 async fn a_duplicate_handle_is_refused() {
1230 let repos = repos().await;
1231 saved_org(&repos, "james").await;
1232
1233 let clash = Organization::new(OrgId::generate(), "james", None).expect("valid org");
1234 let result = repos.orgs.save(&clash).await;
1235
1236 assert!(result.is_err(), "orgs.name is unique");
1237 }
1238
1239 #[tokio::test]
1240 async fn a_differently_cased_handle_is_also_refused() {
1241 let repos = repos().await;
1242 saved_org(&repos, "james").await;
1243
1244 // OrgName lowercases, so this can only arrive via from_trusted -- but the
1245 // constraint is what we're testing, not the value object.
1246 let clash = Organization::from_trusted(
1247 OrgId::generate(),
1248 OrgName::from_trusted("JAMES"),
1249 None,
1250 None,
1251 );
1252 let result = repos.orgs.save(&clash).await;
1253
1254 assert!(result.is_err(), "collate nocase should catch this");
1255 }
1256
1257 /// The claim use case checks `is_claimed` and then writes, which is TOCTOU. This
1258 /// asserts the database is what actually stops a second owner being created.
1259 #[tokio::test]
1260 async fn a_second_claim_is_stopped_by_the_database_not_the_check() {
1261 let repos = repos().await;
1262 let token = SetupToken::generate();
1263 let hasher = StubHasher::new();
1264 let spec = OwnerSpec {
1265 handle: "james".to_owned(),
1266 email: "dev@example.com".to_owned(),
1267 password: "hunter2".to_owned(),
1268 };
1269
1270 claim_instance(
1271 token.reveal(),
1272 &token,
1273 &spec,
1274 &repos.users,
1275 &repos.orgs,
1276 &repos.memberships,
1277 &hasher,
1278 )
1279 .await
1280 .expect("first claim");
1281
1282 // Simulate the race: the second claimant passed is_claimed before the first
1283 // committed, so it proceeds straight to the writes.
1284 let intruder_org = Organization::new(OrgId::generate(), "james", None).expect("valid org");
1285 let result = repos.orgs.save(&intruder_org).await;
1286
1287 assert!(
1288 result.is_err(),
1289 "unique(orgs.name) is what actually serialises concurrent claims"
1290 );
1291
1292 let intruder_user = User::new(
1293 UserId::generate(),
1294 Email::new("dev@example.com").expect("valid email"),
1295 hasher.hash("letmein").expect("hash"),
1296 OrgId::generate(),
1297 );
1298 assert!(
1299 repos.users.save(&intruder_user).await.is_err(),
1300 "unique(users.email) closes the other half"
1301 );
1302 }
1303 async fn org_with(orgs: &SqliteOrgRepo, name: &str) -> Organization {
1304 let org = Organization::new(OrgId::generate(), name, None).expect("valid org");
1305 orgs.save(&org).await.expect("save org");
1306 org
1307 }
1308
1309 async fn saved_repo(
1310 repos: &SqliteRepoRepo,
1311 org: &Organization,
1312 name: &str,
1313 visibility: Visibility,
1314 ) -> Repository {
1315 let repo = Repository::new(
1316 RepoId::generate(),
1317 org.id.clone(),
1318 name,
1319 None,
1320 visibility,
1321 at(1_000),
1322 )
1323 .expect("valid repo");
1324 repos.save(&repo).await.expect("save repo");
1325 repo
1326 }
1327
1328 #[tokio::test]
1329 async fn a_repository_round_trips() {
1330 let pool = test_pool().await;
1331 let orgs = SqliteOrgRepo::new(pool.clone());
1332 let repos = SqliteRepoRepo::new(pool);
1333 let org = org_with(&orgs, "acme").await;
1334
1335 let repo = Repository::new(
1336 RepoId::generate(),
1337 org.id.clone(),
1338 "steid",
1339 Some("A gitforge.".to_owned()),
1340 Visibility::Private,
1341 at(1_000),
1342 )
1343 .expect("valid repo");
1344 repos.save(&repo).await.expect("save");
1345
1346 let found = repos
1347 .find_by_id(&repo.id)
1348 .await
1349 .expect("lookup")
1350 .expect("should exist");
1351
1352 assert_eq!(found, repo);
1353 assert_eq!(found.visibility, Visibility::Private);
1354 assert_eq!(found.description.as_deref(), Some("A gitforge."));
1355 }
1356
1357 #[tokio::test]
1358 async fn lookup_by_name_is_case_insensitive() {
1359 let pool = test_pool().await;
1360 let orgs = SqliteOrgRepo::new(pool.clone());
1361 let repos = SqliteRepoRepo::new(pool);
1362 let org = org_with(&orgs, "acme").await;
1363 saved_repo(&repos, &org, "steid", Visibility::Public).await;
1364
1365 let found = repos
1366 .find_by_org_and_name(&org.id, &RepoName::from_trusted("STEID"))
1367 .await
1368 .expect("lookup");
1369
1370 assert!(found.is_some(), "collate nocase should make this match");
1371 }
1372
1373 #[tokio::test]
1374 async fn one_owner_cannot_have_two_repositories_with_the_same_name() {
1375 let pool = test_pool().await;
1376 let orgs = SqliteOrgRepo::new(pool.clone());
1377 let repos = SqliteRepoRepo::new(pool);
1378 let org = org_with(&orgs, "acme").await;
1379 saved_repo(&repos, &org, "steid", Visibility::Public).await;
1380
1381 let clash = Repository::new(
1382 RepoId::generate(),
1383 org.id.clone(),
1384 "steid",
1385 None,
1386 Visibility::Public,
1387 at(1_000),
1388 )
1389 .expect("valid repo");
1390
1391 assert!(repos.save(&clash).await.is_err(), "unique (org_id, name)");
1392 }
1393
1394 #[tokio::test]
1395 async fn two_owners_may_each_have_a_repository_of_the_same_name() {
1396 let pool = test_pool().await;
1397 let orgs = SqliteOrgRepo::new(pool.clone());
1398 let repos = SqliteRepoRepo::new(pool);
1399 let first = org_with(&orgs, "acme").await;
1400 let second = org_with(&orgs, "globex").await;
1401
1402 saved_repo(&repos, &first, "steid", Visibility::Public).await;
1403 saved_repo(&repos, &second, "steid", Visibility::Public).await;
1404
1405 // The constraint is a pair. On `name` alone, repository names would be globally
1406 // unique across the whole installation.
1407 assert_eq!(repos.list_by_org(&first.id).await.expect("list").len(), 1);
1408 assert_eq!(repos.list_by_org(&second.id).await.expect("list").len(), 1);
1409 }
1410
1411 #[tokio::test]
1412 async fn a_repository_owned_by_a_missing_org_is_refused() {
1413 let pool = test_pool().await;
1414 let repos = SqliteRepoRepo::new(pool);
1415 let orphan = Repository::new(
1416 RepoId::generate(),
1417 OrgId::generate(),
1418 "steid",
1419 None,
1420 Visibility::Public,
1421 at(1_000),
1422 )
1423 .expect("valid repo");
1424
1425 assert!(repos.save(&orphan).await.is_err(), "foreign key");
1426 }
1427
1428 #[tokio::test]
1429 async fn repositories_list_newest_first_breaking_ties_by_name() {
1430 // The order the profile renders, and the same order `InMemoryRepoRepo` produces
1431 // — the two are asserted against the same expectation on purpose.
1432 let pool = test_pool().await;
1433 let orgs = SqliteOrgRepo::new(pool.clone());
1434 let repos = SqliteRepoRepo::new(pool);
1435 let org = org_with(&orgs, "acme").await;
1436
1437 for (name, seconds) in [
1438 ("alpha", 3_000),
1439 ("older", 1_000),
1440 ("newer", 2_000),
1441 ("also-older", 1_000),
1442 ] {
1443 let mut repo = saved_repo(&repos, &org, name, Visibility::Public).await;
1444 repo.updated_at = at(seconds);
1445 repos.save(&repo).await.expect("restamp");
1446 }
1447
1448 let listed = repos.list_by_org(&org.id).await.expect("list");
1449
1450 assert_eq!(
1451 listed.iter().map(|r| r.name.as_str()).collect::<Vec<_>>(),
1452 vec!["alpha", "newer", "also-older", "older"]
1453 );
1454 }
1455
1456 #[tokio::test]
1457 async fn touching_moves_a_repository_to_the_supplied_time() {
1458 let pool = test_pool().await;
1459 let orgs = SqliteOrgRepo::new(pool.clone());
1460 let repos = SqliteRepoRepo::new(pool);
1461 let org = org_with(&orgs, "acme").await;
1462 let repo = saved_repo(&repos, &org, "steid", Visibility::Public).await;
1463
1464 repos.touch(&repo.id, at(5_000)).await.expect("touch");
1465
1466 let found = repos
1467 .find_by_id(&repo.id)
1468 .await
1469 .expect("lookup")
1470 .expect("still there");
1471 assert_eq!(found.updated_at, at(5_000));
1472 assert_eq!(found.name, repo.name, "only the timestamp should move");
1473 }
1474
1475 #[tokio::test]
1476 async fn touching_a_repository_that_is_gone_succeeds() {
1477 let pool = test_pool().await;
1478 let repos = SqliteRepoRepo::new(pool);
1479
1480 assert!(repos.touch(&RepoId::generate(), at(5_000)).await.is_ok());
1481 }
1482
1483 #[tokio::test]
1484 async fn pinning_round_trips_through_an_integer_column() {
1485 // SQLite has no boolean; a column read as anything but 0/1 would silently unpin.
1486 let pool = test_pool().await;
1487 let orgs = SqliteOrgRepo::new(pool.clone());
1488 let repos = SqliteRepoRepo::new(pool);
1489 let org = org_with(&orgs, "acme").await;
1490 let mut repo = saved_repo(&repos, &org, "steid", Visibility::Public).await;
1491
1492 assert!(!repo.pinned, "a repository is not pinned by default");
1493
1494 repo.pinned = true;
1495 repos.save(&repo).await.expect("save");
1496
1497 assert!(
1498 repos
1499 .find_by_id(&repo.id)
1500 .await
1501 .expect("lookup")
1502 .expect("still there")
1503 .pinned
1504 );
1505 }
1506
1507 /// The column migrations, applied to a row that predates all of them.
1508 ///
1509 /// The dev database and any deployed instance already hold repositories, and this is
1510 /// the only chance to check what they look like afterwards: the table is created
1511 /// with the new columns from scratch everywhere else. Every migration that adds a
1512 /// column to `repositories` belongs in the list below.
1513 #[tokio::test]
1514 async fn the_repository_migrations_leave_existing_rows_looking_current() {
1515 let pool = SqlitePool::connect("sqlite::memory:")
1516 .await
1517 .expect("in-memory database should open");
1518
1519 // The table as it stood before this migration, with a repository already in it.
1520 sqlx::query(
1521 "create table repositories (
1522 id text primary key,
1523 org_id text not null,
1524 name text not null collate nocase,
1525 description text,
1526 visibility text not null,
1527 unique (org_id, name)
1528 )",
1529 )
1530 .execute(&pool)
1531 .await
1532 .expect("old schema");
1533 sqlx::query(
1534 "insert into repositories (id, org_id, name, visibility)
1535 values ('r1', 'o1', 'steid', 'public')",
1536 )
1537 .execute(&pool)
1538 .await
1539 .expect("an existing repository");
1540
1541 for migration in [
1542 include_str!("../../../migrations/20260829090000_add_repository_recency.sql"),
1543 include_str!("../../../migrations/20260906120100_add_repository_import.sql"),
1544 include_str!("../../../migrations/20260906120400_add_repository_archived.sql"),
1545 ] {
1546 for statement in migration
1547 .split(';')
1548 .filter(|statement| !statement.trim().is_empty())
1549 {
1550 sqlx::query(statement)
1551 .execute(&pool)
1552 .await
1553 .expect("the migration should apply");
1554 }
1555 }
1556
1557 let repo = SqliteRepoRepo::new(pool)
1558 .find_by_id(&RepoId::from_trusted("r1"))
1559 .await
1560 .expect("lookup")
1561 .expect("the row survives");
1562
1563 assert!(
1564 !repo.pinned,
1565 "nothing becomes the lead without being chosen"
1566 );
1567 assert!(
1568 !repo.archived,
1569 "nothing becomes archived by migrating a database"
1570 );
1571
1572 // Stamped with the migration's own clock, not left at the epoch: an existing
1573 // repository must not read "updated 56 years ago" on the page this column exists
1574 // to order.
1575 let age = SystemTime::now()
1576 .duration_since(repo.updated_at)
1577 .expect("stamped in the past");
1578 assert!(
1579 age < Duration::from_secs(60),
1580 "expected a just-migrated timestamp, got one {age:?} old"
1581 );
1582
1583 // The import migration's columns are nullable and default to null, so every
1584 // repository that existed before importing did stays an ordinary repository.
1585 assert_eq!(repo.import_state, None);
1586 assert_eq!(repo.import_source, None);
1587 assert!(!repo.is_importing());
1588 }
1589
1590 /// The boot sweep, on a table holding one of each kind of row.
1591 #[tokio::test]
1592 async fn the_boot_sweep_fails_only_the_repositories_still_importing() {
1593 let pool = test_pool().await;
1594 let orgs = SqliteOrgRepo::new(pool.clone());
1595 let repos = SqliteRepoRepo::new(pool.clone());
1596 let org = org_with(&orgs, "acme").await;
1597
1598 let named = |name: &str| {
1599 Repository::new(
1600 RepoId::generate(),
1601 org.id.clone(),
1602 name,
1603 None,
1604 Visibility::Public,
1605 at(1_000),
1606 )
1607 .expect("valid repo")
1608 };
1609
1610 let mut ordinary = named("ordinary");
1611 let mut running = named("running");
1612 let mut done = named("done");
1613
1614 running.start_import(ImportSource::new("https://example.com/a.git").expect("valid"));
1615 done.start_import(ImportSource::new("https://example.com/b.git").expect("valid"));
1616 done.finish_import();
1617
1618 for repo in [&ordinary, &running, &done] {
1619 repos.save(repo).await.expect("save");
1620 }
1621
1622 let swept = repos
1623 .fail_interrupted_imports("interrupted by a restart")
1624 .await
1625 .expect("sweep");
1626
1627 assert_eq!(swept, 1, "only the running import is interrupted");
1628
1629 for repo in [&mut ordinary, &mut running, &mut done] {
1630 *repo = repos
1631 .find_by_id(&repo.id)
1632 .await
1633 .expect("lookup")
1634 .expect("still there");
1635 }
1636
1637 assert_eq!(ordinary.import_state, None);
1638 assert_eq!(done.import_state, None);
1639 assert_eq!(running.import_state, Some(ImportState::Failed));
1640 assert_eq!(
1641 running.import_error.as_deref(),
1642 Some("interrupted by a restart")
1643 );
1644 // The source survives the sweep: it is what a retry needs.
1645 assert_eq!(
1646 running.import_source.as_ref().map(ImportSource::as_str),
1647 Some("https://example.com/a.git")
1648 );
1649 }
1650
1651 /// An unreadable import state is a fault for the same reason an unreadable
1652 /// visibility is: both defaults are wrong in a way nobody would notice.
1653 #[tokio::test]
1654 async fn an_unreadable_import_state_surfaces_rather_than_defaulting() {
1655 let pool = test_pool().await;
1656 let orgs = SqliteOrgRepo::new(pool.clone());
1657 let repos = SqliteRepoRepo::new(pool.clone());
1658 let org = org_with(&orgs, "acme").await;
1659
1660 sqlx::query(
1661 "insert into repositories (id, org_id, name, visibility, updated_at, pinned, import_state)
1662 values ('r1', ?, 'half', 'public', 0, 0, 'halfway')",
1663 )
1664 .bind(org.id.as_str())
1665 .execute(&pool)
1666 .await
1667 .expect("a row written behind the repository");
1668
1669 assert!(repos.find_by_id(&RepoId::from_trusted("r1")).await.is_err());
1670 }
1671
1672 #[tokio::test]
1673 async fn an_unreadable_visibility_surfaces_rather_than_defaulting() {
1674 let pool = test_pool().await;
1675 let orgs = SqliteOrgRepo::new(pool.clone());
1676 let repos = SqliteRepoRepo::new(pool.clone());
1677 let org = org_with(&orgs, "acme").await;
1678
1679 sqlx::query(
1680 "insert into repositories (id, org_id, name, visibility)
1681 values ('r1', ?, 'secret', 'internal')",
1682 )
1683 .bind(org.id.as_str())
1684 .execute(&pool)
1685 .await
1686 .expect("insert");
1687
1688 assert!(
1689 repos.find_by_id(&RepoId::from_trusted("r1")).await.is_err(),
1690 "a visibility we cannot parse must not become a guess"
1691 );
1692 }
1693
1694 #[tokio::test]
1695 async fn listing_returns_only_that_org_ordered_by_name() {
1696 let pool = test_pool().await;
1697 let orgs = SqliteOrgRepo::new(pool.clone());
1698 let repos = SqliteRepoRepo::new(pool);
1699 let mine = org_with(&orgs, "acme").await;
1700 let theirs = org_with(&orgs, "globex").await;
1701
1702 for name in ["zebra", "alpha", "middle"] {
1703 saved_repo(&repos, &mine, name, Visibility::Public).await;
1704 }
1705 saved_repo(&repos, &theirs, "not-mine", Visibility::Public).await;
1706
1707 let listed = repos.list_by_org(&mine.id).await.expect("list");
1708
1709 let names: Vec<&str> = listed.iter().map(|repo| repo.name.as_str()).collect();
1710 assert_eq!(names, vec!["alpha", "middle", "zebra"]);
1711 }
1712
1713 #[tokio::test]
1714 async fn listing_includes_private_repositories() {
1715 let pool = test_pool().await;
1716 let orgs = SqliteOrgRepo::new(pool.clone());
1717 let repos = SqliteRepoRepo::new(pool);
1718 let org = org_with(&orgs, "acme").await;
1719 saved_repo(&repos, &org, "secret", Visibility::Private).await;
1720
1721 // The port returns everything; filtering by visibility is the use case's job, so
1722 // the page and /api cannot end up applying different rules.
1723 assert_eq!(repos.list_by_org(&org.id).await.expect("list").len(), 1);
1724 }
1725
1726 #[tokio::test]
1727 async fn a_missing_repository_is_none_not_an_error() {
1728 let pool = test_pool().await;
1729 let repos = SqliteRepoRepo::new(pool);
1730
1731 let found = repos
1732 .find_by_id(&RepoId::generate())
1733 .await
1734 .expect("lookup should not error");
1735
1736 assert_eq!(found, None);
1737 }
1738
1739 #[tokio::test]
1740 async fn a_deleted_repository_is_gone_and_frees_its_name() {
1741 let pool = test_pool().await;
1742 let orgs = SqliteOrgRepo::new(pool.clone());
1743 let repos = SqliteRepoRepo::new(pool);
1744 let org = org_with(&orgs, "acme").await;
1745 let repo = saved_repo(&repos, &org, "steid", Visibility::Public).await;
1746
1747 repos.delete(&repo.id).await.expect("delete");
1748
1749 assert_eq!(repos.find_by_id(&repo.id).await.expect("lookup"), None);
1750 // The unique (org_id, name) pair is what would fail if the row lingered.
1751 saved_repo(&repos, &org, "steid", Visibility::Private).await;
1752 }
1753
1754 #[tokio::test]
1755 async fn deleting_a_repository_that_is_not_there_succeeds() {
1756 // Idempotent, matching the fake: a second click must not become an error.
1757 let pool = test_pool().await;
1758 let repos = SqliteRepoRepo::new(pool);
1759
1760 assert!(repos.delete(&RepoId::generate()).await.is_ok());
1761 }
1762
1763 #[tokio::test]
1764 async fn deleting_one_repository_leaves_the_others() {
1765 let pool = test_pool().await;
1766 let orgs = SqliteOrgRepo::new(pool.clone());
1767 let repos = SqliteRepoRepo::new(pool);
1768 let org = org_with(&orgs, "acme").await;
1769 let doomed = saved_repo(&repos, &org, "alpha", Visibility::Public).await;
1770 saved_repo(&repos, &org, "zebra", Visibility::Public).await;
1771
1772 repos.delete(&doomed.id).await.expect("delete");
1773
1774 let listed = repos.list_by_org(&org.id).await.expect("list");
1775 assert_eq!(
1776 listed.iter().map(|r| r.name.as_str()).collect::<Vec<_>>(),
1777 vec!["zebra"]
1778 );
1779 }
1780
1781 // --- SqliteTokenRepo ---------------------------------------------------------
1782
1783 /// A pool plus a user to hang tokens off, since the foreign key runs that way.
1784 async fn token_fixture() -> (SqliteTokenRepo, User, User) {
1785 let pool = test_pool().await;
1786 let repos = Repos {
1787 users: SqliteUserRepo::new(pool.clone()),
1788 orgs: SqliteOrgRepo::new(pool.clone()),
1789 memberships: SqliteMembershipRepo::new(pool.clone()),
1790 };
1791
1792 let org = saved_org(&repos, "acme").await;
1793 let owner = saved_user(&repos, "owner@example.com", &org).await;
1794 let other = saved_user(&repos, "other@example.com", &org).await;
1795
1796 (SqliteTokenRepo::new(pool), owner, other)
1797 }
1798
1799 fn issued(user: &User, name: &str, at: u64) -> (PersonalAccessToken, TokenSecret) {
1800 let secret = TokenSecret::generate();
1801 let token = PersonalAccessToken::new(
1802 TokenId::generate(),
1803 user.id.clone(),
1804 name,
1805 &secret,
1806 SystemTime::UNIX_EPOCH + Duration::from_secs(at),
1807 )
1808 .expect("valid token");
1809
1810 (token, secret)
1811 }
1812
1813 #[tokio::test]
1814 async fn a_token_round_trips_through_its_hash() {
1815 let (tokens, owner, _) = token_fixture().await;
1816 let (token, secret) = issued(&owner, "laptop", 1_000);
1817 tokens.save(&token).await.expect("save");
1818
1819 let found = tokens
1820 .find_by_hash(&secret.hash())
1821 .await
1822 .expect("lookup")
1823 .expect("should be found");
1824
1825 assert_eq!(found, token);
1826 assert_eq!(found.name, "laptop");
1827 assert_eq!(found.prefix, secret.display_prefix());
1828 }
1829
1830 #[tokio::test]
1831 async fn an_unknown_hash_finds_nothing() {
1832 let (tokens, owner, _) = token_fixture().await;
1833 let (token, _) = issued(&owner, "laptop", 1_000);
1834 tokens.save(&token).await.expect("save");
1835
1836 let found = tokens
1837 .find_by_hash(&TokenSecret::generate().hash())
1838 .await
1839 .expect("lookup");
1840
1841 assert!(found.is_none());
1842 }
1843
1844 #[tokio::test]
1845 async fn tokens_are_listed_newest_first_and_only_the_users_own() {
1846 let (tokens, owner, other) = token_fixture().await;
1847
1848 for (user, name, at) in [
1849 (&owner, "old", 1_000),
1850 (&owner, "new", 3_000),
1851 (&owner, "middle", 2_000),
1852 (&other, "theirs", 4_000),
1853 ] {
1854 let (token, _) = issued(user, name, at);
1855 tokens.save(&token).await.expect("save");
1856 }
1857
1858 let listed = tokens.list_by_user(&owner.id).await.expect("list");
1859
1860 assert_eq!(
1861 listed
1862 .iter()
1863 .map(|token| token.name.as_str())
1864 .collect::<Vec<_>>(),
1865 vec!["new", "middle", "old"]
1866 );
1867 }
1868
1869 #[tokio::test]
1870 async fn deleting_a_token_stops_it_authenticating() {
1871 // Revocation is a delete, so the credential is gone rather than flagged.
1872 let (tokens, owner, _) = token_fixture().await;
1873 let (token, secret) = issued(&owner, "laptop", 1_000);
1874 tokens.save(&token).await.expect("save");
1875
1876 tokens.delete(&token.id).await.expect("delete");
1877
1878 assert!(
1879 tokens
1880 .find_by_hash(&secret.hash())
1881 .await
1882 .expect("lookup")
1883 .is_none()
1884 );
1885 }
1886
1887 #[tokio::test]
1888 async fn deleting_a_token_that_is_not_there_succeeds() {
1889 let (tokens, _, _) = token_fixture().await;
1890
1891 tokens
1892 .delete(&TokenId::generate())
1893 .await
1894 .expect("deleting nothing should not fail");
1895 }
1896
1897 #[tokio::test]
1898 async fn a_second_token_with_the_same_hash_is_refused() {
1899 // The unique constraint. Two rows answering one credential would make which
1900 // user a token authenticates depend on row order.
1901 let (tokens, owner, other) = token_fixture().await;
1902 let (first, secret) = issued(&owner, "laptop", 1_000);
1903 tokens.save(&first).await.expect("save");
1904
1905 let clash = PersonalAccessToken::new(
1906 TokenId::generate(),
1907 other.id.clone(),
1908 "clash",
1909 &secret,
1910 SystemTime::UNIX_EPOCH,
1911 )
1912 .expect("valid token");
1913
1914 assert!(tokens.save(&clash).await.is_err());
1915 }
1916
1917 #[tokio::test]
1918 async fn a_token_belonging_to_no_user_is_refused() {
1919 // The foreign key. Without `foreign_keys(true)` per connection SQLite ignores it.
1920 let (tokens, _, _) = token_fixture().await;
1921 let secret = TokenSecret::generate();
1922 let orphan = PersonalAccessToken::new(
1923 TokenId::generate(),
1924 UserId::generate(),
1925 "orphan",
1926 &secret,
1927 SystemTime::UNIX_EPOCH,
1928 )
1929 .expect("valid token");
1930
1931 assert!(tokens.save(&orphan).await.is_err());
1932 }
1933
1934 // --- sole_user ----------------------------------------------------------------
1935
1936 #[tokio::test]
1937 async fn there_is_no_sole_user_before_the_instance_is_claimed() {
1938 let repos = repos().await;
1939
1940 assert!(repos.users.sole_user().await.expect("lookup").is_none());
1941 }
1942
1943 #[tokio::test]
1944 async fn the_only_user_is_the_sole_user() {
1945 let repos = repos().await;
1946 let org = saved_org(&repos, "acme").await;
1947 let user = saved_user(&repos, "owner@example.com", &org).await;
1948
1949 let found = repos
1950 .users
1951 .sole_user()
1952 .await
1953 .expect("lookup")
1954 .expect("one user");
1955
1956 assert_eq!(found.id, user.id);
1957 }
1958
1959 #[tokio::test]
1960 async fn a_second_user_makes_the_owner_undefined_rather_than_arbitrary() {
1961 // The root redirects an anonymous visitor to "the owner". With two users that
1962 // question has no answer, and picking whichever row came back first would send
1963 // strangers to a person chosen by storage order.
1964 let repos = repos().await;
1965 let first = saved_org(&repos, "acme").await;
1966 let second = saved_org(&repos, "other").await;
1967 saved_user(&repos, "one@example.com", &first).await;
1968 saved_user(&repos, "two@example.com", &second).await;
1969
1970 assert!(repos.users.sole_user().await.expect("lookup").is_none());
1971 }
1972
1973 // --- SqliteIssueRepo ------------------------------------------------------------
1974
1975 struct IssueFixture {
1976 issues: SqliteIssueRepo,
1977 repo: Repository,
1978 other: Repository,
1979 author: User,
1980 }
1981
1982 /// A pool with two repositories and a user, since every foreign key runs that way.
1983 async fn issue_fixture() -> IssueFixture {
1984 let pool = test_pool().await;
1985 let repos = Repos {
1986 users: SqliteUserRepo::new(pool.clone()),
1987 orgs: SqliteOrgRepo::new(pool.clone()),
1988 memberships: SqliteMembershipRepo::new(pool.clone()),
1989 };
1990 let repo_repo = SqliteRepoRepo::new(pool.clone());
1991
1992 let org = saved_org(&repos, "acme").await;
1993 let author = saved_user(&repos, "owner@example.com", &org).await;
1994
1995 IssueFixture {
1996 issues: SqliteIssueRepo::new(pool),
1997 repo: saved_repo(&repo_repo, &org, "steid", Visibility::Public).await,
1998 other: saved_repo(&repo_repo, &org, "other", Visibility::Public).await,
1999 author,
2000 }
2001 }
2002
2003 fn issue_of(f: &IssueFixture, repo: &Repository, number: u64, title: &str) -> Issue {
2004 Issue::new(
2005 IssueId::generate(),
2006 repo.id.clone(),
2007 IssueNumber::from_trusted(number),
2008 title,
2009 "body",
2010 f.author.id.clone(),
2011 at(1_000),
2012 )
2013 .expect("valid issue")
2014 }
2015
2016 #[tokio::test]
2017 async fn numbering_starts_at_one_and_never_repeats() {
2018 let f = issue_fixture().await;
2019
2020 let first = f.issues.next_number(&f.repo.id).await.expect("allocate");
2021 let second = f.issues.next_number(&f.repo.id).await.expect("allocate");
2022 let third = f.issues.next_number(&f.repo.id).await.expect("allocate");
2023
2024 assert_eq!(
2025 [first.get(), second.get(), third.get()],
2026 [1, 2, 3],
2027 "the sequence starts at 1 and steps by one"
2028 );
2029 }
2030
2031 #[tokio::test]
2032 async fn each_repository_has_its_own_sequence() {
2033 // The number is part of a URL, so `#1` on two repositories has to be two things.
2034 let f = issue_fixture().await;
2035
2036 f.issues.next_number(&f.repo.id).await.expect("allocate");
2037 f.issues.next_number(&f.repo.id).await.expect("allocate");
2038
2039 assert_eq!(
2040 f.issues
2041 .next_number(&f.other.id)
2042 .await
2043 .expect("allocate")
2044 .get(),
2045 1
2046 );
2047 }
2048
2049 #[tokio::test]
2050 async fn an_issue_round_trips_with_every_field() {
2051 let f = issue_fixture().await;
2052 let mut issue = issue_of(&f, &f.repo, 1, "Blame is slow");
2053 issue.close(at(2_000));
2054 f.issues.save(&issue).await.expect("save");
2055
2056 let found = f
2057 .issues
2058 .find_by_number(&f.repo.id, IssueNumber::from_trusted(1))
2059 .await
2060 .expect("lookup")
2061 .expect("the issue is there");
2062
2063 assert_eq!(found, issue);
2064 }
2065
2066 #[tokio::test]
2067 async fn an_issue_is_found_only_under_its_own_repository() {
2068 let f = issue_fixture().await;
2069 f.issues
2070 .save(&issue_of(&f, &f.repo, 1, "Blame is slow"))
2071 .await
2072 .expect("save");
2073
2074 assert!(
2075 f.issues
2076 .find_by_number(&f.other.id, IssueNumber::from_trusted(1))
2077 .await
2078 .expect("lookup")
2079 .is_none()
2080 );
2081 }
2082
2083 #[tokio::test]
2084 async fn two_issues_cannot_share_a_number_on_one_repository() {
2085 // The constraint that makes the sequence load-bearing rather than decorative.
2086 let f = issue_fixture().await;
2087 f.issues
2088 .save(&issue_of(&f, &f.repo, 1, "first"))
2089 .await
2090 .expect("save");
2091
2092 assert!(
2093 f.issues
2094 .save(&issue_of(&f, &f.repo, 1, "second"))
2095 .await
2096 .is_err()
2097 );
2098 }
2099
2100 #[tokio::test]
2101 async fn saving_an_existing_issue_updates_it_rather_than_duplicating_it() {
2102 let f = issue_fixture().await;
2103 let mut issue = issue_of(&f, &f.repo, 1, "Blame is slow");
2104 f.issues.save(&issue).await.expect("save");
2105
2106 issue
2107 .edit("Blame is very slow", "more", at(3_000))
2108 .expect("edit");
2109 issue.close(at(4_000));
2110 f.issues.save(&issue).await.expect("update");
2111
2112 let found = f
2113 .issues
2114 .find_by_number(&f.repo.id, IssueNumber::from_trusted(1))
2115 .await
2116 .expect("lookup")
2117 .expect("still one issue");
2118
2119 assert_eq!(found.title, "Blame is very slow");
2120 assert_eq!(found.state, IssueState::Closed);
2121 assert_eq!(found.closed_at, Some(at(4_000)));
2122 }
2123
2124 #[tokio::test]
2125 async fn a_listing_is_filtered_by_state_and_newest_first() {
2126 let f = issue_fixture().await;
2127 let mut second = issue_of(&f, &f.repo, 2, "issue 2");
2128 for issue in [
2129 issue_of(&f, &f.repo, 1, "issue 1"),
2130 second.clone(),
2131 issue_of(&f, &f.repo, 3, "issue 3"),
2132 ] {
2133 f.issues.save(&issue).await.expect("save");
2134 }
2135
2136 second.close(at(2_000));
2137 f.issues.save(&second).await.expect("close");
2138
2139 let open = f
2140 .issues
2141 .list_by_repo(&f.repo.id, IssueState::Open)
2142 .await
2143 .expect("list");
2144 let shut = f
2145 .issues
2146 .list_by_repo(&f.repo.id, IssueState::Closed)
2147 .await
2148 .expect("list");
2149
2150 assert_eq!(
2151 open.iter().map(|i| i.number.get()).collect::<Vec<_>>(),
2152 vec![3, 1]
2153 );
2154 assert_eq!(
2155 shut.iter().map(|i| i.number.get()).collect::<Vec<_>>(),
2156 vec![2]
2157 );
2158 }
2159
2160 #[tokio::test]
2161 async fn counts_cover_both_states_and_only_this_repository() {
2162 let f = issue_fixture().await;
2163 f.issues
2164 .save(&issue_of(&f, &f.repo, 1, "open one"))
2165 .await
2166 .expect("save");
2167 let mut closed = issue_of(&f, &f.repo, 2, "closed one");
2168 closed.close(at(2_000));
2169 f.issues.save(&closed).await.expect("save");
2170 f.issues
2171 .save(&issue_of(&f, &f.other, 1, "elsewhere"))
2172 .await
2173 .expect("save");
2174
2175 assert_eq!(
2176 f.issues.counts(&f.repo.id).await.expect("counts"),
2177 IssueCounts { open: 1, closed: 1 }
2178 );
2179 }
2180
2181 #[tokio::test]
2182 async fn comments_read_forwards_and_are_counted_per_issue() {
2183 let f = issue_fixture().await;
2184 let issue = issue_of(&f, &f.repo, 1, "Blame is slow");
2185 let quiet = issue_of(&f, &f.repo, 2, "Nobody replied");
2186 f.issues.save(&issue).await.expect("save");
2187 f.issues.save(&quiet).await.expect("save");
2188
2189 for (seconds, body) in [(3_000, "second"), (2_000, "first")] {
2190 f.issues
2191 .add_comment(
2192 &IssueComment::new(
2193 IssueCommentId::generate(),
2194 issue.id.clone(),
2195 f.author.id.clone(),
2196 body,
2197 at(seconds),
2198 )
2199 .expect("valid comment"),
2200 )
2201 .await
2202 .expect("comment");
2203 }
2204
2205 let comments = f.issues.list_comments(&issue.id).await.expect("list");
2206 assert_eq!(
2207 comments.iter().map(|c| c.body.as_str()).collect::<Vec<_>>(),
2208 vec!["first", "second"],
2209 "a conversation reads forwards"
2210 );
2211
2212 let mut counts = f.issues.comment_counts(&f.repo.id).await.expect("counts");
2213 counts.sort_by_key(|(id, _)| id.as_str().to_owned());
2214 let mut expected = vec![(issue.id.clone(), 2), (quiet.id.clone(), 0)];
2215 expected.sort_by_key(|(id, _)| id.as_str().to_owned());
2216
2217 assert_eq!(
2218 counts, expected,
2219 "an issue with no comments still gets a row"
2220 );
2221 }
2222
2223 #[tokio::test]
2224 async fn deleting_a_repository_takes_its_issues_and_their_comments() {
2225 // `on delete cascade`, which is the whole of a comment's lifecycle.
2226 let f = issue_fixture().await;
2227 let issue = issue_of(&f, &f.repo, 1, "Blame is slow");
2228 f.issues.save(&issue).await.expect("save");
2229 f.issues
2230 .add_comment(
2231 &IssueComment::new(
2232 IssueCommentId::generate(),
2233 issue.id.clone(),
2234 f.author.id.clone(),
2235 "looks fixed",
2236 at(2_000),
2237 )
2238 .expect("valid comment"),
2239 )
2240 .await
2241 .expect("comment");
2242
2243 SqliteRepoRepo::new(f.issues.pool.clone())
2244 .delete(&f.repo.id)
2245 .await
2246 .expect("delete");
2247
2248 assert!(
2249 f.issues
2250 .find_by_number(&f.repo.id, IssueNumber::from_trusted(1))
2251 .await
2252 .expect("lookup")
2253 .is_none()
2254 );
2255 assert!(
2256 f.issues
2257 .list_comments(&issue.id)
2258 .await
2259 .expect("list")
2260 .is_empty()
2261 );
2262 }
2263
2264 #[tokio::test]
2265 async fn an_issue_cannot_hang_off_a_repository_that_is_not_there() {
2266 let f = issue_fixture().await;
2267 let orphan = Issue::new(
2268 IssueId::generate(),
2269 RepoId::generate(),
2270 IssueNumber::from_trusted(1),
2271 "nowhere",
2272 "",
2273 f.author.id.clone(),
2274 at(1_000),
2275 )
2276 .expect("valid issue");
2277
2278 assert!(f.issues.save(&orphan).await.is_err());
2279 }
2280
2281 // --- push events, webhooks and their deliveries ---------------------------------
2282
2283 /// A repository with an owner, which is what every row below hangs off.
2284 async fn hooked_repo() -> (sqlx::SqlitePool, Repository, User) {
2285 let pool = test_pool().await;
2286 let orgs = SqliteOrgRepo::new(pool.clone());
2287 let users = SqliteUserRepo::new(pool.clone());
2288 let repos = SqliteRepoRepo::new(pool.clone());
2289
2290 let org = org_with(&orgs, "acme").await;
2291 let user = User::new(
2292 UserId::generate(),
2293 Email::new("dev@example.com").expect("valid email"),
2294 PasswordHash::from_trusted("$argon2id$test"),
2295 org.id.clone(),
2296 );
2297 users.save(&user).await.expect("save user");
2298
2299 let repo = saved_repo(&repos, &org, "steid", Visibility::Public).await;
2300
2301 (pool, repo, user)
2302 }
2303
2304 fn oid(prefix: &str) -> ObjectId {
2305 ObjectId::new(format!("{prefix:0>40}")).expect("valid id")
2306 }
2307
2308 #[tokio::test]
2309 async fn a_push_event_round_trips_with_its_pusher() {
2310 let (pool, repo, user) = hooked_repo().await;
2311 let events = SqlitePushEventRepo::new(pool);
2312
2313 let event = PushEvent::new(
2314 PushEventId::generate(),
2315 repo.id.clone(),
2316 RefName::from_trusted("refs/heads/main"),
2317 oid("a"),
2318 oid("b"),
2319 Some(user.id.clone()),
2320 at(2_000),
2321 )
2322 .expect("valid event");
2323 events.save(&event).await.expect("save");
2324
2325 assert_eq!(
2326 events.find(&event.id).await.expect("lookup"),
2327 Some(event.clone())
2328 );
2329 assert_eq!(
2330 events.list_by_repo(&repo.id, 10).await.expect("list"),
2331 vec![event]
2332 );
2333 }
2334
2335 #[tokio::test]
2336 async fn push_events_come_back_newest_first_and_capped() {
2337 let (pool, repo, user) = hooked_repo().await;
2338 let events = SqlitePushEventRepo::new(pool);
2339
2340 for (seconds, name) in [(1_000, "one"), (3_000, "three"), (2_000, "two")] {
2341 let event = PushEvent::new(
2342 PushEventId::generate(),
2343 repo.id.clone(),
2344 RefName::from_trusted(format!("refs/heads/{name}")),
2345 oid("a"),
2346 oid("b"),
2347 Some(user.id.clone()),
2348 at(seconds),
2349 )
2350 .expect("valid event");
2351 events.save(&event).await.expect("save");
2352 }
2353
2354 let listed = events.list_by_repo(&repo.id, 2).await.expect("list");
2355
2356 assert_eq!(listed.len(), 2);
2357 assert_eq!(listed[0].short_ref(), "three");
2358 assert_eq!(listed[1].short_ref(), "two");
2359 }
2360
2361 #[tokio::test]
2362 async fn a_webhook_round_trips_with_its_secret_and_deliveries_follow_it_out() {
2363 // The cascade is the point: a hook's deliveries are that hook's history and
2364 // mean nothing without it.
2365 let (pool, repo, user) = hooked_repo().await;
2366 let events = SqlitePushEventRepo::new(pool.clone());
2367 let webhooks = SqliteWebhookRepo::new(pool.clone());
2368 let deliveries = SqliteWebhookDeliveryRepo::new(pool);
2369
2370 let hook = Webhook::new(
2371 WebhookId::generate(),
2372 repo.id.clone(),
2373 "https://example.com/hook",
2374 WebhookSecret::generate(),
2375 at(1_000),
2376 PrivateTargets::Refused,
2377 )
2378 .expect("valid hook");
2379 webhooks.save(&hook).await.expect("save");
2380
2381 let found = webhooks
2382 .find(&hook.id)
2383 .await
2384 .expect("lookup")
2385 .expect("hook should exist");
2386 assert_eq!(found.secret.reveal(), hook.secret.reveal());
2387 assert_eq!(found, hook);
2388
2389 let event = PushEvent::new(
2390 PushEventId::generate(),
2391 repo.id.clone(),
2392 RefName::from_trusted("refs/heads/main"),
2393 oid("a"),
2394 oid("b"),
2395 Some(user.id),
2396 at(2_000),
2397 )
2398 .expect("valid event");
2399 events.save(&event).await.expect("save");
2400
2401 for attempt in 1..=2u32 {
2402 deliveries
2403 .save(&WebhookDelivery::record(
2404 WebhookDeliveryId::generate(),
2405 hook.id.clone(),
2406 event.id.clone(),
2407 attempt,
2408 if attempt == 2 { Some(200) } else { None },
2409 "boom",
2410 12,
2411 at(2_000 + u64::from(attempt)),
2412 ))
2413 .await
2414 .expect("save");
2415 }
2416
2417 let listed = deliveries
2418 .list_by_webhook(&hook.id, 10)
2419 .await
2420 .expect("list");
2421 assert_eq!(listed.len(), 2);
2422 assert_eq!(listed[0].attempt, 2, "newest attempt first");
2423 assert!(listed[0].ok);
2424 assert_eq!(listed[1].status, None);
2425 assert_eq!(listed[1].response, "boom");
2426
2427 assert_eq!(
2428 deliveries
2429 .latest_by_webhook(&hook.id)
2430 .await
2431 .expect("lookup")
2432 .map(|delivery| delivery.attempt),
2433 Some(2)
2434 );
2435
2436 webhooks.delete(&hook.id).await.expect("delete");
2437
2438 assert!(webhooks.find(&hook.id).await.expect("lookup").is_none());
2439 assert!(
2440 deliveries
2441 .list_by_webhook(&hook.id, 10)
2442 .await
2443 .expect("list")
2444 .is_empty(),
2445 "deliveries should go with the hook"
2446 );
2447 assert!(
2448 events.find(&event.id).await.expect("lookup").is_some(),
2449 "the event outlives the hook that was told about it"
2450 );
2451 }
2452
2453 #[tokio::test]
2454 async fn a_hook_can_be_turned_off_and_stays_listed() {
2455 let (pool, repo, _) = hooked_repo().await;
2456 let webhooks = SqliteWebhookRepo::new(pool);
2457
2458 let mut hook = Webhook::new(
2459 WebhookId::generate(),
2460 repo.id.clone(),
2461 "https://example.com/hook",
2462 WebhookSecret::generate(),
2463 at(1_000),
2464 PrivateTargets::Refused,
2465 )
2466 .expect("valid hook");
2467 webhooks.save(&hook).await.expect("save");
2468
2469 hook.active = false;
2470 webhooks.save(&hook).await.expect("save again");
2471
2472 let listed = webhooks.list_by_repo(&repo.id).await.expect("list");
2473
2474 assert_eq!(listed.len(), 1);
2475 assert!(!listed[0].active);
2476 }
2477}