Skip to content
1,141 linesCodeBlameRaw
1//! Events published on the bus, and the events service that carries them.
2//! Mirrors `packages/contracts/src/events.ts`.
3
4use serde::Serialize;
5
6/// The key in an event's `data` that marks what a workflow job's own token
7/// (`G1T_TOKEN`) did, with the run's id as its value. The actions service
8/// starts no workflows for such an event, as GitHub starts none for what
9/// its `GITHUB_TOKEN` does, so a workflow cannot set itself off.
10pub const CAUSED_BY_JOB: &str = "causedByJob";
11
12/// The run whose job's token caused an event, if one did.
13pub fn caused_by_job(data: &serde_json::Value) -> Option<&str> {
14 data[CAUSED_BY_JOB].as_str().filter(|run| !run.is_empty())
15}
16
17/// The run whose job's token `actor` is acting with, if it is one.
18pub fn job_run_of(actor: &crate::User) -> Option<&str> {
19 actor.token.as_deref().and_then(|token| token.job.as_ref()).map(|job| job.run_id.as_str())
20}
21
22/// `data` as JSON, marked as a workflow job's doing when `actor` acted
23/// with a job's token (see [`CAUSED_BY_JOB`]).
24pub fn marked<T: Serialize>(data: T, actor: Option<&crate::User>) -> serde_json::Value {
25 let mut value = serde_json::to_value(data).unwrap_or(serde_json::Value::Null);
26 if let (Some(run), serde_json::Value::Object(map)) = (actor.and_then(job_run_of), &mut value) {
27 map.insert(CAUSED_BY_JOB.to_owned(), serde_json::Value::String(run.to_owned()));
28 }
29 value
30}
31
32/// `data` as JSON, marked as a workflow job's doing when the event it
33/// follows from (`cause`, its data) was: a push by a job's token moves its
34/// pull request, and that starts no workflows either.
35pub fn carried<T: Serialize>(data: T, cause: &serde_json::Value) -> serde_json::Value {
36 let mut value = serde_json::to_value(data).unwrap_or(serde_json::Value::Null);
37 if let (Some(run), serde_json::Value::Object(map)) = (caused_by_job(cause), &mut value) {
38 map.insert(CAUSED_BY_JOB.to_owned(), serde_json::Value::String(run.to_owned()));
39 }
40 value
41}
42
43/// What a publisher supplies; the bus fills in the id and time.
44#[derive(Debug, Serialize)]
45#[serde(rename_all = "camelCase")]
46pub struct NewEvent<T: Serialize> {
47 #[serde(rename = "type")]
48 pub kind: &'static str,
49 /// The service that published it.
50 pub source: &'static str,
51 /// The repo the event concerns.
52 pub repo_id: Option<String>,
53 /// The user or agent that caused it, if any.
54 pub actor: Option<String>,
55 pub data: T,
56}
57
58#[derive(Debug, Serialize)]
59#[serde(rename_all = "camelCase")]
60pub struct RepoCreated {
61 pub repo_id: String,
62 pub namespace: String,
63 pub name: String,
64 pub is_private: bool,
65}
66
67/// The payload of `repo.collaborator_added`, `repo.collaborator_removed`
68/// and `repo.collaborator_role_changed`: a person's own role on one
69/// repository (see `access`). `role` is the role they have now (null once
70/// removed); `previous_role` what they had before (null when added).
71#[derive(Debug, Serialize)]
72#[serde(rename_all = "camelCase")]
73pub struct RepoCollaborator {
74 pub repo_id: String,
75 pub namespace: String,
76 pub name: String,
77 pub username: String,
78 pub role: Option<crate::access::RepoRole>,
79 pub previous_role: Option<crate::access::RepoRole>,
80}
81
82#[derive(Debug, Serialize)]
83#[serde(rename_all = "camelCase")]
84pub struct RepoForked {
85 pub repo_id: String,
86 pub source_repo_id: String,
87 pub pull_id: String,
88}
89
90/// One branch or tag moved by a push. `after` is the commit it points to now.
91#[derive(Debug, Serialize)]
92#[serde(rename_all = "camelCase")]
93pub struct GitPush {
94 pub repo_id: String,
95 /// The full ref, such as `refs/heads/main`.
96 #[serde(rename = "ref")]
97 pub git_ref: String,
98 /// Where it pointed before; absent for a new branch or tag.
99 #[serde(skip_serializing_if = "Option::is_none")]
100 pub before: Option<String>,
101 pub after: String,
102 /// Whether the ref is the repository's default branch.
103 pub default_branch: bool,
104 /// Set when the push was too large to scan for secrets before it was
105 /// stored, and was let through: the security service scans
106 /// `before..after` after it landed. Absent otherwise.
107 #[serde(skip_serializing_if = "std::ops::Not::not")]
108 pub unscanned: bool,
109 /// Set when a workflow job's token pushed: the run's id (see
110 /// [`CAUSED_BY_JOB`]). Absent otherwise.
111 #[serde(rename = "causedByJob", skip_serializing_if = "Option::is_none")]
112 pub caused_by_job: Option<String>,
113 /// Set when the push was copied in from the remote a mirror follows,
114 /// not made on g1t. Absent otherwise.
115 #[serde(skip_serializing_if = "std::ops::Not::not")]
116 pub mirrored: bool,
117 /// The repository's mirror state when the push landed (see
118 /// [`crate::mirrors`]): workflows and deployments follow it. Absent for
119 /// a repository that leads.
120 #[serde(skip_serializing_if = "Option::is_none")]
121 pub mirror: Option<crate::mirrors::RepoMirror>,
122}
123
124/// The payload of `issue.opened`, `issue.updated`, `issue.assigned`,
125/// `issue.labeled`, `issue.unlabeled`, `issue.milestoned`,
126/// `issue.demilestoned`, `issue.closed` and `issue.reopened`; each uses
127/// the fields that apply to it.
128#[derive(Debug, Default, Serialize)]
129#[serde(rename_all = "camelCase")]
130pub struct IssueEvent {
131 pub issue_id: String,
132 pub repo_id: String,
133 pub number: u32,
134 /// Who opened it: g1t, for one its agent filed while at work.
135 #[serde(skip_serializing_if = "Option::is_none")]
136 pub author: Option<crate::credentials::Principal>,
137 /// For an issue g1t's agent filed: the person it was working for.
138 #[serde(skip_serializing_if = "Option::is_none")]
139 pub requested_by: Option<crate::credentials::Principal>,
140 #[serde(skip_serializing_if = "Option::is_none")]
141 pub title: Option<String>,
142 /// On close: `completed` or `not_planned`.
143 #[serde(skip_serializing_if = "Option::is_none")]
144 pub reason: Option<&'static str>,
145 /// On close: the number of the pull request whose merge closed it.
146 #[serde(skip_serializing_if = "Option::is_none")]
147 pub resolved_by: Option<u32>,
148 /// On `issue.assigned`: the people it is now assigned to.
149 #[serde(skip_serializing_if = "Option::is_none")]
150 pub assignees: Option<Vec<String>>,
151 /// On `issue.assigned`: those of them who were not before.
152 #[serde(skip_serializing_if = "Option::is_none")]
153 pub added: Option<Vec<String>>,
154 /// On `issue.labeled` and `issue.unlabeled`: the label put on or taken
155 /// off. One event for each.
156 #[serde(skip_serializing_if = "Option::is_none")]
157 pub label: Option<EventLabel>,
158 /// On `issue.milestoned`: the milestone it was put in; on
159 /// `issue.demilestoned`, the one it was taken out of.
160 #[serde(skip_serializing_if = "Option::is_none")]
161 pub milestone: Option<crate::work::MilestoneRef>,
162}
163
164/// A label, as `issue.labeled`, `pull.labeled` and their `unlabeled` say.
165#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize)]
166pub struct EventLabel {
167 pub name: String,
168 /// Six hex digits.
169 pub color: String,
170}
171
172/// The payload of `pull.opened`, `pull.ready`, `pull.updated` (its head
173/// moved), `pull.closed`, `pull.reopened`, `pull.converted_to_draft`,
174/// `pull.merged`, `pull.assigned`,
175/// `pull.review_requested` and `pull.review_request_removed` (reviewers
176/// asked, or no longer), `pull.labeled` and `pull.unlabeled`,
177/// `pull.milestoned` and `pull.demilestoned`, `pull.base_changed` (the
178/// branch it merges into changed), `pull.stalled` (g1t stopped seeing it
179/// through until a person steps in) and `pull.resumed` (it picked back
180/// up); each uses the fields that apply to it.
181#[derive(Debug, Default, Serialize)]
182#[serde(rename_all = "camelCase")]
183pub struct PullEvent {
184 pub pull_id: String,
185 pub repo_id: String,
186 pub number: u32,
187 /// Who opened it: g1t, for a change g1t made.
188 #[serde(skip_serializing_if = "Option::is_none")]
189 pub author: Option<crate::credentials::Principal>,
190 /// For a change g1t made: the person who asked for it.
191 #[serde(skip_serializing_if = "Option::is_none")]
192 pub requested_by: Option<crate::credentials::Principal>,
193 /// The number of the issue it is for.
194 #[serde(skip_serializing_if = "Option::is_none")]
195 pub issue: Option<u32>,
196 #[serde(skip_serializing_if = "Option::is_none")]
197 pub agent: Option<String>,
198 /// On merge: the commit the branch now points to. On update, when
199 /// marked ready and when reopened: the head of the change.
200 #[serde(skip_serializing_if = "Option::is_none")]
201 pub commit: Option<String>,
202 /// On close: the pull request that was merged instead.
203 #[serde(skip_serializing_if = "Option::is_none")]
204 pub superseded_by: Option<u32>,
205 /// How sure g1t is of a g1t agent's change, once it has worked that out.
206 #[serde(skip_serializing_if = "Option::is_none")]
207 pub confidence: Option<crate::work::Confidence>,
208 /// On `pull.assigned`: the people it is now assigned to.
209 #[serde(skip_serializing_if = "Option::is_none")]
210 pub assignees: Option<Vec<String>>,
211 /// On `pull.assigned`: those newly assigned.
212 #[serde(skip_serializing_if = "Option::is_none")]
213 pub added: Option<Vec<String>>,
214 /// On `pull.review_requested`: the reviewers newly asked; on
215 /// `pull.review_request_removed`, those no longer asked.
216 #[serde(skip_serializing_if = "Option::is_none")]
217 pub reviewers: Option<Vec<String>>,
218 /// On `pull.review_requested` and `pull.review_request_removed`: the
219 /// teams newly asked, or no longer, each with the people it asks.
220 #[serde(skip_serializing_if = "Option::is_none")]
221 pub teams: Option<Vec<TeamRequested>>,
222 /// On `pull.review_requested`: asked because they own files it changes
223 /// (its CODEOWNERS file), not by a person.
224 #[serde(skip_serializing_if = "std::ops::Not::not")]
225 pub code_owners: bool,
226 /// On `pull.stalled`: why g1t stopped, and what would start it again.
227 #[serde(skip_serializing_if = "Option::is_none")]
228 pub detail: Option<String>,
229 /// On `pull.labeled` and `pull.unlabeled`: the label put on or taken off.
230 #[serde(skip_serializing_if = "Option::is_none")]
231 pub label: Option<EventLabel>,
232 /// On `pull.milestoned`: the milestone it was put in; on
233 /// `pull.demilestoned`, the one it was taken out of.
234 #[serde(skip_serializing_if = "Option::is_none")]
235 pub milestone: Option<crate::work::MilestoneRef>,
236 /// On `pull.opened` and `pull.base_changed`: the branch it merges into.
237 #[serde(skip_serializing_if = "Option::is_none")]
238 pub base: Option<String>,
239}
240
241/// A team asked to review a pull request.
242#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, serde::Deserialize)]
243#[serde(rename_all = "camelCase")]
244pub struct TeamRequested {
245 /// `workspace/slug`.
246 pub team: String,
247 /// Everyone in it who is told: the whole team, or, with review
248 /// assignment, the people picked (and the rest when it says to tell
249 /// them). Never the pull request's author.
250 pub notified: Vec<String>,
251 /// With review assignment: the people picked, who are asked as
252 /// reviewers themselves.
253 #[serde(default)]
254 pub assigned: Vec<String>,
255}
256
257/// The payload of every `team.*` event: `team.created`, `team.edited`,
258/// `team.deleted`; `team.member_added`, `team.member_role_changed`,
259/// `team.member_removed` (with `username`, `role` and `previousRole`);
260/// and `team.repo_added`, `team.repo_role_changed`, `team.repo_removed`
261/// (with `repoId`, `repo`, `repoRole` and `previousRepoRole`), which also
262/// name the repository as the event's own.
263#[derive(Clone, Debug, Default, Serialize)]
264#[serde(rename_all = "camelCase")]
265pub struct TeamChanged {
266 pub workspace: String,
267 pub team_id: String,
268 /// The team's slug, as it is now.
269 pub team: String,
270 pub name: String,
271 pub visibility: Option<crate::teams::TeamVisibility>,
272 /// The parent's slug.
273 #[serde(skip_serializing_if = "Option::is_none")]
274 pub parent: Option<String>,
275 /// On `team.edited`: what changed, such as `name` or `parent`.
276 #[serde(skip_serializing_if = "Vec::is_empty")]
277 pub changes: Vec<String>,
278 #[serde(skip_serializing_if = "Option::is_none")]
279 pub username: Option<String>,
280 #[serde(skip_serializing_if = "Option::is_none")]
281 pub role: Option<crate::teams::TeamRole>,
282 #[serde(skip_serializing_if = "Option::is_none")]
283 pub previous_role: Option<crate::teams::TeamRole>,
284 #[serde(skip_serializing_if = "Option::is_none")]
285 pub repo_id: Option<String>,
286 /// `workspace/name`.
287 #[serde(skip_serializing_if = "Option::is_none")]
288 pub repo: Option<String>,
289 #[serde(skip_serializing_if = "Option::is_none")]
290 pub repo_role: Option<crate::access::RepoRole>,
291 #[serde(skip_serializing_if = "Option::is_none")]
292 pub previous_repo_role: Option<crate::access::RepoRole>,
293}
294
295/// `deployment.succeeded` and `deployment.failed`: a build of a project
296/// finished, for production or for one pull request's preview.
297#[derive(Debug, Serialize)]
298#[serde(rename_all = "camelCase")]
299pub struct DeploymentEvent {
300 pub deployment_id: String,
301 pub project_id: String,
302 pub repo_id: String,
303 pub workspace: String,
304 /// The project's slug.
305 pub project: String,
306 /// `production` or `preview`.
307 pub kind: String,
308 pub branch: Option<String>,
309 /// For a preview: its pull request.
310 pub number: Option<u32>,
311 pub commit: String,
312 /// Where the deployment is on the site, such as
313 /// `/acme/rocket/deployments/dpl_1`.
314 pub path: String,
315 /// For a failure: what went wrong.
316 pub error: Option<String>,
317 /// For a success: whether the deployment before it, of the same app, failed.
318 pub recovered: bool,
319 /// Who started it, by username, or `g1t`.
320 pub triggered_by: String,
321}
322
323/// `checks.completed`: a run of an issue's acceptance checks against a pull
324/// request finished.
325#[derive(Debug, Serialize)]
326#[serde(rename_all = "camelCase")]
327pub struct ChecksEvent {
328 pub pull_id: String,
329 pub repo_id: String,
330 pub number: u32,
331 /// `passed`, `failed` or `errored`.
332 pub status: &'static str,
333 /// The commit that was checked.
334 pub commit: String,
335}
336
337/// `workflow.completed`: a GitHub Actions run finished.
338#[derive(Debug, Serialize)]
339#[serde(rename_all = "camelCase")]
340pub struct WorkflowEvent {
341 pub run_id: String,
342 pub repo_id: String,
343 /// The workflow's name, and its file.
344 pub workflow: String,
345 pub path: String,
346 /// The run's number among the workflow's runs.
347 pub number: u64,
348 /// The GitHub event that started it, such as `push`.
349 pub event: String,
350 /// `success`, `failure`, `cancelled` or `skipped`.
351 pub conclusion: String,
352 #[serde(rename = "ref")]
353 pub git_ref: String,
354 pub sha: String,
355 /// The pull request it ran for, if any.
356 #[serde(skip_serializing_if = "Option::is_none")]
357 pub pull: Option<u32>,
358}
359
360/// `review.completed`: a g1t agent finished reviewing a pull request, or
361/// could not.
362#[derive(Debug, Serialize)]
363#[serde(rename_all = "camelCase")]
364pub struct ReviewEvent {
365 pub pull_id: String,
366 pub repo_id: String,
367 pub number: u32,
368 /// `approve` or `request_changes`; absent when no review was written.
369 #[serde(skip_serializing_if = "Option::is_none")]
370 pub verdict: Option<&'static str>,
371}
372
373/// `comment.created`. `number` is the issue or pull request commented on.
374#[derive(Debug, Serialize)]
375#[serde(rename_all = "camelCase")]
376pub struct CommentCreated {
377 pub comment_id: String,
378 pub repo_id: String,
379 pub number: u32,
380 /// Set when the comment is on a pull request.
381 #[serde(skip_serializing_if = "Option::is_none")]
382 pub pull_id: Option<String>,
383 /// Set when the comment is a review: approve or request changes.
384 #[serde(skip_serializing_if = "Option::is_none")]
385 pub verdict: Option<crate::work::Verdict>,
386}
387
388/// `comment.edited`: a comment's text changed. `changes.body.from` is what
389/// it said before; the comment as it is now is read by `commentId`.
390#[derive(Debug, Serialize)]
391#[serde(rename_all = "camelCase")]
392pub struct CommentEdited {
393 pub comment_id: String,
394 pub repo_id: String,
395 pub number: u32,
396 /// Set when the comment is on a pull request.
397 #[serde(skip_serializing_if = "Option::is_none")]
398 pub pull_id: Option<String>,
399 pub changes: CommentChanges,
400}
401
402/// What an edit changed, as `comment.edited` says it.
403#[derive(Debug, Serialize)]
404pub struct CommentChanges {
405 pub body: ChangedFrom,
406}
407
408/// A field's value before a change.
409#[derive(Debug, Serialize)]
410pub struct ChangedFrom {
411 pub from: String,
412}
413
414/// `comment.deleted`: a comment was deleted. It no longer exists when the
415/// event is read, so `comment` is the comment as it was.
416#[derive(Debug, Serialize)]
417#[serde(rename_all = "camelCase")]
418pub struct CommentDeleted {
419 pub comment_id: String,
420 pub repo_id: String,
421 pub number: u32,
422 /// Set when the comment was on a pull request.
423 #[serde(skip_serializing_if = "Option::is_none")]
424 pub pull_id: Option<String>,
425 pub comment: DeletedComment,
426}
427
428/// A deleted comment, as it was.
429#[derive(Debug, Serialize)]
430#[serde(rename_all = "camelCase")]
431pub struct DeletedComment {
432 pub id: String,
433 pub body: String,
434 pub author: crate::credentials::Principal,
435 /// RFC 3339.
436 pub created_at: String,
437 /// For a comment on one line of a pull request's change: the file.
438 pub path: Option<String>,
439 /// And the line, as numbered after the change.
440 pub line: Option<u32>,
441}
442
443/// The payload of every `release.*` event: `release.created`,
444/// `release.published`, `release.released`, `release.prereleased`,
445/// `release.edited`, `release.unpublished` and `release.deleted`. One change
446/// to a release can be several of them (see [`release_actions`]).
447#[derive(Debug, Serialize)]
448#[serde(rename_all = "camelCase")]
449pub struct ReleaseEvent {
450 pub release_id: String,
451 pub repo_id: String,
452 pub tag_name: String,
453 /// As it is now; as it was, for `release.deleted`.
454 pub release: crate::about::Release,
455 /// On `release.edited`: `{ "name": { "from" }, "body": { "from" } }`
456 /// for what changed.
457 #[serde(skip_serializing_if = "Option::is_none")]
458 pub changes: Option<serde_json::Value>,
459}
460
461/// A release's state, for [`release_actions`]: whether it is a draft, and
462/// whether it is a prerelease.
463#[derive(Clone, Copy, Debug, PartialEq, Eq)]
464pub struct ReleaseState {
465 pub draft: bool,
466 pub prerelease: bool,
467}
468
469/// What a change to a release is, as GitHub's release activity types, in
470/// the order they are sent: from `before` (None: it did not exist) to
471/// `after` (None: deleted). A release made published is `created`,
472/// `published` and `released` (or `prereleased`); a draft published is
473/// `published` and `released` (or `prereleased`); made a draft again,
474/// `unpublished`; anything else `edited`, and a prerelease made a full
475/// release is `released` too.
476pub fn release_actions(before: Option<ReleaseState>, after: Option<ReleaseState>) -> Vec<&'static str> {
477 let published = |state: ReleaseState| if state.prerelease { "prereleased" } else { "released" };
478 match (before, after) {
479 (None, None) => Vec::new(),
480 (None, Some(after)) if after.draft => vec!["created"],
481 (None, Some(after)) => vec!["created", "published", published(after)],
482 (Some(_), None) => vec!["deleted"],
483 (Some(before), Some(after)) if before.draft && !after.draft => vec!["published", published(after)],
484 (Some(before), Some(after)) if !before.draft && after.draft => vec!["unpublished"],
485 (Some(before), Some(after)) if !after.draft && before.prerelease && !after.prerelease => vec!["edited", "released"],
486 (Some(_), Some(_)) => vec!["edited"],
487 }
488}
489
490/// The event kind for a release activity type from [`release_actions`].
491pub fn release_kind(action: &str) -> Option<&'static str> {
492 Some(match action {
493 "created" => "release.created",
494 "published" => "release.published",
495 "released" => "release.released",
496 "prereleased" => "release.prereleased",
497 "edited" => "release.edited",
498 "unpublished" => "release.unpublished",
499 "deleted" => "release.deleted",
500 _ => return None,
501 })
502}
503
504#[derive(Debug, Serialize)]
505#[serde(rename_all = "camelCase")]
506pub struct SessionAppended {
507 pub pull_id: String,
508 pub repo_id: String,
509 pub number: u32,
510 pub count: u32,
511}
512
513/// An event as stored in the log and delivered to subscribers. `data` is
514/// left as JSON; each reader decodes the types it cares about.
515#[derive(Clone, Debug, Serialize, serde::Deserialize)]
516#[serde(rename_all = "camelCase")]
517pub struct Event {
518 /// Sorts by the time the event was published.
519 pub id: String,
520 #[serde(rename = "type")]
521 pub kind: String,
522 /// The service that published it.
523 pub source: String,
524 /// RFC 3339.
525 pub time: String,
526 /// The repo the event concerns.
527 pub repo_id: Option<String>,
528 /// The user or agent that caused it, if any.
529 pub actor: Option<String>,
530 pub data: serde_json::Value,
531}
532
533/// `publish`, as a publisher sends it. Returns nothing.
534#[derive(Debug, Serialize)]
535pub struct Publish<T: Serialize> {
536 pub events: Vec<NewEvent<T>>,
537}
538
539/// `publish`, as the events service reads it.
540#[derive(Debug, serde::Deserialize)]
541pub struct PublishArgs {
542 pub events: Vec<Published>,
543}
544
545/// A [`NewEvent`] of any type, as received.
546#[derive(Debug, serde::Deserialize)]
547#[serde(rename_all = "camelCase")]
548pub struct Published {
549 #[serde(rename = "type")]
550 pub kind: String,
551 pub source: String,
552 #[serde(default)]
553 pub repo_id: Option<String>,
554 #[serde(default)]
555 pub actor: Option<String>,
556 pub data: serde_json::Value,
557}
558
559/// `list`: events from the log, newest first. Returns `Vec<Event>`.
560#[derive(Debug, Default, Serialize, serde::Deserialize)]
561#[serde(rename_all = "camelCase")]
562pub struct ListArgs {
563 #[serde(default)]
564 pub repo_id: Option<String>,
565 /// Only these types; all types when empty.
566 #[serde(default)]
567 pub types: Vec<String>,
568 /// Only events older than this event id.
569 #[serde(default)]
570 pub before: Option<String>,
571 #[serde(default)]
572 pub limit: Option<u32>,
573}
574
575/// `workspace.renamed`: a workspace's slug changed from `from` to `to`.
576/// Every service that stores a slug moves its rows to the workspace's
577/// *current* slug (ask identity by `workspace_id`), so that a repeated or
578/// late delivery after a second rename still lands in the right place.
579#[derive(Clone, Debug, Serialize, serde::Deserialize)]
580#[serde(rename_all = "camelCase")]
581pub struct WorkspaceRenamed {
582 pub workspace_id: String,
583 pub from: String,
584 pub to: String,
585}
586
587impl WorkspaceRenamed {
588 /// The slugs whose rows move to `current`: the two this rename names,
589 /// minus `current` itself. Moving rows keyed by either converges on the
590 /// current slug whatever order renames are delivered in.
591 pub fn stale_slugs(&self, current: &str) -> Vec<String> {
592 let mut slugs: Vec<String> = Vec::new();
593 for slug in [&self.from, &self.to] {
594 if slug != current && !slugs.contains(slug) {
595 slugs.push(slug.clone());
596 }
597 }
598 slugs
599 }
600}
601
602/// `repo.updated`: a repository's description, topics or visibility
603/// changed. `visibility_changed` says whether it went public or private,
604/// which `repo.visibility_changed` also announces on its own.
605#[derive(Debug, Serialize, serde::Deserialize)]
606#[serde(rename_all = "camelCase")]
607pub struct RepoUpdated {
608 pub repo_id: String,
609 pub namespace: String,
610 pub name: String,
611 pub is_private: bool,
612 #[serde(default)]
613 pub visibility_changed: bool,
614}
615
616/// `repo.visibility_changed`: a repository went public or private.
617#[derive(Debug, Serialize, serde::Deserialize)]
618#[serde(rename_all = "camelCase")]
619pub struct RepoVisibilityChanged {
620 pub repo_id: String,
621 pub is_private: bool,
622}
623
624/// `repo.renamed`: a repository's name changed within its workspace,
625/// keeping its id and its git store key. Like `repo.transferred`, a path
626/// change: every service that keeps rows under the repository's path moves
627/// them to its *current* path (ask repos `path_by_id`), so a repeated or
628/// late delivery after a second rename or a transfer still lands in the
629/// right place. `g1t_kit::transfer::on_event` handles both.
630#[derive(Clone, Debug, Serialize, serde::Deserialize)]
631#[serde(rename_all = "camelCase")]
632pub struct RepoRenamed {
633 pub repo_id: String,
634 /// The workspace it is in.
635 pub namespace: String,
636 /// Its old name.
637 pub from: String,
638 /// Its new name.
639 pub to: String,
640}
641
642impl RepoRenamed {
643 /// The paths whose rows move to `current` (`namespace/name`): the two
644 /// this rename names, minus `current`.
645 pub fn stale_paths(&self, current: &str) -> Vec<String> {
646 let mut paths: Vec<String> = Vec::new();
647 for name in [&self.from, &self.to] {
648 let path = format!("{}/{name}", self.namespace);
649 if path != current && !paths.contains(&path) {
650 paths.push(path);
651 }
652 }
653 paths
654 }
655}
656
657/// `repo.deleted`: a repository was deleted. It is hidden everywhere and
658/// git refuses it, but it can be restored until `purge_after`, so services
659/// stop what runs for it (agents, workflows, deployments, indexing,
660/// webhook deliveries) and hide it, and keep what they hold until
661/// `repo.purged`. `repo.restored` brings it back.
662#[derive(Clone, Debug, Serialize, serde::Deserialize)]
663#[serde(rename_all = "camelCase")]
664pub struct RepoDeleted {
665 pub repo_id: String,
666 #[serde(default)]
667 pub namespace: String,
668 #[serde(default)]
669 pub name: String,
670 #[serde(default)]
671 pub is_private: bool,
672 /// RFC 3339: when it is purged unless restored first.
673 #[serde(default)]
674 pub purge_after: String,
675 /// It went with its workspace (`workspace.deleting`). Services that
676 /// handle the workspace as a whole (deployments pauses its apps rather
677 /// than taking them down) leave this one to that.
678 #[serde(default)]
679 pub with_workspace: bool,
680}
681
682/// `repo.restored`: a deleted repository is back, at its path, as it was.
683/// Services start again what `repo.deleted` stopped: index it, deploy its
684/// production, show it.
685#[derive(Clone, Debug, Serialize, serde::Deserialize)]
686#[serde(rename_all = "camelCase")]
687pub struct RepoRestored {
688 pub repo_id: String,
689 pub namespace: String,
690 pub name: String,
691 pub is_private: bool,
692 /// It came back with its workspace (`workspace.restored`).
693 #[serde(default)]
694 pub with_workspace: bool,
695}
696
697/// `repo.purged`: a deleted repository is gone for good, its git data
698/// with it. Services drop every row they keep for it by `repo_id`, except
699/// history that belongs to its workspace: ledgers, invoices and the audit
700/// log. Its path is free for a new repository.
701#[derive(Clone, Debug, Serialize, serde::Deserialize)]
702#[serde(rename_all = "camelCase")]
703pub struct RepoPurged {
704 pub repo_id: String,
705 pub namespace: String,
706 pub name: String,
707}
708
709/// `repo.archived` and `repo.unarchived`: a repository became read-only,
710/// or writable again. While archived, pushes are refused, issues and pull
711/// requests are locked, and agents and workflows do not run for it; its
712/// deployments keep serving.
713#[derive(Clone, Debug, Serialize, serde::Deserialize)]
714#[serde(rename_all = "camelCase")]
715pub struct RepoArchived {
716 pub repo_id: String,
717 pub namespace: String,
718 pub name: String,
719 pub archived: bool,
720}
721
722/// `repo.default_branch_changed`: the branch everything lands on is now
723/// `to`. `renamed` says whether `from` was renamed to `to` (open pull
724/// requests into it now target `to`) rather than another branch chosen.
725#[derive(Clone, Debug, Serialize, serde::Deserialize)]
726#[serde(rename_all = "camelCase")]
727pub struct RepoDefaultBranchChanged {
728 pub repo_id: String,
729 pub from: String,
730 pub to: String,
731 #[serde(default)]
732 pub renamed: bool,
733}
734
735/// `branch.renamed`: a branch was renamed. Pull requests from or into
736/// `from` follow it to `to`, and web addresses that name `from` redirect.
737#[derive(Clone, Debug, Serialize, serde::Deserialize)]
738#[serde(rename_all = "camelCase")]
739pub struct BranchRenamed {
740 pub repo_id: String,
741 pub from: String,
742 pub to: String,
743 /// Whether it is the default branch.
744 #[serde(default)]
745 pub default_branch: bool,
746}
747
748/// `repo.transferred`: a repository moved from one workspace to another,
749/// keeping its id and its name. Every service that keeps a repository
750/// under its path (`namespace/name`) or its workspace's slug moves those
751/// rows to the repository's *current* path (ask repos `path_by_id`), so a
752/// repeated or late delivery after a second transfer still lands in the
753/// right place. What was charged or recorded before the transfer stays
754/// with the workspace it happened in.
755#[derive(Clone, Debug, Serialize, serde::Deserialize)]
756#[serde(rename_all = "camelCase")]
757pub struct RepoTransferred {
758 pub repo_id: String,
759 pub name: String,
760 /// The workspace it left.
761 pub from: String,
762 /// The workspace it went to.
763 pub to: String,
764}
765
766impl RepoTransferred {
767 /// The paths whose rows move to `current` (`namespace/name`): the two
768 /// this transfer names, minus `current`. Moving rows keyed by either
769 /// converges whatever order transfers are delivered in.
770 pub fn stale_paths(&self, current: &str) -> Vec<String> {
771 let mut paths: Vec<String> = Vec::new();
772 for namespace in [&self.from, &self.to] {
773 let path = format!("{namespace}/{}", self.name);
774 if path != current && !paths.contains(&path) {
775 paths.push(path);
776 }
777 }
778 paths
779 }
780}
781
782/// `workspace.deleted`: a workspace is gone. Services drop what they keep
783/// for it alone (its webhooks, integrations, secrets, memory, guardrails,
784/// agent queue) and keep what is history: ledgers, invoices and the audit
785/// log stay under its slug, which is never given to another workspace.
786#[derive(Clone, Debug, Serialize, serde::Deserialize)]
787#[serde(rename_all = "camelCase")]
788pub struct WorkspaceDeleted {
789 pub workspace_id: String,
790 pub slug: String,
791}
792
793/// `workspace.deleting`: an owner deleted a workspace, and it can be
794/// restored by g1t's staff until `purge_after`. Nobody can reach it in the
795/// meantime. Services hide what they keep for it and stop what runs for it,
796/// keeping their rows: repos deletes its repositories softly (each with a
797/// `repo.deleted` whose `with_workspace` is set), deployments pauses its
798/// apps, search drops it from results. `workspace.restored` undoes exactly
799/// that; once `purge_after` passes, `workspace.deleted` follows and
800/// services purge as for any deleted workspace.
801#[derive(Clone, Debug, Serialize, serde::Deserialize)]
802#[serde(rename_all = "camelCase")]
803pub struct WorkspaceDeleting {
804 pub workspace_id: String,
805 pub slug: String,
806 /// The username of the owner who deleted it.
807 pub by: String,
808 /// RFC 3339: when it is purged unless restored first.
809 pub purge_after: String,
810}
811
812/// `workspace.restored`: staff brought a deleted workspace back, with its
813/// members and tokens. Services undo what they did on `workspace.deleting`,
814/// and only that: a repository deleted on its own before stays deleted.
815#[derive(Clone, Debug, Serialize, serde::Deserialize)]
816#[serde(rename_all = "camelCase")]
817pub struct WorkspaceRestored {
818 pub workspace_id: String,
819 pub slug: String,
820}
821
822/// `user.deleting`: an account was deleted, by the person or by g1t's
823/// staff, and can be restored by staff until `purge_after`. Its sessions,
824/// tokens and keys have ended and it has left every workspace; services
825/// stop what they do for it (search drops its profile, nothing more is
826/// sent to it) and keep their rows. `user.restored` undoes that; once
827/// `purge_after` passes, `user.deleted` follows.
828#[derive(Clone, Debug, Serialize, serde::Deserialize)]
829#[serde(rename_all = "camelCase")]
830pub struct UserDeleting {
831 pub user_id: String,
832 pub username: String,
833 /// Whether g1t's staff deleted it rather than the person.
834 #[serde(default)]
835 pub by_staff: bool,
836 /// RFC 3339: when it is purged unless restored first.
837 pub purge_after: String,
838}
839
840/// `user.restored`: staff brought a deleted account back. It signs in
841/// again with its password; its old sessions and tokens stay ended.
842/// Services undo what they did on `user.deleting`.
843#[derive(Clone, Debug, Serialize, serde::Deserialize)]
844#[serde(rename_all = "camelCase")]
845pub struct UserRestored {
846 pub user_id: String,
847 pub username: String,
848}
849
850/// `user.deleted`: an account is gone for good. Services drop what they
851/// keep for it alone (its inbox, subscriptions, settings) and show what it
852/// wrote as `ghost` (`account_deletion::GHOST_USERNAME`, id
853/// `account_deletion::GHOST_ID`). Ledgers, invoices and audit logs keep
854/// its username. The username is never given to anyone again.
855#[derive(Clone, Debug, Serialize, serde::Deserialize)]
856#[serde(rename_all = "camelCase")]
857pub struct UserDeleted {
858 pub user_id: String,
859 pub username: String,
860}
861
862/// `user.updated`: an account was made, or changed what its profile shows
863/// (name, bio, avatar). Nothing private: ask identity for the profile.
864#[derive(Debug, Serialize, serde::Deserialize)]
865#[serde(rename_all = "camelCase")]
866pub struct UserUpdated {
867 pub username: String,
868}
869
870/// `user.email_added`, `user.email_verified`, `user.email_removed` and
871/// `user.primary_email_changed`: an account's addresses changed. Never the
872/// address itself; ask identity, as the person, for that.
873#[derive(Debug, Serialize, serde::Deserialize)]
874#[serde(rename_all = "camelCase")]
875pub struct UserEmailChanged {
876 pub user_id: String,
877 /// Whether g1t staff made the change.
878 #[serde(default)]
879 pub by_staff: bool,
880}
881
882/// `workspace.updated`: a workspace was made, or its name, description or
883/// icon changed. Ask identity for it by slug.
884#[derive(Debug, Serialize, serde::Deserialize)]
885#[serde(rename_all = "camelCase")]
886pub struct WorkspaceUpdated {
887 pub workspace_id: String,
888 pub slug: String,
889}
890
891/// `invite.created`: someone (or staff) made an invite. Never the code or
892/// the address it is for.
893#[derive(Debug, Serialize, serde::Deserialize)]
894#[serde(rename_all = "camelCase")]
895pub struct InviteCreated {
896 pub invite_id: String,
897 /// The account that made it; null when staff did.
898 pub inviter_id: Option<String>,
899 /// The workspace it joins.
900 pub workspace_id: Option<String>,
901 /// Whether it is bound to one email address.
902 pub bound: bool,
903}
904
905/// `invite.redeemed`: an invite was used, by a new account or by an
906/// existing one joining a workspace.
907#[derive(Debug, Serialize, serde::Deserialize)]
908#[serde(rename_all = "camelCase")]
909pub struct InviteRedeemed {
910 /// The invite's id, or a shared invite link's (`sinv_…`) when one made
911 /// the account.
912 pub invite_id: String,
913 pub user_id: String,
914 pub inviter_id: Option<String>,
915 pub workspace_id: Option<String>,
916 /// Whether it made the account.
917 pub created_account: bool,
918}
919
920/// `waitlist.requested`: someone asked for access. Ask identity's staff
921/// methods for the entry; the address is not in the event.
922#[derive(Debug, Serialize, serde::Deserialize)]
923#[serde(rename_all = "camelCase")]
924pub struct WaitlistRequested {
925 pub entry_id: String,
926}
927
928/// The payload of `package.published`, `package.version_deleted`,
929/// `package.deleted` and `package.visibility_changed`; each uses the fields
930/// that apply to it. `repo_id` is the repository the package is linked to.
931#[derive(Clone, Debug, Default, Serialize)]
932#[serde(rename_all = "camelCase")]
933pub struct PackageEvent {
934 pub package_id: String,
935 pub workspace: String,
936 pub ecosystem: String,
937 pub name: String,
938 pub repo_id: Option<String>,
939 /// The version published or deleted: for a container image, its
940 /// manifest's digest.
941 #[serde(skip_serializing_if = "Option::is_none")]
942 pub version: Option<String>,
943 #[serde(skip_serializing_if = "Option::is_none")]
944 pub digest: Option<String>,
945 #[serde(skip_serializing_if = "Option::is_none")]
946 pub size: Option<u64>,
947 /// On publish: the tags that now point to the version.
948 #[serde(skip_serializing_if = "Option::is_none")]
949 pub tags: Option<Vec<String>>,
950 /// On `package.visibility_changed`: `public` or `private`.
951 #[serde(skip_serializing_if = "Option::is_none")]
952 pub visibility: Option<String>,
953}
954
955/// `queue.changed`: a repository's merge queue gained, lost or settled an
956/// entry, so the next batch may be ready to test.
957#[derive(Debug, Serialize)]
958#[serde(rename_all = "camelCase")]
959pub struct QueueChanged {
960 pub repo_id: String,
961}
962
963#[cfg(test)]
964mod tests {
965 use super::*;
966
967 #[test]
968 fn comment_edits_and_deletes_say_what_it_was() {
969 let edited = CommentEdited {
970 comment_id: "cmt_1".into(),
971 repo_id: "rep_1".into(),
972 number: 7,
973 pull_id: Some("pr_1".into()),
974 changes: CommentChanges { body: ChangedFrom { from: "Before".into() } },
975 };
976 assert_eq!(
977 serde_json::to_value(edited).unwrap(),
978 serde_json::json!({
979 "commentId": "cmt_1", "repoId": "rep_1", "number": 7, "pullId": "pr_1",
980 "changes": { "body": { "from": "Before" } },
981 })
982 );
983 let deleted = CommentDeleted {
984 comment_id: "cmt_1".into(),
985 repo_id: "rep_1".into(),
986 number: 7,
987 pull_id: None,
988 comment: DeletedComment {
989 id: "cmt_1".into(),
990 body: "Gone".into(),
991 author: crate::credentials::Principal { id: "usr_1".into(), username: "ana".into() },
992 created_at: "2026-10-08T00:00:00Z".into(),
993 path: None,
994 line: None,
995 },
996 };
997 assert_eq!(
998 serde_json::to_value(deleted).unwrap(),
999 serde_json::json!({
1000 "commentId": "cmt_1", "repoId": "rep_1", "number": 7,
1001 "comment": {
1002 "id": "cmt_1", "body": "Gone", "author": { "id": "usr_1", "username": "ana" },
1003 "createdAt": "2026-10-08T00:00:00Z", "path": null, "line": null,
1004 },
1005 })
1006 );
1007 }
1008
1009 #[test]
1010 fn a_release_change_is_githubs_activity_types() {
1011 let state = |draft, prerelease| Some(ReleaseState { draft, prerelease });
1012 assert_eq!(release_actions(None, state(true, false)), ["created"]);
1013 assert_eq!(release_actions(None, state(false, false)), ["created", "published", "released"]);
1014 assert_eq!(release_actions(None, state(false, true)), ["created", "published", "prereleased"]);
1015 assert_eq!(release_actions(state(true, true), state(false, true)), ["published", "prereleased"]);
1016 assert_eq!(release_actions(state(false, false), state(true, false)), ["unpublished"]);
1017 assert_eq!(release_actions(state(false, true), state(false, false)), ["edited", "released"]);
1018 assert_eq!(release_actions(state(false, false), state(false, true)), ["edited"]);
1019 assert_eq!(release_actions(state(true, false), state(true, false)), ["edited"]);
1020 assert_eq!(release_actions(state(false, false), None), ["deleted"]);
1021 for action in ["created", "published", "released", "prereleased", "edited", "unpublished", "deleted"] {
1022 assert_eq!(release_kind(action).map(|kind| kind.trim_start_matches("release.")), Some(action));
1023 }
1024 assert_eq!(release_kind("archived"), None);
1025 }
1026
1027 #[test]
1028 fn what_a_job_token_did_is_marked_and_carried_on() {
1029 let mut actor = crate::User { id: "wsp_1".into(), username: "acme".into(), ..crate::User::default() };
1030 let plain = marked(serde_json::json!({ "number": 4 }), Some(&actor));
1031 assert_eq!(caused_by_job(&plain), None);
1032 actor.token = Some(Box::new(crate::scopes::TokenAccess {
1033 job: Some(crate::scopes::JobToken { run_id: "run_9".into(), job_id: "job_1".into(), pull_requests: false }),
1034 ..Default::default()
1035 }));
1036 let by_job = marked(serde_json::json!({ "number": 4 }), Some(&actor));
1037 assert_eq!(caused_by_job(&by_job), Some("run_9"));
1038 assert_eq!(by_job["number"], 4);
1039 // A push by the job's token, and the pull request it moves.
1040 let push = GitPush {
1041 repo_id: "rep_1".into(),
1042 git_ref: "refs/heads/fix".into(),
1043 before: Some("a".into()),
1044 after: "b".into(),
1045 default_branch: false,
1046 unscanned: false,
1047 caused_by_job: job_run_of(&actor).map(str::to_owned),
1048 mirrored: false,
1049 mirror: None,
1050 };
1051 let push = serde_json::to_value(push).unwrap();
1052 assert_eq!(caused_by_job(&push), Some("run_9"));
1053 assert_eq!(caused_by_job(&carried(serde_json::json!({ "number": 4 }), &push)), Some("run_9"));
1054 assert_eq!(caused_by_job(&carried(serde_json::json!({ "number": 4 }), &serde_json::json!({}))), None);
1055 }
1056
1057 #[test]
1058 fn a_push_says_it_was_unscanned_only_when_it_was() {
1059 let push = |unscanned| GitPush {
1060 repo_id: "rep_1".into(),
1061 git_ref: "refs/heads/import".into(),
1062 before: None,
1063 after: "abc".into(),
1064 default_branch: false,
1065 unscanned,
1066 caused_by_job: None,
1067 mirrored: false,
1068 mirror: None,
1069 };
1070 let quiet = serde_json::to_value(push(false)).unwrap();
1071 assert!(quiet.get("unscanned").is_none());
1072 let flagged = serde_json::to_value(push(true)).unwrap();
1073 assert_eq!(flagged["unscanned"], true);
1074 assert_eq!(flagged["ref"], "refs/heads/import");
1075 }
1076
1077 fn renamed(from: &str, to: &str) -> WorkspaceRenamed {
1078 WorkspaceRenamed {
1079 workspace_id: "wsp_1".into(),
1080 from: from.into(),
1081 to: to.into(),
1082 }
1083 }
1084
1085 #[test]
1086 fn stale_slugs_leave_out_the_current_one() {
1087 assert_eq!(renamed("a", "b").stale_slugs("b"), vec!["a"]);
1088 // Delivered after a second rename, b → c: both move to c.
1089 assert_eq!(renamed("a", "b").stale_slugs("c"), vec!["a", "b"]);
1090 // Renamed back: a → b → a.
1091 assert_eq!(renamed("a", "b").stale_slugs("a"), vec!["b"]);
1092 }
1093
1094 fn transferred(from: &str, to: &str) -> RepoTransferred {
1095 RepoTransferred {
1096 repo_id: "rep_1".into(),
1097 name: "rocket".into(),
1098 from: from.into(),
1099 to: to.into(),
1100 }
1101 }
1102
1103 #[test]
1104 fn stale_paths_leave_out_the_current_one() {
1105 assert_eq!(transferred("a", "b").stale_paths("b/rocket"), vec!["a/rocket"]);
1106 // Delivered after a second transfer, b → c: both move to c.
1107 assert_eq!(
1108 transferred("a", "b").stale_paths("c/rocket"),
1109 vec!["a/rocket", "b/rocket"]
1110 );
1111 // Transferred back: a → b → a.
1112 assert_eq!(transferred("a", "b").stale_paths("a/rocket"), vec!["b/rocket"]);
1113 }
1114
1115 #[test]
1116 fn a_transfer_reads_as_published() {
1117 let data = serde_json::json!({ "repoId": "rep_1", "name": "rocket", "from": "a", "to": "b" });
1118 let event: RepoTransferred = serde_json::from_value(data).unwrap();
1119 assert_eq!((event.from.as_str(), event.to.as_str()), ("a", "b"));
1120 }
1121
1122 #[test]
1123 fn a_rename_names_both_paths_in_its_workspace() {
1124 let renamed = RepoRenamed {
1125 repo_id: "rep_1".into(),
1126 namespace: "acme".into(),
1127 from: "old".into(),
1128 to: "new".into(),
1129 };
1130 assert_eq!(renamed.stale_paths("acme/new"), vec!["acme/old"]);
1131 // Delivered after a transfer: both names in acme move.
1132 assert_eq!(renamed.stale_paths("flagon/new"), vec!["acme/old", "acme/new"]);
1133 }
1134
1135 #[test]
1136 fn reads_the_published_payload() {
1137 let data = serde_json::json!({ "workspaceId": "wsp_1", "from": "a", "to": "b" });
1138 let event: WorkspaceRenamed = serde_json::from_value(data).unwrap();
1139 assert_eq!((event.from.as_str(), event.to.as_str()), ("a", "b"));
1140 }
1141}