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