steid

@jamesgill /

Rust13.1 KBCode·Blame·History·Raw
1//! Recording what a push did.
2//!
3//! **The event is recorded from the application, not from a `post-receive` hook script
4//! inside the bare repository.** The refs are snapshotted before the receive-pack RPC
5//! and again after it, and every ref whose id moved becomes an event. Two extra
6//! `for-each-ref` per push is the accepted cost.
7//!
8//! The alternative — a hook script in every repository — was considered and rejected
9//! *for now*: the application already knows the actor, whereas a script would have to be
10//! installed on repository creation **and on boot** (so that repositories created by an
11//! older version get it), kept in sync with the binary, and would still need a channel
12//! back into the process to reach the database. It is the right answer if the per-push
13//! cost ever matters; it is two problems where this is none.
14//!
15//! A snapshot diff has one property a hook does not: it reports what *actually* changed
16//! on disk. A hook is told what receive-pack intends, before another hook can reject it.
17
18use std::time::SystemTime;
19
20use crate::domain::{
21 Actor, DomainError, ObjectId, OrgName, PushEvent, PushEventId, RefName, RepoName,
22 repository::{MembershipRepository, OrgRepository, PushEventRepository, RepoRepository},
23};
24
25use super::{
26 authz::is_org_owner,
27 error::Result,
28 port::{GitQuery, GitQueryError},
29};
30
31/// Every ref and what it pointed at, at one moment.
32///
33/// A plain list rather than a map because it is produced by one port call and consumed
34/// by one comparison, and both are small.
35pub type RefSnapshot = Vec<(RefName, ObjectId)>;
36
37/// One ref that moved between two snapshots.
38#[derive(Debug, Clone, PartialEq, Eq)]
39pub struct RefChange {
40 pub name: RefName,
41 /// The zero id when the ref was created.
42 pub before: ObjectId,
43 /// The zero id when the ref was deleted.
44 pub after: ObjectId,
45}
46
47/// Reads every ref and the object it names.
48///
49/// Fails soft nowhere: a snapshot that could not be taken is a real failure, and the
50/// caller decides whether to give up on recording rather than pretending the repository
51/// had no refs — which would turn a failed read into a flood of spurious "created"
52/// events on the next push.
53pub async fn snapshot_refs(
54 handle: &OrgName,
55 name: &RepoName,
56 git: &impl GitQuery,
57) -> std::result::Result<RefSnapshot, GitQueryError> {
58 git.ref_snapshot(handle, name).await
59}
60
61/// What changed between two snapshots, ordered by ref name.
62///
63/// Pure, so the rule that decides what counts as a change is testable without a
64/// repository. Ordered so a `git push --all` records its events in a stable order
65/// rather than whatever git listed.
66pub fn ref_changes(
67 before: &[(RefName, ObjectId)],
68 after: &[(RefName, ObjectId)],
69) -> Vec<RefChange> {
70 let zero = PushEvent::zero();
71 let find = |snapshot: &[(RefName, ObjectId)], wanted: &RefName| {
72 snapshot
73 .iter()
74 .find(|(name, _)| name == wanted)
75 .map(|(_, id)| id.clone())
76 };
77
78 let mut changes = Vec::new();
79
80 // Moved and deleted refs come from walking `before`; created ones from walking
81 // `after` for names that were not there. Two passes rather than a merged sort,
82 // because a snapshot is tens of entries and clarity is worth more here.
83 for (name, was) in before {
84 let now = find(after, name).unwrap_or_else(|| zero.clone());
85
86 if &now != was {
87 changes.push(RefChange {
88 name: name.clone(),
89 before: was.clone(),
90 after: now,
91 });
92 }
93 }
94
95 for (name, now) in after {
96 if find(before, name).is_none() {
97 changes.push(RefChange {
98 name: name.clone(),
99 before: zero.clone(),
100 after: now.clone(),
101 });
102 }
103 }
104
105 changes.sort_by(|a, b| a.name.as_str().cmp(b.name.as_str()));
106 changes
107}
108
109/// Records one event per ref the push moved.
110///
111/// Takes an `Actor` and re-checks that they own the repository, even though nothing
112/// reaches here without `serve_git` having already said so. Two reasons: the rule lives
113/// in one place regardless of transport, and this runs in a task spawned *after* the
114/// response has begun streaming — far enough from the check that repeating it is
115/// cheaper than reasoning about whether it still holds.
116///
117/// An absent or invisible repository records nothing and is not an error: a repository
118/// can be deleted while a push to it is in flight, and there is nothing useful to do
119/// about that.
120#[allow(clippy::too_many_arguments)]
121pub async fn record_push(
122 actor: &Actor,
123 handle: &OrgName,
124 name: &RepoName,
125 before: &[(RefName, ObjectId)],
126 after: &[(RefName, ObjectId)],
127 now: SystemTime,
128 orgs: &impl OrgRepository,
129 memberships: &impl MembershipRepository,
130 repos: &impl RepoRepository,
131 events: &impl PushEventRepository,
132) -> Result<Vec<PushEvent>> {
133 let Some(org) = orgs.find_by_name(handle).await? else {
134 return Ok(Vec::new());
135 };
136
137 let Some(repo) = repos.find_by_org_and_name(&org.id, name).await? else {
138 return Ok(Vec::new());
139 };
140
141 if !is_org_owner(&org, actor, memberships).await? {
142 return Err(DomainError::Forbidden.into());
143 }
144
145 let mut recorded = Vec::new();
146
147 for change in ref_changes(before, after) {
148 let event = PushEvent::new(
149 PushEventId::generate(),
150 repo.id.clone(),
151 change.name,
152 change.before,
153 change.after,
154 actor.user_id().cloned(),
155 now,
156 )?;
157
158 events.save(&event).await?;
159 recorded.push(event);
160 }
161
162 Ok(recorded)
163}
164
165#[cfg(test)]
166mod tests {
167 use super::*;
168 use crate::{
169 domain::{
170 Membership, MembershipId, OrgId, Organization, RepoId, Repository, Role, UserId,
171 Visibility,
172 },
173 infrastructure::repository::{
174 InMemoryMembershipRepo, InMemoryOrgRepo, InMemoryPushEventRepo, InMemoryRepoRepo,
175 },
176 };
177
178 fn oid(prefix: &str) -> ObjectId {
179 ObjectId::new(format!("{prefix:0>40}")).expect("valid id")
180 }
181
182 fn snapshot(refs: &[(&str, &str)]) -> RefSnapshot {
183 refs.iter()
184 .map(|(name, id)| (RefName::from_trusted(*name), oid(id)))
185 .collect()
186 }
187
188 // --- what counts as a change ---------------------------------------------------
189
190 #[test]
191 fn nothing_moving_is_no_change() {
192 let refs = snapshot(&[("refs/heads/main", "a"), ("refs/tags/v1", "b")]);
193
194 assert_eq!(ref_changes(&refs, &refs), Vec::new());
195 }
196
197 #[test]
198 fn a_moved_ref_carries_both_ends() {
199 let changes = ref_changes(
200 &snapshot(&[("refs/heads/main", "a")]),
201 &snapshot(&[("refs/heads/main", "b")]),
202 );
203
204 assert_eq!(changes.len(), 1);
205 assert_eq!(changes[0].before, oid("a"));
206 assert_eq!(changes[0].after, oid("b"));
207 }
208
209 #[test]
210 fn a_created_ref_has_the_zero_id_before_it() {
211 let changes = ref_changes(&[], &snapshot(&[("refs/heads/main", "a")]));
212
213 assert_eq!(changes.len(), 1);
214 assert_eq!(changes[0].before, PushEvent::zero());
215 assert_eq!(changes[0].after, oid("a"));
216 }
217
218 #[test]
219 fn a_deleted_ref_has_the_zero_id_after_it() {
220 let changes = ref_changes(&snapshot(&[("refs/heads/gone", "a")]), &[]);
221
222 assert_eq!(changes.len(), 1);
223 assert_eq!(changes[0].before, oid("a"));
224 assert_eq!(changes[0].after, PushEvent::zero());
225 }
226
227 #[test]
228 fn a_push_of_several_refs_is_reported_in_a_stable_order() {
229 // `git push --all` moves everything at once, and a listing that reshuffled per
230 // push would be unreadable.
231 let changes = ref_changes(
232 &snapshot(&[("refs/heads/main", "a"), ("refs/heads/old", "c")]),
233 &snapshot(&[
234 ("refs/heads/main", "b"),
235 ("refs/heads/feat", "d"),
236 ("refs/tags/v1", "e"),
237 ]),
238 );
239
240 assert_eq!(
241 changes
242 .iter()
243 .map(|change| change.name.as_str())
244 .collect::<Vec<_>>(),
245 [
246 "refs/heads/feat",
247 "refs/heads/main",
248 "refs/heads/old",
249 "refs/tags/v1"
250 ]
251 );
252 }
253
254 // --- recording -----------------------------------------------------------------
255
256 struct Fixture {
257 orgs: InMemoryOrgRepo,
258 memberships: InMemoryMembershipRepo,
259 repos: InMemoryRepoRepo,
260 events: InMemoryPushEventRepo,
261 owner: Actor,
262 member: Actor,
263 handle: OrgName,
264 repo_id: RepoId,
265 }
266
267 async fn fixture() -> Fixture {
268 let orgs = InMemoryOrgRepo::new();
269 let memberships = InMemoryMembershipRepo::new();
270 let repos = InMemoryRepoRepo::new();
271
272 let org = Organization::new(OrgId::generate(), "acme", None).expect("valid org");
273 orgs.save(&org).await.expect("save org");
274
275 let owner = UserId::generate();
276 let member = UserId::generate();
277
278 for (user, role) in [(&owner, Role::Owner), (&member, Role::Member)] {
279 memberships
280 .save(&Membership::new(
281 MembershipId::generate(),
282 org.id.clone(),
283 user.clone(),
284 role,
285 ))
286 .await
287 .expect("save membership");
288 }
289
290 let repo = Repository::new(
291 RepoId::generate(),
292 org.id.clone(),
293 "steid",
294 None,
295 Visibility::Public,
296 SystemTime::UNIX_EPOCH,
297 )
298 .expect("valid repo");
299 repos.save(&repo).await.expect("save repo");
300
301 Fixture {
302 orgs,
303 memberships,
304 repos,
305 events: InMemoryPushEventRepo::new(),
306 owner: Actor::User(owner),
307 member: Actor::User(member),
308 handle: org.name,
309 repo_id: repo.id,
310 }
311 }
312
313 impl Fixture {
314 async fn record(
315 &self,
316 actor: &Actor,
317 name: &str,
318 before: &[(&str, &str)],
319 after: &[(&str, &str)],
320 ) -> Result<Vec<PushEvent>> {
321 record_push(
322 actor,
323 &self.handle,
324 &RepoName::new(name).expect("valid name"),
325 &snapshot(before),
326 &snapshot(after),
327 SystemTime::UNIX_EPOCH,
328 &self.orgs,
329 &self.memberships,
330 &self.repos,
331 &self.events,
332 )
333 .await
334 }
335 }
336
337 #[tokio::test]
338 async fn a_push_records_one_event_per_ref_that_moved() {
339 let f = fixture().await;
340
341 let recorded = f
342 .record(
343 &f.owner,
344 "steid",
345 &[("refs/heads/main", "a")],
346 &[("refs/heads/main", "b"), ("refs/tags/v1", "c")],
347 )
348 .await
349 .expect("should record");
350
351 assert_eq!(recorded.len(), 2);
352
353 let stored = f
354 .events
355 .list_by_repo(&f.repo_id, 10)
356 .await
357 .expect("should list");
358 assert_eq!(stored.len(), 2);
359 assert!(
360 stored
361 .iter()
362 .all(|event| event.pusher == f.owner.user_id().cloned())
363 );
364 }
365
366 #[tokio::test]
367 async fn a_push_that_moved_nothing_records_nothing() {
368 // A `git push` with nothing to send still runs the RPC.
369 let f = fixture().await;
370
371 let recorded = f
372 .record(
373 &f.owner,
374 "steid",
375 &[("refs/heads/main", "a")],
376 &[("refs/heads/main", "a")],
377 )
378 .await
379 .expect("should record");
380
381 assert!(recorded.is_empty());
382 assert!(
383 f.events
384 .list_by_repo(&f.repo_id, 10)
385 .await
386 .expect("list")
387 .is_empty()
388 );
389 }
390
391 #[tokio::test]
392 async fn only_an_owner_can_have_a_push_recorded_for_them() {
393 // Repeated here rather than trusted from `serve_git`, because this runs in a
394 // task spawned after the response has begun streaming.
395 let f = fixture().await;
396
397 for actor in [&f.member, &Actor::Anonymous] {
398 let error = f
399 .record(actor, "steid", &[], &[("refs/heads/main", "a")])
400 .await
401 .expect_err("should refuse");
402
403 assert!(matches!(
404 error,
405 super::super::Error::Domain(DomainError::Forbidden)
406 ));
407 }
408
409 assert!(
410 f.events
411 .list_by_repo(&f.repo_id, 10)
412 .await
413 .expect("list")
414 .is_empty()
415 );
416 }
417
418 #[tokio::test]
419 async fn a_repository_deleted_mid_push_records_nothing_rather_than_failing() {
420 let f = fixture().await;
421
422 let recorded = f
423 .record(&f.owner, "gone", &[], &[("refs/heads/main", "a")])
424 .await
425 .expect("should not fail");
426
427 assert!(recorded.is_empty());
428 }
429}