Skip to content
1,138 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 /// Only events by this account id.
563 #[serde(default)]
564 pub actor: Option<String>,
565 /// Only events about these issues or pull requests: their `number`, or
566 /// the `issue` a comment, review or link is on. All when empty.
567 #[serde(default)]
568 pub numbers: Vec<u32>,
569 /// Only events at or after this RFC 3339 time.
570 #[serde(default)]
571 pub since: Option<String>,
572 #[serde(default)]
573 pub limit: Option<u32>,
574}
575
576/// `workspace.renamed`: a workspace's slug changed from `from` to `to`.
577/// Every service that stores a slug moves its rows to the workspace's
578/// *current* slug (ask identity by `workspace_id`), so that a repeated or
579/// late delivery after a second rename still lands in the right place.
580#[derive(Clone, Debug, Serialize, serde::Deserialize)]
581#[serde(rename_all = "camelCase")]
582pub struct WorkspaceRenamed {
583 pub workspace_id: String,
584 pub from: String,
585 pub to: String,
586}
587
588impl WorkspaceRenamed {
589 /// The slugs whose rows move to `current`: the two this rename names,
590 /// minus `current` itself. Moving rows keyed by either converges on the
591 /// current slug whatever order renames are delivered in.
592 pub fn stale_slugs(&self, current: &str) -> Vec<String> {
593 let mut slugs: Vec<String> = Vec::new();
594 for slug in [&self.from, &self.to] {
595 if slug != current && !slugs.contains(slug) {
596 slugs.push(slug.clone());
597 }
598 }
599 slugs
600 }
601}
602
603/// `repo.updated`: a repository's description, topics or visibility
604/// changed. `visibility_changed` says whether it went public or private,
605/// which `repo.visibility_changed` also announces on its own.
606#[derive(Debug, Serialize, serde::Deserialize)]
607#[serde(rename_all = "camelCase")]
608pub struct RepoUpdated {
609 pub repo_id: String,
610 pub namespace: String,
611 pub name: String,
612 pub is_private: bool,
613 #[serde(default)]
614 pub visibility_changed: bool,
615}
616
617/// `repo.visibility_changed`: a repository went public or private.
618#[derive(Debug, Serialize, serde::Deserialize)]
619#[serde(rename_all = "camelCase")]
620pub struct RepoVisibilityChanged {
621 pub repo_id: String,
622 pub is_private: bool,
623}
624
625/// `repo.renamed`: a repository's name changed within its workspace,
626/// keeping its id and its git store key. Like `repo.transferred`, a path
627/// change: every service that keeps rows under the repository's path moves
628/// them to its *current* path (ask repos `path_by_id`), so a repeated or
629/// late delivery after a second rename or a transfer still lands in the
630/// right place. `g1t_kit::transfer::on_event` handles both.
631#[derive(Clone, Debug, Serialize, serde::Deserialize)]
632#[serde(rename_all = "camelCase")]
633pub struct RepoRenamed {
634 pub repo_id: String,
635 /// The workspace it is in.
636 pub namespace: String,
637 /// Its old name.
638 pub from: String,
639 /// Its new name.
640 pub to: String,
641}
642
643impl RepoRenamed {
644 /// The paths whose rows move to `current` (`namespace/name`): the two
645 /// this rename names, minus `current`.
646 pub fn stale_paths(&self, current: &str) -> Vec<String> {
647 let mut paths: Vec<String> = Vec::new();
648 for name in [&self.from, &self.to] {
649 let path = format!("{}/{name}", self.namespace);
650 if path != current && !paths.contains(&path) {
651 paths.push(path);
652 }
653 }
654 paths
655 }
656}
657
658/// `repo.deleted`: a repository was deleted. It is hidden everywhere and
659/// git refuses it, but it can be restored until `purge_after`, so services
660/// stop what runs for it (agents, workflows, deployments, indexing,
661/// webhook deliveries) and hide it, and keep what they hold until
662/// `repo.purged`. `repo.restored` brings it back.
663#[derive(Clone, Debug, Serialize, serde::Deserialize)]
664#[serde(rename_all = "camelCase")]
665pub struct RepoDeleted {
666 pub repo_id: String,
667 #[serde(default)]
668 pub namespace: String,
669 #[serde(default)]
670 pub name: String,
671 #[serde(default)]
672 pub is_private: bool,
673 /// RFC 3339: when it is purged unless restored first.
674 #[serde(default)]
675 pub purge_after: String,
676 /// It went with its workspace (`workspace.deleting`). Services that
677 /// handle the workspace as a whole (deployments pauses its apps rather
678 /// than taking them down) leave this one to that.
679 #[serde(default)]
680 pub with_workspace: bool,
681}
682
683/// `repo.restored`: a deleted repository is back, at its path, as it was.
684/// Services start again what `repo.deleted` stopped: index it, deploy its
685/// production, show it.
686#[derive(Clone, Debug, Serialize, serde::Deserialize)]
687#[serde(rename_all = "camelCase")]
688pub struct RepoRestored {
689 pub repo_id: String,
690 pub namespace: String,
691 pub name: String,
692 pub is_private: bool,
693 /// It came back with its workspace (`workspace.restored`).
694 #[serde(default)]
695 pub with_workspace: bool,
696}
697
698/// `repo.purged`: a deleted repository is gone for good, its git data
699/// with it. Services drop every row they keep for it by `repo_id`, except
700/// history that belongs to its workspace: ledgers, invoices and the audit
701/// log. Its path is free for a new repository.
702#[derive(Clone, Debug, Serialize, serde::Deserialize)]
703#[serde(rename_all = "camelCase")]
704pub struct RepoPurged {
705 pub repo_id: String,
706 pub namespace: String,
707 pub name: String,
708}
709
710/// `repo.archived` and `repo.unarchived`: a repository became read-only,
711/// or writable again. While archived, pushes are refused, issues and pull
712/// requests are locked, and agents and workflows do not run for it; its
713/// deployments keep serving.
714#[derive(Clone, Debug, Serialize, serde::Deserialize)]
715#[serde(rename_all = "camelCase")]
716pub struct RepoArchived {
717 pub repo_id: String,
718 pub namespace: String,
719 pub name: String,
720 pub archived: bool,
721}
722
723/// `repo.default_branch_changed`: the branch everything lands on is now
724/// `to`. `renamed` says whether `from` was renamed to `to` (open pull
725/// requests into it now target `to`) rather than another branch chosen.
726#[derive(Clone, Debug, Serialize, serde::Deserialize)]
727#[serde(rename_all = "camelCase")]
728pub struct RepoDefaultBranchChanged {
729 pub repo_id: String,
730 pub from: String,
731 pub to: String,
732 #[serde(default)]
733 pub renamed: bool,
734}
735
736/// `branch.renamed`: a branch was renamed. Pull requests from or into
737/// `from` follow it to `to`, and web addresses that name `from` redirect.
738#[derive(Clone, Debug, Serialize, serde::Deserialize)]
739#[serde(rename_all = "camelCase")]
740pub struct BranchRenamed {
741 pub repo_id: String,
742 pub from: String,
743 pub to: String,
744 /// Whether it is the default branch.
745 #[serde(default)]
746 pub default_branch: bool,
747}
748
749/// `repo.transferred`: a repository moved from one workspace to another,
750/// keeping its id and its name. Every service that keeps a repository
751/// under its path (`namespace/name`) or its workspace's slug moves those
752/// rows to the repository's *current* path (ask repos `path_by_id`), so a
753/// repeated or late delivery after a second transfer still lands in the
754/// right place. What was charged or recorded before the transfer stays
755/// with the workspace it happened in.
756#[derive(Clone, Debug, Serialize, serde::Deserialize)]
757#[serde(rename_all = "camelCase")]
758pub struct RepoTransferred {
759 pub repo_id: String,
760 pub name: String,
761 /// The workspace it left.
762 pub from: String,
763 /// The workspace it went to.
764 pub to: String,
765}
766
767impl RepoTransferred {
768 /// The paths whose rows move to `current` (`namespace/name`): the two
769 /// this transfer names, minus `current`. Moving rows keyed by either
770 /// converges whatever order transfers are delivered in.
771 pub fn stale_paths(&self, current: &str) -> Vec<String> {
772 let mut paths: Vec<String> = Vec::new();
773 for namespace in [&self.from, &self.to] {
774 let path = format!("{namespace}/{}", self.name);
775 if path != current && !paths.contains(&path) {
776 paths.push(path);
777 }
778 }
779 paths
780 }
781}
782
783/// `workspace.deleted`: a workspace is gone. Services drop what they keep
784/// for it alone (its webhooks, integrations, secrets, memory, guardrails,
785/// agent queue) and keep what is history: ledgers, invoices and the audit
786/// log stay under its slug, which is never given to another workspace.
787#[derive(Clone, Debug, Serialize, serde::Deserialize)]
788#[serde(rename_all = "camelCase")]
789pub struct WorkspaceDeleted {
790 pub workspace_id: String,
791 pub slug: String,
792}
793
794/// `workspace.deleting`: an owner deleted a workspace, and it can be
795/// restored by g1t's staff until `purge_after`. Nobody can reach it in the
796/// meantime. Services hide what they keep for it and stop what runs for it,
797/// keeping their rows: repos deletes its repositories softly (each with a
798/// `repo.deleted` whose `with_workspace` is set), deployments pauses its
799/// apps, search drops it from results. `workspace.restored` undoes exactly
800/// that; once `purge_after` passes, `workspace.deleted` follows and
801/// services purge as for any deleted workspace.
802#[derive(Clone, Debug, Serialize, serde::Deserialize)]
803#[serde(rename_all = "camelCase")]
804pub struct WorkspaceDeleting {
805 pub workspace_id: String,
806 pub slug: String,
807 /// The username of the owner who deleted it.
808 pub by: String,
809 /// RFC 3339: when it is purged unless restored first.
810 pub purge_after: String,
811}
812
813/// `workspace.restored`: staff brought a deleted workspace back, with its
814/// members and tokens. Services undo what they did on `workspace.deleting`,
815/// and only that: a repository deleted on its own before stays deleted.
816#[derive(Clone, Debug, Serialize, serde::Deserialize)]
817#[serde(rename_all = "camelCase")]
818pub struct WorkspaceRestored {
819 pub workspace_id: String,
820 pub slug: String,
821}
822
823/// `user.deleting`: an account was deleted, by the person or by g1t's
824/// staff, and can be restored by staff until `purge_after`. Its sessions,
825/// tokens and keys have ended and it has left every workspace; services
826/// stop what they do for it (search drops its profile, nothing more is
827/// sent to it) and keep their rows. `user.restored` undoes that; once
828/// `purge_after` passes, `user.deleted` follows.
829#[derive(Clone, Debug, Serialize, serde::Deserialize)]
830#[serde(rename_all = "camelCase")]
831pub struct UserDeleting {
832 pub user_id: String,
833 pub username: String,
834 /// Whether g1t's staff deleted it rather than the person.
835 #[serde(default)]
836 pub by_staff: bool,
837 /// RFC 3339: when it is purged unless restored first.
838 pub purge_after: String,
839}
840
841/// `user.restored`: staff brought a deleted account back. It signs in
842/// again with its password; its old sessions and tokens stay ended.
843/// Services undo what they did on `user.deleting`.
844#[derive(Clone, Debug, Serialize, serde::Deserialize)]
845#[serde(rename_all = "camelCase")]
846pub struct UserRestored {
847 pub user_id: String,
848 pub username: String,
849}
850
851/// `user.deleted`: an account is gone for good. Services drop what they
852/// keep for it alone (its inbox, subscriptions, settings) and show what it
853/// wrote as `ghost` (`account_deletion::GHOST_USERNAME`, id
854/// `account_deletion::GHOST_ID`). Ledgers, invoices and audit logs keep
855/// its username. The username is never given to anyone again.
856#[derive(Clone, Debug, Serialize, serde::Deserialize)]
857#[serde(rename_all = "camelCase")]
858pub struct UserDeleted {
859 pub user_id: String,
860 pub username: String,
861}
862
863/// `user.updated`: an account was made, or changed what its profile shows
864/// (name, bio, avatar). Nothing private: ask identity for the profile.
865#[derive(Debug, Serialize, serde::Deserialize)]
866#[serde(rename_all = "camelCase")]
867pub struct UserUpdated {
868 pub username: String,
869}
870
871/// `user.email_added`, `user.email_verified`, `user.email_removed` and
872/// `user.primary_email_changed`: an account's addresses changed. Never the
873/// address itself; ask identity, as the person, for that.
874#[derive(Debug, Serialize, serde::Deserialize)]
875#[serde(rename_all = "camelCase")]
876pub struct UserEmailChanged {
877 pub user_id: String,
878 /// Whether g1t staff made the change.
879 #[serde(default)]
880 pub by_staff: bool,
881}
882
883/// `workspace.updated`: a workspace was made, or its name, description or
884/// icon changed. Ask identity for it by slug.
885#[derive(Debug, Serialize, serde::Deserialize)]
886#[serde(rename_all = "camelCase")]
887pub struct WorkspaceUpdated {
888 pub workspace_id: String,
889 pub slug: String,
890}
891
892/// `invite.created`: someone (or staff) made an invite. Never the code or
893/// the address it is for.
894#[derive(Debug, Serialize, serde::Deserialize)]
895#[serde(rename_all = "camelCase")]
896pub struct InviteCreated {
897 pub invite_id: String,
898 /// The account that made it; null when staff did.
899 pub inviter_id: Option<String>,
900 /// The workspace it joins.
901 pub workspace_id: Option<String>,
902 /// Whether it is bound to one email address.
903 pub bound: bool,
904}
905
906/// `invite.redeemed`: an invite was used, by a new account or by an
907/// existing one joining a workspace.
908#[derive(Debug, Serialize, serde::Deserialize)]
909#[serde(rename_all = "camelCase")]
910pub struct InviteRedeemed {
911 /// The invite's id, or a shared invite link's (`sinv_…`) when one made
912 /// the account.
913 pub invite_id: String,
914 pub user_id: String,
915 pub inviter_id: Option<String>,
916 pub workspace_id: Option<String>,
917 /// Whether it made the account.
918 pub created_account: bool,
919}
920
921/// `waitlist.requested`: someone asked for access. Ask identity's staff
922/// methods for the entry; the address is not in the event.
923#[derive(Debug, Serialize, serde::Deserialize)]
924#[serde(rename_all = "camelCase")]
925pub struct WaitlistRequested {
926 pub entry_id: String,
927}
928
929/// The payload of `package.published`, `package.version_deleted`,
930/// `package.deleted` and `package.visibility_changed`; each uses the fields
931/// that apply to it. `repo_id` is the repository the package is linked to.
932#[derive(Clone, Debug, Default, Serialize)]
933#[serde(rename_all = "camelCase")]
934pub struct PackageEvent {
935 pub package_id: String,
936 pub workspace: String,
937 pub ecosystem: String,
938 pub name: String,
939 pub repo_id: Option<String>,
940 /// The version published or deleted: for a container image, its
941 /// manifest's digest.
942 #[serde(skip_serializing_if = "Option::is_none")]
943 pub version: Option<String>,
944 #[serde(skip_serializing_if = "Option::is_none")]
945 pub digest: Option<String>,
946 #[serde(skip_serializing_if = "Option::is_none")]
947 pub size: Option<u64>,
948 /// On publish: the tags that now point to the version.
949 #[serde(skip_serializing_if = "Option::is_none")]
950 pub tags: Option<Vec<String>>,
951 /// On `package.visibility_changed`: `public` or `private`.
952 #[serde(skip_serializing_if = "Option::is_none")]
953 pub visibility: Option<String>,
954}
955
956/// `queue.changed`: a repository's merge queue gained, lost or settled an
957/// entry, so the next batch may be ready to test.
958#[derive(Debug, Serialize)]
959#[serde(rename_all = "camelCase")]
960pub struct QueueChanged {
961 pub repo_id: String,
962}
963
964#[cfg(test)]
965mod tests {
966 use super::*;
967
968 #[test]
969 fn comment_edits_and_deletes_say_what_it_was() {
970 let edited = CommentEdited {
971 comment_id: "cmt_1".into(),
972 repo_id: "rep_1".into(),
973 number: 7,
974 pull_id: Some("pr_1".into()),
975 changes: CommentChanges { body: ChangedFrom { from: "Before".into() } },
976 };
977 assert_eq!(
978 serde_json::to_value(edited).unwrap(),
979 serde_json::json!({
980 "commentId": "cmt_1", "repoId": "rep_1", "number": 7, "pullId": "pr_1",
981 "changes": { "body": { "from": "Before" } },
982 })
983 );
984 let deleted = CommentDeleted {
985 comment_id: "cmt_1".into(),
986 repo_id: "rep_1".into(),
987 number: 7,
988 pull_id: None,
989 comment: DeletedComment {
990 id: "cmt_1".into(),
991 body: "Gone".into(),
992 author: crate::credentials::Principal { id: "usr_1".into(), username: "ana".into() },
993 created_at: "2026-10-08T00:00:00Z".into(),
994 path: None,
995 line: None,
996 },
997 };
998 assert_eq!(
999 serde_json::to_value(deleted).unwrap(),
1000 serde_json::json!({
1001 "commentId": "cmt_1", "repoId": "rep_1", "number": 7,
1002 "comment": {
1003 "id": "cmt_1", "body": "Gone", "author": { "id": "usr_1", "username": "ana" },
1004 "createdAt": "2026-10-08T00:00:00Z", "path": null, "line": null,
1005 },
1006 })
1007 );
1008 }
1009
1010 #[test]
1011 fn a_release_change_is_githubs_activity_types() {
1012 let state = |draft, prerelease| Some(ReleaseState { draft, prerelease });
1013 assert_eq!(release_actions(None, state(true, false)), ["created"]);
1014 assert_eq!(release_actions(None, state(false, false)), ["created", "published", "released"]);
1015 assert_eq!(release_actions(None, state(false, true)), ["created", "published", "prereleased"]);
1016 assert_eq!(release_actions(state(true, true), state(false, true)), ["published", "prereleased"]);
1017 assert_eq!(release_actions(state(false, false), state(true, false)), ["unpublished"]);
1018 assert_eq!(release_actions(state(false, true), state(false, false)), ["edited", "released"]);
1019 assert_eq!(release_actions(state(false, false), state(false, true)), ["edited"]);
1020 assert_eq!(release_actions(state(true, false), state(true, false)), ["edited"]);
1021 assert_eq!(release_actions(state(false, false), None), ["deleted"]);
1022 for action in ["created", "published", "released", "prereleased", "edited", "unpublished", "deleted"] {
1023 assert_eq!(release_kind(action).map(|kind| kind.trim_start_matches("release.")), Some(action));
1024 }
1025 assert_eq!(release_kind("archived"), None);
1026 }
1027
1028 #[test]
1029 fn what_a_job_token_did_is_marked_and_carried_on() {
1030 let mut actor = crate::User { id: "wsp_1".into(), username: "acme".into(), ..crate::User::default() };
1031 let plain = marked(serde_json::json!({ "number": 4 }), Some(&actor));
1032 assert_eq!(caused_by_job(&plain), None);
1033 actor.token = Some(Box::new(crate::scopes::TokenAccess {
1034 job: Some(crate::scopes::JobToken { run_id: "run_9".into(), job_id: "job_1".into(), pull_requests: false }),
1035 ..Default::default()
1036 }));
1037 let by_job = marked(serde_json::json!({ "number": 4 }), Some(&actor));
1038 assert_eq!(caused_by_job(&by_job), Some("run_9"));
1039 assert_eq!(by_job["number"], 4);
1040 // A push by the job's token, and the pull request it moves.
1041 let push = GitPush {
1042 repo_id: "rep_1".into(),
1043 git_ref: "refs/heads/fix".into(),
1044 before: Some("a".into()),
1045 after: "b".into(),
1046 default_branch: false,
1047 unscanned: false,
1048 caused_by_job: job_run_of(&actor).map(str::to_owned),
1049 };
1050 let push = serde_json::to_value(push).unwrap();
1051 assert_eq!(caused_by_job(&push), Some("run_9"));
1052 assert_eq!(caused_by_job(&carried(serde_json::json!({ "number": 4 }), &push)), Some("run_9"));
1053 assert_eq!(caused_by_job(&carried(serde_json::json!({ "number": 4 }), &serde_json::json!({}))), None);
1054 }
1055
1056 #[test]
1057 fn a_push_says_it_was_unscanned_only_when_it_was() {
1058 let push = |unscanned| GitPush {
1059 repo_id: "rep_1".into(),
1060 git_ref: "refs/heads/import".into(),
1061 before: None,
1062 after: "abc".into(),
1063 default_branch: false,
1064 unscanned,
1065 caused_by_job: None,
1066 };
1067 let quiet = serde_json::to_value(push(false)).unwrap();
1068 assert!(quiet.get("unscanned").is_none());
1069 let flagged = serde_json::to_value(push(true)).unwrap();
1070 assert_eq!(flagged["unscanned"], true);
1071 assert_eq!(flagged["ref"], "refs/heads/import");
1072 }
1073
1074 fn renamed(from: &str, to: &str) -> WorkspaceRenamed {
1075 WorkspaceRenamed {
1076 workspace_id: "wsp_1".into(),
1077 from: from.into(),
1078 to: to.into(),
1079 }
1080 }
1081
1082 #[test]
1083 fn stale_slugs_leave_out_the_current_one() {
1084 assert_eq!(renamed("a", "b").stale_slugs("b"), vec!["a"]);
1085 // Delivered after a second rename, b → c: both move to c.
1086 assert_eq!(renamed("a", "b").stale_slugs("c"), vec!["a", "b"]);
1087 // Renamed back: a → b → a.
1088 assert_eq!(renamed("a", "b").stale_slugs("a"), vec!["b"]);
1089 }
1090
1091 fn transferred(from: &str, to: &str) -> RepoTransferred {
1092 RepoTransferred {
1093 repo_id: "rep_1".into(),
1094 name: "rocket".into(),
1095 from: from.into(),
1096 to: to.into(),
1097 }
1098 }
1099
1100 #[test]
1101 fn stale_paths_leave_out_the_current_one() {
1102 assert_eq!(transferred("a", "b").stale_paths("b/rocket"), vec!["a/rocket"]);
1103 // Delivered after a second transfer, b → c: both move to c.
1104 assert_eq!(
1105 transferred("a", "b").stale_paths("c/rocket"),
1106 vec!["a/rocket", "b/rocket"]
1107 );
1108 // Transferred back: a → b → a.
1109 assert_eq!(transferred("a", "b").stale_paths("a/rocket"), vec!["b/rocket"]);
1110 }
1111
1112 #[test]
1113 fn a_transfer_reads_as_published() {
1114 let data = serde_json::json!({ "repoId": "rep_1", "name": "rocket", "from": "a", "to": "b" });
1115 let event: RepoTransferred = serde_json::from_value(data).unwrap();
1116 assert_eq!((event.from.as_str(), event.to.as_str()), ("a", "b"));
1117 }
1118
1119 #[test]
1120 fn a_rename_names_both_paths_in_its_workspace() {
1121 let renamed = RepoRenamed {
1122 repo_id: "rep_1".into(),
1123 namespace: "acme".into(),
1124 from: "old".into(),
1125 to: "new".into(),
1126 };
1127 assert_eq!(renamed.stale_paths("acme/new"), vec!["acme/old"]);
1128 // Delivered after a transfer: both names in acme move.
1129 assert_eq!(renamed.stale_paths("flagon/new"), vec!["acme/old", "acme/new"]);
1130 }
1131
1132 #[test]
1133 fn reads_the_published_payload() {
1134 let data = serde_json::json!({ "workspaceId": "wsp_1", "from": "a", "to": "b" });
1135 let event: WorkspaceRenamed = serde_json::from_value(data).unwrap();
1136 assert_eq!((event.from.as_str(), event.to.as_str()), ("a", "b"));
1137 }
1138}