steid

@jamesgill /

Rust18.4 KBCode·Blame·History·Raw
1//! What the three Atom feeds read.
2//!
3//! Feeds are read by software that nobody is watching — a reader polls every half hour
4//! whether or not anyone opens it — so these use cases are deliberately the cheapest
5//! reads in Steid. The commit feed is one `git` process; the issue and activity feeds
6//! are none at all.
7//!
8//! Visibility is not re-decided here. Each one goes through the same resolution its
9//! pages do, so a private repository's feed answers `None` for a stranger exactly as
10//! its landing page does, and the activity feed lists only repositories the requester
11//! could have reached by clicking.
12
13use std::time::SystemTime;
14
15use crate::domain::{
16 Actor, CommitEntry, IssueNumber, IssueState, OrgName, PushEvent, RefName, RepoName,
17 repository::{
18 IssueRepository, MembershipRepository, OrgRepository, PushEventRepository, RepoRepository,
19 UserRepository,
20 },
21};
22
23use super::{
24 authz::is_org_member, browse::resolve_revision, error::Result, issue::Handles, port::GitQuery,
25 repo::visible_repo,
26};
27
28/// How many entries a feed carries.
29///
30/// The same fifty the log page shows, and for the same reason: a feed is a window on
31/// what changed recently, not an archive. A reader that has been away longer than fifty
32/// commits has the pages to catch up on.
33pub const FEED_LIMIT: usize = 50;
34
35/// An issue as a feed entry needs it — the body included, which a listing row omits.
36#[derive(Debug, Clone, PartialEq, Eq)]
37pub struct IssueEntry {
38 pub number: IssueNumber,
39 pub title: String,
40 /// Markdown, exactly as written. Rendering it is the web layer's job.
41 pub body: String,
42 pub state: IssueState,
43 /// The author's handle, or `None` if the account is gone — the same answer
44 /// [`IssueSummary`](super::IssueSummary) gives, for the same reason.
45 pub author: Option<OrgName>,
46 pub created_at: SystemTime,
47 pub updated_at: SystemTime,
48}
49
50/// One push, with the repository it landed in.
51///
52/// The repository's name rather than its id: the feed writes a URL out of it, and a
53/// reader of an activity feed is being told *where* something happened first of all.
54#[derive(Debug, Clone, PartialEq, Eq)]
55pub struct ActivityEntry {
56 pub repo: RepoName,
57 pub event: PushEvent,
58 /// Who pushed, or `None` for a deleted account.
59 pub pusher: Option<OrgName>,
60}
61
62/// The most recent commits on a revision, with their message bodies.
63///
64/// `Ok(None)` on the same terms as [`repo_log`](super::repo_log): the repository is not
65/// there, or the reader may not see it, and the route must answer both identically.
66/// An empty repository feeds nothing rather than failing.
67///
68/// **One `git` process**, or two when the revision has to be resolved from `HEAD`.
69#[allow(clippy::too_many_arguments)]
70pub async fn commit_feed(
71 handle: &OrgName,
72 name: &RepoName,
73 rev: Option<&RefName>,
74 actor: &Actor,
75 orgs: &impl OrgRepository,
76 memberships: &impl MembershipRepository,
77 repos: &impl RepoRepository,
78 queries: &impl GitQuery,
79) -> Result<Option<Vec<CommitEntry>>> {
80 if visible_repo(handle, name, actor, orgs, memberships, repos)
81 .await?
82 .is_none()
83 {
84 return Ok(None);
85 }
86
87 let Some(rev) = resolve_revision(handle, name, rev, queries).await? else {
88 return Ok(Some(Vec::new()));
89 };
90
91 Ok(Some(
92 queries.log_entries(handle, name, &rev, FEED_LIMIT).await?,
93 ))
94}
95
96/// The most recent issues on a repository, newest first, open and closed together.
97///
98/// Both states in one list because a feed is a record of what happened, and an issue
99/// being closed does not un-happen its opening. The two are fetched separately —
100/// [`IssueRepository::list_by_repo`] takes a state — and merged here, which is two
101/// queries rather than a port method that exists only for this.
102#[allow(clippy::too_many_arguments)]
103pub async fn issue_feed(
104 actor: &Actor,
105 handle: &OrgName,
106 name: &RepoName,
107 orgs: &impl OrgRepository,
108 memberships: &impl MembershipRepository,
109 repos: &impl RepoRepository,
110 issues: &impl IssueRepository,
111 users: &impl UserRepository,
112) -> Result<Option<Vec<IssueEntry>>> {
113 let Some((_, repo)) = visible_repo(handle, name, actor, orgs, memberships, repos).await? else {
114 return Ok(None);
115 };
116
117 // The newest `FEED_LIMIT` of each state, because the merge below keeps at most that
118 // many overall — anything older than the 50th open issue cannot survive it.
119 let mut listed = issues
120 .list_by_repo(&repo.id, IssueState::Open, 0, FEED_LIMIT)
121 .await?;
122 listed.extend(
123 issues
124 .list_by_repo(&repo.id, IssueState::Closed, 0, FEED_LIMIT)
125 .await?,
126 );
127
128 // Newest first, ties broken by descending number — the order each state's listing
129 // already promises, reasserted because merging two of them loses it.
130 listed.sort_by(|a, b| {
131 b.created_at
132 .cmp(&a.created_at)
133 .then_with(|| b.number.get().cmp(&a.number.get()))
134 });
135 listed.truncate(FEED_LIMIT);
136
137 let mut handles = Handles::default();
138 let mut entries = Vec::with_capacity(listed.len());
139
140 for issue in listed {
141 entries.push(IssueEntry {
142 author: handles.of(&issue.author_id, orgs, users).await?,
143 number: issue.number,
144 title: issue.title,
145 body: issue.body,
146 state: issue.state,
147 created_at: issue.created_at,
148 updated_at: issue.updated_at,
149 });
150 }
151
152 Ok(Some(entries))
153}
154
155/// One owner's recent pushes, across every repository the reader may see.
156///
157/// `Ok(None)` means no such handle, which is the profile page's 404. A handle whose
158/// repositories are all private answers with an empty list to a stranger — the same
159/// silence [`list_repos`](super::list_repos) gives, and for the same reason: a count
160/// would leak both the existence and the number of them.
161///
162/// **No `git` processes.** Everything an entry says comes out of the `push_events`
163/// table; the pages an entry links to do the reading when somebody follows the link.
164pub async fn activity_feed(
165 handle: &OrgName,
166 actor: &Actor,
167 orgs: &impl OrgRepository,
168 memberships: &impl MembershipRepository,
169 repos: &impl RepoRepository,
170 events: &impl PushEventRepository,
171 users: &impl UserRepository,
172) -> Result<Option<Vec<ActivityEntry>>> {
173 let Some(org) = orgs.find_by_name(handle).await? else {
174 return Ok(None);
175 };
176
177 // Resolved once for the whole listing, exactly as `list_repos` does it: membership
178 // cannot change mid-read, and asking per repository would be a query per repository.
179 let is_member = is_org_member(&org, actor, memberships).await?;
180
181 let visible: Vec<_> = repos
182 .list_by_org(&org.id)
183 .await?
184 .into_iter()
185 .filter(|repo| repo.visibility.is_public() || is_member)
186 .collect();
187
188 let ids: Vec<_> = visible.iter().map(|repo| repo.id.clone()).collect();
189 let recent = events.list_recent(&ids, FEED_LIMIT).await?;
190
191 let mut handles = Handles::default();
192 let mut entries = Vec::with_capacity(recent.len());
193
194 for event in recent {
195 // The repository is in `visible` by construction — `list_recent` was asked
196 // about exactly these — so a miss would be a storage inconsistency rather than
197 // a permission question, and skipping it is the safe reading either way.
198 let Some(repo) = visible.iter().find(|repo| repo.id == event.repo_id) else {
199 continue;
200 };
201
202 let pusher = match &event.pusher {
203 Some(id) => handles.of(id, orgs, users).await?,
204 None => None,
205 };
206
207 entries.push(ActivityEntry {
208 repo: repo.name.clone(),
209 event,
210 pusher,
211 });
212 }
213
214 Ok(Some(entries))
215}
216
217#[cfg(test)]
218mod tests {
219 use std::time::Duration;
220
221 use super::*;
222 use crate::{
223 domain::{
224 CommitSummary, Email, Issue, Membership, MembershipId, ObjectId, OrgId, Organization,
225 PasswordHash, PushEventId, RepoId, Repository, Role, User, UserId, Visibility,
226 repository::{MembershipRepository, OrgRepository, RepoRepository, UserRepository},
227 },
228 infrastructure::{
229 git::InMemoryGitQuery,
230 repository::{
231 InMemoryIssueRepo, InMemoryMembershipRepo, InMemoryOrgRepo, InMemoryPushEventRepo,
232 InMemoryRepoRepo, InMemoryUserRepo,
233 },
234 },
235 };
236
237 struct Fixture {
238 orgs: InMemoryOrgRepo,
239 memberships: InMemoryMembershipRepo,
240 repos: InMemoryRepoRepo,
241 issues: InMemoryIssueRepo,
242 events: InMemoryPushEventRepo,
243 users: InMemoryUserRepo,
244 owner: UserId,
245 org: Organization,
246 public: Repository,
247 private: Repository,
248 }
249
250 fn at(seconds: u64) -> SystemTime {
251 SystemTime::UNIX_EPOCH + Duration::from_secs(seconds)
252 }
253
254 fn handle() -> OrgName {
255 OrgName::new("ada").expect("valid handle")
256 }
257
258 async fn fixture() -> Fixture {
259 let orgs = InMemoryOrgRepo::new();
260 let memberships = InMemoryMembershipRepo::new();
261 let repos = InMemoryRepoRepo::new();
262 let issues = InMemoryIssueRepo::new();
263 let events = InMemoryPushEventRepo::new();
264 let users = InMemoryUserRepo::new();
265
266 let org = Organization::new(OrgId::generate(), "ada", None).expect("valid org");
267 orgs.save(&org).await.expect("save org");
268
269 let owner = UserId::generate();
270 memberships
271 .save(&Membership::new(
272 MembershipId::generate(),
273 org.id.clone(),
274 owner.clone(),
275 Role::Owner,
276 ))
277 .await
278 .expect("save membership");
279 users
280 .save(&User::new(
281 owner.clone(),
282 Email::new("ada@example.com").expect("valid email"),
283 PasswordHash::from_trusted("$argon2id$test"),
284 org.id.clone(),
285 ))
286 .await
287 .expect("save user");
288
289 let public = Repository::new(
290 RepoId::generate(),
291 org.id.clone(),
292 "steid",
293 None,
294 Visibility::Public,
295 at(1_000),
296 )
297 .expect("valid repo");
298 repos.save(&public).await.expect("save repo");
299
300 let private = Repository::new(
301 RepoId::generate(),
302 org.id.clone(),
303 "secret",
304 None,
305 Visibility::Private,
306 at(1_000),
307 )
308 .expect("valid repo");
309 repos.save(&private).await.expect("save repo");
310
311 Fixture {
312 orgs,
313 memberships,
314 repos,
315 issues,
316 events,
317 users,
318 owner,
319 org,
320 public,
321 private,
322 }
323 }
324
325 async fn push(f: &Fixture, repo: &Repository, name: &str, seconds: u64) {
326 let event = PushEvent::new(
327 PushEventId::generate(),
328 repo.id.clone(),
329 RefName::from_trusted(format!("refs/heads/{name}")),
330 ObjectId::from_trusted("a".repeat(40)),
331 ObjectId::from_trusted("b".repeat(40)),
332 Some(f.owner.clone()),
333 at(seconds),
334 )
335 .expect("valid event");
336 f.events.save(&event).await.expect("save event");
337 }
338
339 async fn open_issue(f: &Fixture, number: u64, title: &str, seconds: u64) -> Issue {
340 let issue = Issue::new(
341 crate::domain::IssueId::generate(),
342 f.public.id.clone(),
343 IssueNumber::new(number).expect("valid number"),
344 title,
345 "a **body**",
346 f.owner.clone(),
347 at(seconds),
348 )
349 .expect("valid issue");
350 f.issues.save(&issue).await.expect("save issue");
351 issue
352 }
353
354 fn queries() -> InMemoryGitQuery {
355 InMemoryGitQuery::new()
356 .with_log(vec![CommitSummary {
357 id: ObjectId::from_trusted("c".repeat(40)),
358 summary: "first".to_owned(),
359 author_name: "Ada".to_owned(),
360 committed_at: at(2_000),
361 }])
362 .with_commit_body(&"c".repeat(40), "why it happened")
363 }
364
365 // --- commits ------------------------------------------------------------------
366
367 #[tokio::test]
368 async fn a_public_repository_feeds_its_commits_to_a_stranger() {
369 let f = fixture().await;
370
371 let entries = commit_feed(
372 &handle(),
373 &f.public.name,
374 None,
375 &Actor::Anonymous,
376 &f.orgs,
377 &f.memberships,
378 &f.repos,
379 &queries(),
380 )
381 .await
382 .expect("read")
383 .expect("visible");
384
385 assert_eq!(entries.len(), 1);
386 assert_eq!(entries[0].commit.summary, "first");
387 assert_eq!(entries[0].body, "why it happened");
388 }
389
390 #[tokio::test]
391 async fn a_private_repository_feeds_nothing_to_a_stranger_and_everything_to_its_owner() {
392 let f = fixture().await;
393
394 let anonymous = commit_feed(
395 &handle(),
396 &f.private.name,
397 None,
398 &Actor::Anonymous,
399 &f.orgs,
400 &f.memberships,
401 &f.repos,
402 &queries(),
403 )
404 .await
405 .expect("read");
406
407 assert_eq!(
408 anonymous, None,
409 "a private feed must be indistinguishable from one that does not exist"
410 );
411
412 assert!(
413 commit_feed(
414 &handle(),
415 &f.private.name,
416 None,
417 &Actor::User(f.owner.clone()),
418 &f.orgs,
419 &f.memberships,
420 &f.repos,
421 &queries(),
422 )
423 .await
424 .expect("read")
425 .is_some()
426 );
427 }
428
429 #[tokio::test]
430 async fn an_empty_repository_feeds_an_empty_list_rather_than_failing() {
431 let f = fixture().await;
432
433 let entries = commit_feed(
434 &handle(),
435 &f.public.name,
436 None,
437 &Actor::Anonymous,
438 &f.orgs,
439 &f.memberships,
440 &f.repos,
441 &InMemoryGitQuery::empty(),
442 )
443 .await
444 .expect("read")
445 .expect("visible");
446
447 assert!(entries.is_empty());
448 }
449
450 // --- issues -------------------------------------------------------------------
451
452 #[tokio::test]
453 async fn the_issue_feed_carries_both_states_newest_first_with_bodies() {
454 let f = fixture().await;
455 open_issue(&f, 1, "oldest", 1_000).await;
456 let mut closed = open_issue(&f, 2, "middle", 2_000).await;
457 closed.close(at(3_000));
458 f.issues.save(&closed).await.expect("save issue");
459 open_issue(&f, 3, "newest", 4_000).await;
460
461 let entries = issue_feed(
462 &Actor::Anonymous,
463 &handle(),
464 &f.public.name,
465 &f.orgs,
466 &f.memberships,
467 &f.repos,
468 &f.issues,
469 &f.users,
470 )
471 .await
472 .expect("read")
473 .expect("visible");
474
475 assert_eq!(
476 entries
477 .iter()
478 .map(|entry| entry.title.as_str())
479 .collect::<Vec<_>>(),
480 vec!["newest", "middle", "oldest"],
481 "a closed issue still happened, so it stays in the feed in date order"
482 );
483 assert_eq!(entries[0].body, "a **body**");
484 assert_eq!(entries[0].author.as_ref().map(OrgName::as_str), Some("ada"));
485 assert!(!entries[1].state.is_open());
486 }
487
488 #[tokio::test]
489 async fn a_private_repository_feeds_no_issues_to_a_stranger() {
490 let f = fixture().await;
491
492 assert_eq!(
493 issue_feed(
494 &Actor::Anonymous,
495 &handle(),
496 &f.private.name,
497 &f.orgs,
498 &f.memberships,
499 &f.repos,
500 &f.issues,
501 &f.users,
502 )
503 .await
504 .expect("read"),
505 None
506 );
507 }
508
509 // --- activity -----------------------------------------------------------------
510
511 #[tokio::test]
512 async fn the_activity_feed_hides_pushes_to_repositories_a_stranger_cannot_see() {
513 let f = fixture().await;
514 push(&f, &f.public, "main", 1_000).await;
515 push(&f, &f.private, "main", 2_000).await;
516
517 let entries = activity_feed(
518 &handle(),
519 &Actor::Anonymous,
520 &f.orgs,
521 &f.memberships,
522 &f.repos,
523 &f.events,
524 &f.users,
525 )
526 .await
527 .expect("read")
528 .expect("the handle exists");
529
530 assert_eq!(entries.len(), 1);
531 assert_eq!(entries[0].repo.as_str(), "steid");
532 assert_eq!(entries[0].pusher.as_ref().map(OrgName::as_str), Some("ada"));
533 }
534
535 #[tokio::test]
536 async fn the_owner_sees_their_private_pushes_newest_first() {
537 let f = fixture().await;
538 push(&f, &f.public, "main", 1_000).await;
539 push(&f, &f.private, "main", 2_000).await;
540
541 let entries = activity_feed(
542 &handle(),
543 &Actor::User(f.owner.clone()),
544 &f.orgs,
545 &f.memberships,
546 &f.repos,
547 &f.events,
548 &f.users,
549 )
550 .await
551 .expect("read")
552 .expect("the handle exists");
553
554 assert_eq!(
555 entries
556 .iter()
557 .map(|entry| entry.repo.as_str())
558 .collect::<Vec<_>>(),
559 vec!["secret", "steid"]
560 );
561 }
562
563 #[tokio::test]
564 async fn an_unknown_handle_has_no_activity_feed_at_all() {
565 let f = fixture().await;
566
567 assert_eq!(
568 activity_feed(
569 &OrgName::new("nobody").expect("valid"),
570 &Actor::Anonymous,
571 &f.orgs,
572 &f.memberships,
573 &f.repos,
574 &f.events,
575 &f.users,
576 )
577 .await
578 .expect("read"),
579 None,
580 "no such handle is a 404, not an empty feed"
581 );
582
583 // And a handle that exists but has nothing to show is the other answer.
584 assert_eq!(
585 activity_feed(
586 &f.org.name,
587 &Actor::Anonymous,
588 &f.orgs,
589 &f.memberships,
590 &f.repos,
591 &f.events,
592 &f.users,
593 )
594 .await
595 .expect("read"),
596 Some(Vec::new())
597 );
598 }
599}