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