Skip to content

Where people and agents ship software together. The open-source git platform for the whole job: issues, agents, checks and deploys to the edge.

1,537 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 /// The repository it was forked from, when it is a fork.
66 #[serde(skip_serializing_if = "Option::is_none")]
67 pub parent_id: Option<String>,
68}
69
70/// The payload of `repo.collaborator_added`, `repo.collaborator_removed`
71/// and `repo.collaborator_role_changed`: a person's own role on one
72/// repository (see `access`). `role` is the role they have now (null once
73/// removed); `previous_role` what they had before (null when added).
74#[derive(Debug, Serialize)]
75#[serde(rename_all = "camelCase")]
76pub struct RepoCollaborator {
77 pub repo_id: String,
78 pub namespace: String,
79 pub name: String,
80 pub username: String,
81 pub role: Option<crate::access::RepoRole>,
82 pub previous_role: Option<crate::access::RepoRole>,
83}
84
85#[derive(Debug, Serialize)]
86#[serde(rename_all = "camelCase")]
87pub struct RepoForked {
88 pub repo_id: String,
89 pub source_repo_id: String,
90 /// The pull request a working copy was made for; absent for a fork
91 /// someone made into a workspace.
92 #[serde(skip_serializing_if = "Option::is_none")]
93 pub pull_id: Option<String>,
94}
95
96/// The payload of `repo.detached`: a fork left its fork network, because
97/// it was detached or its parent changed who can see it.
98#[derive(Debug, Serialize)]
99#[serde(rename_all = "camelCase")]
100pub struct RepoDetached {
101 pub repo_id: String,
102 pub parent_id: String,
103}
104
105/// One branch or tag moved by a push. `after` is the commit it points to now.
106#[derive(Debug, Serialize)]
107#[serde(rename_all = "camelCase")]
108pub struct GitPush {
109 pub repo_id: String,
110 /// The full ref, such as `refs/heads/main`.
111 #[serde(rename = "ref")]
112 pub git_ref: String,
113 /// Where it pointed before; absent for a new branch or tag.
114 #[serde(skip_serializing_if = "Option::is_none")]
115 pub before: Option<String>,
116 pub after: String,
117 /// Whether the ref is the repository's default branch.
118 pub default_branch: bool,
119 /// Set when the push was too large to scan for secrets before it was
120 /// stored, and was let through: the security service scans
121 /// `before..after` after it landed. Absent otherwise.
122 #[serde(skip_serializing_if = "std::ops::Not::not")]
123 pub unscanned: bool,
124 /// Set when a workflow job's token pushed: the run's id (see
125 /// [`CAUSED_BY_JOB`]). Absent otherwise.
126 #[serde(rename = "causedByJob", skip_serializing_if = "Option::is_none")]
127 pub caused_by_job: Option<String>,
128 /// How many commits the push brought to the branch, counted along its
129 /// first-parent line from `after` back to `before` (a merge commit is
130 /// one), at most 50; one for a new branch. Absent when it was not
131 /// counted: a tag, a branch deleted, a pull request landed, a push the
132 /// store could not read back, or one from before this was recorded.
133 /// Home's digest (`activity_digest`) sums it.
134 #[serde(skip_serializing_if = "Option::is_none")]
135 pub commits: Option<u32>,
136 /// Set when landing a pull request moved the branch (repos `land`): its
137 /// number, so that the pull requests the push merged are told apart
138 /// from the one whose merge is recorded by whoever landed it.
139 #[serde(skip_serializing_if = "Option::is_none")]
140 pub landed_pull: Option<u32>,
141}
142
143/// A branch or tag deleted by a push. `before` is the commit it pointed to.
144#[derive(Debug, Serialize)]
145#[serde(rename_all = "camelCase")]
146pub struct GitDeleted {
147 pub repo_id: String,
148 /// The full ref, such as `refs/heads/feature`.
149 #[serde(rename = "ref")]
150 pub git_ref: String,
151 pub before: String,
152 /// Set when a workflow job's token deleted it: the run's id (see
153 /// [`CAUSED_BY_JOB`]). Absent otherwise.
154 #[serde(rename = "causedByJob", skip_serializing_if = "Option::is_none")]
155 pub caused_by_job: Option<String>,
156}
157
158/// The payload of `issue.opened`, `issue.updated`, `issue.assigned`,
159/// `issue.labeled`, `issue.unlabeled`, `issue.milestoned`,
160/// `issue.demilestoned`, `issue.closed` and `issue.reopened`; each uses
161/// the fields that apply to it.
162#[derive(Debug, Default, Serialize)]
163#[serde(rename_all = "camelCase")]
164pub struct IssueEvent {
165 pub issue_id: String,
166 pub repo_id: String,
167 pub number: u32,
168 /// Who opened it: g1t, for one its agent filed while at work.
169 #[serde(skip_serializing_if = "Option::is_none")]
170 pub author: Option<crate::credentials::Principal>,
171 /// For an issue g1t's agent filed: the person it was working for.
172 #[serde(skip_serializing_if = "Option::is_none")]
173 pub requested_by: Option<crate::credentials::Principal>,
174 #[serde(skip_serializing_if = "Option::is_none")]
175 pub title: Option<String>,
176 /// On close: `completed` or `not_planned`.
177 #[serde(skip_serializing_if = "Option::is_none")]
178 pub reason: Option<&'static str>,
179 /// On close: the number of the pull request whose merge closed it.
180 #[serde(skip_serializing_if = "Option::is_none")]
181 pub resolved_by: Option<u32>,
182 /// On close: the commit pushed to the default branch whose message
183 /// closed it (`Fixes #12`), when one did.
184 #[serde(skip_serializing_if = "Option::is_none")]
185 pub commit: Option<String>,
186 /// On `issue.assigned`: the people it is now assigned to.
187 #[serde(skip_serializing_if = "Option::is_none")]
188 pub assignees: Option<Vec<String>>,
189 /// On `issue.assigned`: those of them who were not before.
190 #[serde(skip_serializing_if = "Option::is_none")]
191 pub added: Option<Vec<String>>,
192 /// On `issue.labeled` and `issue.unlabeled`: the label put on or taken
193 /// off. One event for each.
194 #[serde(skip_serializing_if = "Option::is_none")]
195 pub label: Option<EventLabel>,
196 /// On `issue.milestoned`: the milestone it was put in; on
197 /// `issue.demilestoned`, the one it was taken out of.
198 #[serde(skip_serializing_if = "Option::is_none")]
199 pub milestone: Option<crate::work::MilestoneRef>,
200}
201
202/// A label, as `issue.labeled`, `pull.labeled` and their `unlabeled` say.
203#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize)]
204pub struct EventLabel {
205 pub name: String,
206 /// Six hex digits.
207 pub color: String,
208}
209
210/// The payload of `pull.opened`, `pull.ready`, `pull.updated` (its head
211/// moved), `pull.closed`, `pull.reopened`, `pull.converted_to_draft`,
212/// `pull.merged`, `pull.assigned`,
213/// `pull.review_requested` and `pull.review_request_removed` (reviewers
214/// asked, or no longer), `pull.labeled` and `pull.unlabeled`,
215/// `pull.milestoned` and `pull.demilestoned`, `pull.base_changed` (the
216/// branch it merges into changed), `pull.stalled` (g1t stopped seeing it
217/// through until a person steps in) and `pull.resumed` (it picked back
218/// up); each uses the fields that apply to it.
219#[derive(Debug, Default, Serialize)]
220#[serde(rename_all = "camelCase")]
221pub struct PullEvent {
222 pub pull_id: String,
223 pub repo_id: String,
224 pub number: u32,
225 /// Who opened it: g1t, for a change g1t made.
226 #[serde(skip_serializing_if = "Option::is_none")]
227 pub author: Option<crate::credentials::Principal>,
228 /// For a change g1t made: the person who asked for it.
229 #[serde(skip_serializing_if = "Option::is_none")]
230 pub requested_by: Option<crate::credentials::Principal>,
231 /// The number of the issue it is for.
232 #[serde(skip_serializing_if = "Option::is_none")]
233 pub issue: Option<u32>,
234 #[serde(skip_serializing_if = "Option::is_none")]
235 pub agent: Option<String>,
236 /// On merge: the commit the branch now points to. On update, when
237 /// marked ready and when reopened: the head of the change.
238 #[serde(skip_serializing_if = "Option::is_none")]
239 pub commit: Option<String>,
240 /// On close: the pull request that was merged instead.
241 #[serde(skip_serializing_if = "Option::is_none")]
242 pub superseded_by: Option<u32>,
243 /// On `pull.assigned`: the people it is now assigned to.
244 #[serde(skip_serializing_if = "Option::is_none")]
245 pub assignees: Option<Vec<String>>,
246 /// On `pull.assigned`: those newly assigned.
247 #[serde(skip_serializing_if = "Option::is_none")]
248 pub added: Option<Vec<String>>,
249 /// On `pull.review_requested`: the reviewers newly asked; on
250 /// `pull.review_request_removed`, those no longer asked.
251 #[serde(skip_serializing_if = "Option::is_none")]
252 pub reviewers: Option<Vec<String>>,
253 /// On `pull.review_requested` and `pull.review_request_removed`: the
254 /// teams newly asked, or no longer, each with the people it asks.
255 #[serde(skip_serializing_if = "Option::is_none")]
256 pub teams: Option<Vec<TeamRequested>>,
257 /// On `pull.review_requested`: asked because they own files it changes
258 /// (its CODEOWNERS file), not by a person.
259 #[serde(skip_serializing_if = "std::ops::Not::not")]
260 pub code_owners: bool,
261 /// On `pull.stalled`: why g1t stopped, and what would start it again.
262 #[serde(skip_serializing_if = "Option::is_none")]
263 pub detail: Option<String>,
264 /// On `pull.auto_merge_disabled`: the username of who had turned
265 /// auto-merge on, who is told it is off.
266 #[serde(skip_serializing_if = "Option::is_none")]
267 pub auto_merge_by: Option<String>,
268 /// On `pull.auto_merge_disabled`: g1t turned it off because the pull
269 /// request joined the merge queue, which lands it. Nothing is left for
270 /// anyone to do, so nobody's inbox is told.
271 #[serde(skip_serializing_if = "std::ops::Not::not")]
272 pub queued: bool,
273 /// On `pull.labeled` and `pull.unlabeled`: the label put on or taken off.
274 #[serde(skip_serializing_if = "Option::is_none")]
275 pub label: Option<EventLabel>,
276 /// On `pull.milestoned`: the milestone it was put in; on
277 /// `pull.demilestoned`, the one it was taken out of.
278 #[serde(skip_serializing_if = "Option::is_none")]
279 pub milestone: Option<crate::work::MilestoneRef>,
280 /// On `pull.opened` and `pull.base_changed`: the branch it merges into.
281 #[serde(skip_serializing_if = "Option::is_none")]
282 pub base: Option<String>,
283}
284
285/// A team asked to review a pull request.
286#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, serde::Deserialize)]
287#[serde(rename_all = "camelCase")]
288pub struct TeamRequested {
289 /// `workspace/slug`.
290 pub team: String,
291 /// Everyone in it who is told: the whole team, or, with review
292 /// assignment, the people picked (and the rest when it says to tell
293 /// them). Never the pull request's author.
294 pub notified: Vec<String>,
295 /// With review assignment: the people picked, who are asked as
296 /// reviewers themselves.
297 #[serde(default)]
298 pub assigned: Vec<String>,
299}
300
301/// The payload of every `team.*` event: `team.created`, `team.edited`,
302/// `team.deleted`; `team.member_added`, `team.member_role_changed`,
303/// `team.member_removed` (with `username`, `role` and `previousRole`);
304/// and `team.repo_added`, `team.repo_role_changed`, `team.repo_removed`
305/// (with `repoId`, `repo`, `repoRole` and `previousRepoRole`), which also
306/// name the repository as the event's own.
307#[derive(Clone, Debug, Default, Serialize)]
308#[serde(rename_all = "camelCase")]
309pub struct TeamChanged {
310 pub workspace: String,
311 pub team_id: String,
312 /// The team's slug, as it is now.
313 pub team: String,
314 pub name: String,
315 pub visibility: Option<crate::teams::TeamVisibility>,
316 /// The parent's slug.
317 #[serde(skip_serializing_if = "Option::is_none")]
318 pub parent: Option<String>,
319 /// On `team.edited`: what changed, such as `name` or `parent`.
320 #[serde(skip_serializing_if = "Vec::is_empty")]
321 pub changes: Vec<String>,
322 #[serde(skip_serializing_if = "Option::is_none")]
323 pub username: Option<String>,
324 #[serde(skip_serializing_if = "Option::is_none")]
325 pub role: Option<crate::teams::TeamRole>,
326 #[serde(skip_serializing_if = "Option::is_none")]
327 pub previous_role: Option<crate::teams::TeamRole>,
328 #[serde(skip_serializing_if = "Option::is_none")]
329 pub repo_id: Option<String>,
330 /// `workspace/name`.
331 #[serde(skip_serializing_if = "Option::is_none")]
332 pub repo: Option<String>,
333 #[serde(skip_serializing_if = "Option::is_none")]
334 pub repo_role: Option<crate::access::RepoRole>,
335 #[serde(skip_serializing_if = "Option::is_none")]
336 pub previous_repo_role: Option<crate::access::RepoRole>,
337}
338
339/// `deployment.succeeded` and `deployment.failed`: a build of a project
340/// finished, for production or for one pull request's preview.
341#[derive(Debug, Serialize)]
342#[serde(rename_all = "camelCase")]
343pub struct DeploymentEvent {
344 pub deployment_id: String,
345 pub project_id: String,
346 pub repo_id: String,
347 pub workspace: String,
348 /// The project's slug.
349 pub project: String,
350 /// `production` or `preview`.
351 pub kind: String,
352 pub branch: Option<String>,
353 /// For a preview: its pull request.
354 pub number: Option<u32>,
355 pub commit: String,
356 /// Where the deployment is on the site, such as
357 /// `/acme/rocket/deployments/dpl_1`.
358 pub path: String,
359 /// For a failure: what went wrong.
360 pub error: Option<String>,
361 /// For a success: whether the deployment before it, of the same app, failed.
362 pub recovered: bool,
363 /// Who started it, by username, or `g1t`.
364 pub triggered_by: String,
365}
366
367/// `checks.completed`: a run of an issue's acceptance checks against a pull
368/// request finished.
369#[derive(Debug, Serialize)]
370#[serde(rename_all = "camelCase")]
371pub struct ChecksEvent {
372 pub pull_id: String,
373 pub repo_id: String,
374 pub number: u32,
375 /// `passed`, `failed` or `errored`.
376 pub status: &'static str,
377 /// The commit that was checked.
378 pub commit: String,
379}
380
381/// `workflow.completed`: a GitHub Actions run finished.
382#[derive(Debug, Serialize)]
383#[serde(rename_all = "camelCase")]
384pub struct WorkflowEvent {
385 pub run_id: String,
386 pub repo_id: String,
387 /// The workflow's name, and its file.
388 pub workflow: String,
389 pub path: String,
390 /// The run's number among the workflow's runs.
391 pub number: u64,
392 /// The GitHub event that started it, such as `push`.
393 pub event: String,
394 /// `success`, `failure`, `cancelled` or `skipped`.
395 pub conclusion: String,
396 #[serde(rename = "ref")]
397 pub git_ref: String,
398 pub sha: String,
399 /// The pull request it ran for, if any.
400 #[serde(skip_serializing_if = "Option::is_none")]
401 pub pull: Option<u32>,
402}
403
404/// `comment.created`. `number` is the issue or pull request commented on.
405#[derive(Debug, Default, Serialize)]
406#[serde(rename_all = "camelCase")]
407pub struct CommentCreated {
408 pub comment_id: String,
409 pub repo_id: String,
410 pub number: u32,
411 /// Set when the comment is on a pull request.
412 #[serde(skip_serializing_if = "Option::is_none")]
413 pub pull_id: Option<String>,
414 /// Set when the comment is a review: approve or request changes.
415 #[serde(skip_serializing_if = "Option::is_none")]
416 pub verdict: Option<crate::work::Verdict>,
417 /// Set when one of the workspace's agents wrote it, as itself. The
418 /// event's actor is then the person it acted for (`actingFor`).
419 #[serde(skip_serializing_if = "Option::is_none")]
420 pub agent: Option<crate::work::AgentRef>,
421 /// Who the agent acted for, set with `agent`.
422 #[serde(skip_serializing_if = "Option::is_none")]
423 pub acting_for: Option<crate::credentials::Principal>,
424 /// An agent's review, advisory: its verdict counts toward nothing.
425 #[serde(skip_serializing_if = "std::ops::Not::not")]
426 pub advisory: bool,
427}
428
429/// `comment.edited`: a comment's text changed. `changes.body.from` is what
430/// it said before; the comment as it is now is read by `commentId`.
431#[derive(Debug, Serialize)]
432#[serde(rename_all = "camelCase")]
433pub struct CommentEdited {
434 pub comment_id: String,
435 pub repo_id: String,
436 pub number: u32,
437 /// Set when the comment is on a pull request.
438 #[serde(skip_serializing_if = "Option::is_none")]
439 pub pull_id: Option<String>,
440 pub changes: CommentChanges,
441}
442
443/// What an edit changed, as `comment.edited` says it.
444#[derive(Debug, Serialize)]
445pub struct CommentChanges {
446 pub body: ChangedFrom,
447}
448
449/// A field's value before a change.
450#[derive(Debug, Serialize)]
451pub struct ChangedFrom {
452 pub from: String,
453}
454
455/// `comment.deleted`: a comment was deleted. It no longer exists when the
456/// event is read, so `comment` is the comment as it was.
457#[derive(Debug, Serialize)]
458#[serde(rename_all = "camelCase")]
459pub struct CommentDeleted {
460 pub comment_id: String,
461 pub repo_id: String,
462 pub number: u32,
463 /// Set when the comment was on a pull request.
464 #[serde(skip_serializing_if = "Option::is_none")]
465 pub pull_id: Option<String>,
466 pub comment: DeletedComment,
467}
468
469/// A deleted comment, as it was.
470#[derive(Debug, Serialize)]
471#[serde(rename_all = "camelCase")]
472pub struct DeletedComment {
473 pub id: String,
474 pub body: String,
475 pub author: crate::credentials::Principal,
476 /// RFC 3339.
477 pub created_at: String,
478 /// For a comment on one line of a pull request's change: the file.
479 pub path: Option<String>,
480 /// And the line, as numbered after the change.
481 pub line: Option<u32>,
482}
483
484/// The payload of `commit_comment.created`, `commit_comment.edited` and
485/// `commit_comment.deleted`. `comment` is the comment as it is now, or as
486/// it was when deleted; `changes.body.from` is what an edit replaced.
487#[derive(Debug, Serialize)]
488#[serde(rename_all = "camelCase")]
489pub struct CommitCommentEvent {
490 pub comment_id: String,
491 pub repo_id: String,
492 /// The commit's full hash.
493 pub commit: String,
494 pub comment: crate::work::CommitComment,
495 #[serde(skip_serializing_if = "Option::is_none")]
496 pub changes: Option<CommentChanges>,
497 /// Where it is on g1t.sh: `/owner/name/commit/<hash>`.
498 pub link: String,
499 /// For the inbox, on `commit_comment.created`: the first line it says
500 /// something on, the people it mentions by name (never `g1t`), the
501 /// teams it mentions with the people each tells, and the commit's
502 /// author when their address is a g1t account's (a username).
503 #[serde(skip_serializing_if = "Option::is_none")]
504 pub excerpt: Option<String>,
505 #[serde(skip_serializing_if = "Vec::is_empty")]
506 pub mentions: Vec<String>,
507 #[serde(skip_serializing_if = "Vec::is_empty")]
508 pub team_mentions: Vec<crate::inbox::TeamMentioned>,
509 #[serde(skip_serializing_if = "Option::is_none")]
510 pub commit_author: Option<String>,
511}
512
513/// The payload of every `release.*` event: `release.created`,
514/// `release.published`, `release.released`, `release.prereleased`,
515/// `release.edited`, `release.unpublished` and `release.deleted`. One change
516/// to a release can be several of them (see [`release_actions`]).
517#[derive(Debug, Serialize)]
518#[serde(rename_all = "camelCase")]
519pub struct ReleaseEvent {
520 pub release_id: String,
521 pub repo_id: String,
522 pub tag_name: String,
523 /// As it is now; as it was, for `release.deleted`.
524 pub release: crate::about::Release,
525 /// On `release.edited`: `{ "name": { "from" }, "body": { "from" } }`
526 /// for what changed.
527 #[serde(skip_serializing_if = "Option::is_none")]
528 pub changes: Option<serde_json::Value>,
529}
530
531/// A release's state, for [`release_actions`]: whether it is a draft, and
532/// whether it is a prerelease.
533#[derive(Clone, Copy, Debug, PartialEq, Eq)]
534pub struct ReleaseState {
535 pub draft: bool,
536 pub prerelease: bool,
537}
538
539/// What a change to a release is, as GitHub's release activity types, in
540/// the order they are sent: from `before` (None: it did not exist) to
541/// `after` (None: deleted). A release made published is `created`,
542/// `published` and `released` (or `prereleased`); a draft published is
543/// `published` and `released` (or `prereleased`); made a draft again,
544/// `unpublished`; anything else `edited`, and a prerelease made a full
545/// release is `released` too.
546pub fn release_actions(before: Option<ReleaseState>, after: Option<ReleaseState>) -> Vec<&'static str> {
547 let published = |state: ReleaseState| if state.prerelease { "prereleased" } else { "released" };
548 match (before, after) {
549 (None, None) => Vec::new(),
550 (None, Some(after)) if after.draft => vec!["created"],
551 (None, Some(after)) => vec!["created", "published", published(after)],
552 (Some(_), None) => vec!["deleted"],
553 (Some(before), Some(after)) if before.draft && !after.draft => vec!["published", published(after)],
554 (Some(before), Some(after)) if !before.draft && after.draft => vec!["unpublished"],
555 (Some(before), Some(after)) if !after.draft && before.prerelease && !after.prerelease => vec!["edited", "released"],
556 (Some(_), Some(_)) => vec!["edited"],
557 }
558}
559
560/// The event kind for a release activity type from [`release_actions`].
561pub fn release_kind(action: &str) -> Option<&'static str> {
562 Some(match action {
563 "created" => "release.created",
564 "published" => "release.published",
565 "released" => "release.released",
566 "prereleased" => "release.prereleased",
567 "edited" => "release.edited",
568 "unpublished" => "release.unpublished",
569 "deleted" => "release.deleted",
570 _ => return None,
571 })
572}
573
574#[derive(Debug, Serialize)]
575#[serde(rename_all = "camelCase")]
576pub struct SessionAppended {
577 pub pull_id: String,
578 pub repo_id: String,
579 pub number: u32,
580 pub count: u32,
581}
582
583/// An event as stored in the log and delivered to subscribers. `data` is
584/// left as JSON; each reader decodes the types it cares about.
585#[derive(Clone, Debug, Serialize, serde::Deserialize)]
586#[serde(rename_all = "camelCase")]
587pub struct Event {
588 /// Sorts by the time the event was published.
589 pub id: String,
590 #[serde(rename = "type")]
591 pub kind: String,
592 /// The service that published it.
593 pub source: String,
594 /// RFC 3339.
595 pub time: String,
596 /// The repo the event concerns.
597 pub repo_id: Option<String>,
598 /// The user or agent that caused it, if any.
599 pub actor: Option<String>,
600 pub data: serde_json::Value,
601}
602
603/// `publish`, as a publisher sends it. Returns nothing.
604#[derive(Debug, Serialize)]
605pub struct Publish<T: Serialize> {
606 pub events: Vec<NewEvent<T>>,
607}
608
609/// `publish`, as the events service reads it.
610#[derive(Debug, serde::Deserialize)]
611pub struct PublishArgs {
612 pub events: Vec<Published>,
613}
614
615/// A [`NewEvent`] of any type, as received.
616#[derive(Debug, serde::Deserialize)]
617#[serde(rename_all = "camelCase")]
618pub struct Published {
619 #[serde(rename = "type")]
620 pub kind: String,
621 pub source: String,
622 #[serde(default)]
623 pub repo_id: Option<String>,
624 #[serde(default)]
625 pub actor: Option<String>,
626 pub data: serde_json::Value,
627}
628
629/// `list`: events from the log, newest first, or with `after` oldest first.
630/// Returns `Vec<Event>`.
631#[derive(Debug, Default, Serialize, serde::Deserialize)]
632#[serde(rename_all = "camelCase")]
633pub struct ListArgs {
634 #[serde(default)]
635 pub repo_id: Option<String>,
636 /// Only events of these repositories, by id: a workspace's activity
637 /// across its repositories. The caller has checked the viewer may read
638 /// each. At most [`MAX_LIST_REPOS`] are read.
639 #[serde(default, skip_serializing_if = "Vec::is_empty")]
640 pub repo_ids: Vec<String>,
641 /// Only these types; all types when empty.
642 #[serde(default)]
643 pub types: Vec<String>,
644 /// Only events older than this event id.
645 #[serde(default)]
646 pub before: Option<String>,
647 /// Only events the log recorded after this event id, and then oldest
648 /// first: a cursor to follow the log with. Events are ordered by when
649 /// the log wrote them, not by their ids, so one published a moment
650 /// before another but written after it is not skipped.
651 #[serde(default)]
652 pub after: Option<String>,
653 /// Only events by this account id.
654 #[serde(default)]
655 pub actor: Option<String>,
656 /// Only events about these issues or pull requests: their `number`, or
657 /// the `issue` a comment, review or link is on. All when empty.
658 #[serde(default)]
659 pub numbers: Vec<u32>,
660 /// Only events at or after this RFC 3339 time.
661 #[serde(default)]
662 pub since: Option<String>,
663 #[serde(default)]
664 pub limit: Option<u32>,
665}
666
667/// The most repositories one `list` reads with `repo_ids`.
668pub const MAX_LIST_REPOS: usize = 100;
669
670/// `workspace.renamed`: a workspace's slug changed from `from` to `to`.
671/// Every service that stores a slug moves its rows to the workspace's
672/// *current* slug (ask identity by `workspace_id`), so that a repeated or
673/// late delivery after a second rename still lands in the right place.
674#[derive(Clone, Debug, Serialize, serde::Deserialize)]
675#[serde(rename_all = "camelCase")]
676pub struct WorkspaceRenamed {
677 pub workspace_id: String,
678 pub from: String,
679 pub to: String,
680}
681
682impl WorkspaceRenamed {
683 /// The slugs whose rows move to `current`: the two this rename names,
684 /// minus `current` itself. Moving rows keyed by either converges on the
685 /// current slug whatever order renames are delivered in.
686 pub fn stale_slugs(&self, current: &str) -> Vec<String> {
687 let mut slugs: Vec<String> = Vec::new();
688 for slug in [&self.from, &self.to] {
689 if slug != current && !slugs.contains(slug) {
690 slugs.push(slug.clone());
691 }
692 }
693 slugs
694 }
695}
696
697/// `repo.updated`: a repository's website, topics or visibility
698/// changed. `visibility_changed` says whether it went public or private,
699/// which `repo.visibility_changed` also announces on its own.
700#[derive(Debug, Serialize, serde::Deserialize)]
701#[serde(rename_all = "camelCase")]
702pub struct RepoUpdated {
703 pub repo_id: String,
704 pub namespace: String,
705 pub name: String,
706 pub is_private: bool,
707 #[serde(default)]
708 pub visibility_changed: bool,
709}
710
711/// `project.updated`: a project's name or description changed. `primary`
712/// says whether it is its repository's own project, whose description
713/// search and lists of repositories show.
714#[derive(Debug, Serialize, serde::Deserialize)]
715#[serde(rename_all = "camelCase")]
716pub struct ProjectUpdated {
717 pub project_id: String,
718 pub workspace: String,
719 pub slug: String,
720 pub repo_id: String,
721 #[serde(default)]
722 pub primary: bool,
723 #[serde(default)]
724 pub description: Option<String>,
725}
726
727/// `repo.visibility_changed`: a repository went public or private.
728#[derive(Debug, Serialize, serde::Deserialize)]
729#[serde(rename_all = "camelCase")]
730pub struct RepoVisibilityChanged {
731 pub repo_id: String,
732 pub is_private: bool,
733}
734
735/// `repo.renamed`: a repository's name changed within its workspace,
736/// keeping its id and its git store key. Like `repo.transferred`, a path
737/// change: every service that keeps rows under the repository's path moves
738/// them to its *current* path (ask repos `path_by_id`), so a repeated or
739/// late delivery after a second rename or a transfer still lands in the
740/// right place. `g1t_kit::transfer::on_event` handles both.
741#[derive(Clone, Debug, Serialize, serde::Deserialize)]
742#[serde(rename_all = "camelCase")]
743pub struct RepoRenamed {
744 pub repo_id: String,
745 /// The workspace it is in.
746 pub namespace: String,
747 /// Its old name.
748 pub from: String,
749 /// Its new name.
750 pub to: String,
751}
752
753impl RepoRenamed {
754 /// The paths whose rows move to `current` (`namespace/name`): the two
755 /// this rename names, minus `current`.
756 pub fn stale_paths(&self, current: &str) -> Vec<String> {
757 let mut paths: Vec<String> = Vec::new();
758 for name in [&self.from, &self.to] {
759 let path = format!("{}/{name}", self.namespace);
760 if path != current && !paths.contains(&path) {
761 paths.push(path);
762 }
763 }
764 paths
765 }
766}
767
768/// `repo.deleted`: a repository was deleted. It is hidden everywhere and
769/// git refuses it, but it can be restored until `purge_after`, so services
770/// stop what runs for it (agents, workflows, deployments, indexing,
771/// webhook deliveries) and hide it, and keep what they hold until
772/// `repo.purged`. `repo.restored` brings it back.
773#[derive(Clone, Debug, Serialize, serde::Deserialize)]
774#[serde(rename_all = "camelCase")]
775pub struct RepoDeleted {
776 pub repo_id: String,
777 #[serde(default)]
778 pub namespace: String,
779 #[serde(default)]
780 pub name: String,
781 #[serde(default)]
782 pub is_private: bool,
783 /// RFC 3339: when it is purged unless restored first.
784 #[serde(default)]
785 pub purge_after: String,
786 /// It went with its workspace (`workspace.deleting`). Services that
787 /// handle the workspace as a whole (deployments pauses its apps rather
788 /// than taking them down) leave this one to that.
789 #[serde(default)]
790 pub with_workspace: bool,
791}
792
793/// `repo.restored`: a deleted repository is back, at its path, as it was.
794/// Services start again what `repo.deleted` stopped: index it, deploy its
795/// production, show it.
796#[derive(Clone, Debug, Serialize, serde::Deserialize)]
797#[serde(rename_all = "camelCase")]
798pub struct RepoRestored {
799 pub repo_id: String,
800 pub namespace: String,
801 pub name: String,
802 pub is_private: bool,
803 /// It came back with its workspace (`workspace.restored`).
804 #[serde(default)]
805 pub with_workspace: bool,
806}
807
808/// `repo.purged`: a deleted repository is gone for good, its git data
809/// with it. Services drop every row they keep for it by `repo_id`, except
810/// history that belongs to its workspace: ledgers, invoices and the audit
811/// log. Its path is free for a new repository.
812#[derive(Clone, Debug, Serialize, serde::Deserialize)]
813#[serde(rename_all = "camelCase")]
814pub struct RepoPurged {
815 pub repo_id: String,
816 pub namespace: String,
817 pub name: String,
818}
819
820/// `repo.archived` and `repo.unarchived`: a repository became read-only,
821/// or writable again. While archived, pushes are refused, issues and pull
822/// requests are locked, and agents and workflows do not run for it; its
823/// deployments keep serving.
824#[derive(Clone, Debug, Serialize, serde::Deserialize)]
825#[serde(rename_all = "camelCase")]
826pub struct RepoArchived {
827 pub repo_id: String,
828 pub namespace: String,
829 pub name: String,
830 pub archived: bool,
831}
832
833/// `repo.default_branch_changed`: the branch everything lands on is now
834/// `to`. `renamed` says whether `from` was renamed to `to` (open pull
835/// requests into it now target `to`) rather than another branch chosen.
836#[derive(Clone, Debug, Serialize, serde::Deserialize)]
837#[serde(rename_all = "camelCase")]
838pub struct RepoDefaultBranchChanged {
839 pub repo_id: String,
840 pub from: String,
841 pub to: String,
842 #[serde(default)]
843 pub renamed: bool,
844}
845
846/// `branch.renamed`: a branch was renamed. Pull requests from or into
847/// `from` follow it to `to`, and web addresses that name `from` redirect.
848#[derive(Clone, Debug, Serialize, serde::Deserialize)]
849#[serde(rename_all = "camelCase")]
850pub struct BranchRenamed {
851 pub repo_id: String,
852 pub from: String,
853 pub to: String,
854 /// Whether it is the default branch.
855 #[serde(default)]
856 pub default_branch: bool,
857}
858
859/// `repo.transferred`: a repository moved from one workspace to another,
860/// keeping its id and its name. Every service that keeps a repository
861/// under its path (`namespace/name`) or its workspace's slug moves those
862/// rows to the repository's *current* path (ask repos `path_by_id`), so a
863/// repeated or late delivery after a second transfer still lands in the
864/// right place. What was charged or recorded before the transfer stays
865/// with the workspace it happened in.
866#[derive(Clone, Debug, Serialize, serde::Deserialize)]
867#[serde(rename_all = "camelCase")]
868pub struct RepoTransferred {
869 pub repo_id: String,
870 pub name: String,
871 /// The workspace it left.
872 pub from: String,
873 /// The workspace it went to.
874 pub to: String,
875}
876
877impl RepoTransferred {
878 /// The paths whose rows move to `current` (`namespace/name`): the two
879 /// this transfer names, minus `current`. Moving rows keyed by either
880 /// converges whatever order transfers are delivered in.
881 pub fn stale_paths(&self, current: &str) -> Vec<String> {
882 let mut paths: Vec<String> = Vec::new();
883 for namespace in [&self.from, &self.to] {
884 let path = format!("{namespace}/{}", self.name);
885 if path != current && !paths.contains(&path) {
886 paths.push(path);
887 }
888 }
889 paths
890 }
891}
892
893/// `workspace.deleted`: a workspace is gone. Services drop what they keep
894/// for it alone (its webhooks, integrations, secrets, guardrails,
895/// agent queue) and keep what is history: ledgers, invoices and the audit
896/// log stay under its slug, which is never given to another workspace.
897#[derive(Clone, Debug, Serialize, serde::Deserialize)]
898#[serde(rename_all = "camelCase")]
899pub struct WorkspaceDeleted {
900 pub workspace_id: String,
901 pub slug: String,
902}
903
904/// `workspace.deleting`: an owner deleted a workspace, and it can be
905/// restored by g1t's staff until `purge_after`. Nobody can reach it in the
906/// meantime. Services hide what they keep for it and stop what runs for it,
907/// keeping their rows: repos deletes its repositories softly (each with a
908/// `repo.deleted` whose `with_workspace` is set), deployments pauses its
909/// apps, search drops it from results. `workspace.restored` undoes exactly
910/// that; once `purge_after` passes, `workspace.deleted` follows and
911/// services purge as for any deleted workspace.
912#[derive(Clone, Debug, Serialize, serde::Deserialize)]
913#[serde(rename_all = "camelCase")]
914pub struct WorkspaceDeleting {
915 pub workspace_id: String,
916 pub slug: String,
917 /// The username of the owner who deleted it.
918 pub by: String,
919 /// RFC 3339: when it is purged unless restored first.
920 pub purge_after: String,
921}
922
923/// `workspace.restored`: staff brought a deleted workspace back, with its
924/// members and tokens. Services undo what they did on `workspace.deleting`,
925/// and only that: a repository deleted on its own before stays deleted.
926#[derive(Clone, Debug, Serialize, serde::Deserialize)]
927#[serde(rename_all = "camelCase")]
928pub struct WorkspaceRestored {
929 pub workspace_id: String,
930 pub slug: String,
931}
932
933/// `user.deleting`: an account was deleted, by the person or by g1t's
934/// staff, and can be restored by staff until `purge_after`. Its sessions,
935/// tokens and keys have ended and it has left every workspace; services
936/// stop what they do for it (search drops its profile, nothing more is
937/// sent to it) and keep their rows. `user.restored` undoes that; once
938/// `purge_after` passes, `user.deleted` follows.
939#[derive(Clone, Debug, Serialize, serde::Deserialize)]
940#[serde(rename_all = "camelCase")]
941pub struct UserDeleting {
942 pub user_id: String,
943 pub username: String,
944 /// Whether g1t's staff deleted it rather than the person.
945 #[serde(default)]
946 pub by_staff: bool,
947 /// RFC 3339: when it is purged unless restored first.
948 pub purge_after: String,
949}
950
951/// `user.restored`: staff brought a deleted account back. It signs in
952/// again with its password; its old sessions and tokens stay ended.
953/// Services undo what they did on `user.deleting`.
954#[derive(Clone, Debug, Serialize, serde::Deserialize)]
955#[serde(rename_all = "camelCase")]
956pub struct UserRestored {
957 pub user_id: String,
958 pub username: String,
959}
960
961/// `user.deleted`: an account is gone for good. Services drop what they
962/// keep for it alone (its inbox, subscriptions, settings) and show what it
963/// wrote as `ghost` (`account_deletion::GHOST_USERNAME`, id
964/// `account_deletion::GHOST_ID`). Ledgers, invoices and audit logs keep
965/// its username. The username is never given to anyone again.
966#[derive(Clone, Debug, Serialize, serde::Deserialize)]
967#[serde(rename_all = "camelCase")]
968pub struct UserDeleted {
969 pub user_id: String,
970 pub username: String,
971}
972
973/// `user.updated`: an account was made, or changed what its profile shows
974/// (name, bio, avatar). Nothing private: ask identity for the profile.
975#[derive(Debug, Serialize, serde::Deserialize)]
976#[serde(rename_all = "camelCase")]
977pub struct UserUpdated {
978 pub username: String,
979}
980
981/// `user.email_added`, `user.email_verified`, `user.email_removed` and
982/// `user.primary_email_changed`: an account's addresses changed. Never the
983/// address itself; ask identity, as the person, for that.
984#[derive(Debug, Serialize, serde::Deserialize)]
985#[serde(rename_all = "camelCase")]
986pub struct UserEmailChanged {
987 pub user_id: String,
988 /// Whether g1t staff made the change.
989 #[serde(default)]
990 pub by_staff: bool,
991}
992
993/// `workspace.updated`: a workspace was made, or its name, description or
994/// icon changed. Ask identity for it by slug.
995#[derive(Debug, Serialize, serde::Deserialize)]
996#[serde(rename_all = "camelCase")]
997pub struct WorkspaceUpdated {
998 pub workspace_id: String,
999 pub slug: String,
1000}
1001
1002/// How someone came to be a member of a workspace (`workspace.member_joined`).
1003#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, serde::Deserialize)]
1004#[serde(rename_all = "snake_case")]
1005pub enum JoinedHow {
1006 /// They accepted a workspace invitation sent to them by name.
1007 Invitation,
1008 /// They made the workspace, and are its first owner.
1009 Created,
1010 /// They used an invite code or link that named the workspace.
1011 Joined,
1012}
1013
1014/// `workspace.member_joined`: a person became a member of a workspace,
1015/// published by identity as the membership is written. `how` says by
1016/// which door; the workspace's creator is `created`, so a listener that
1017/// greets new members can leave them out (the agents service's @g1t
1018/// welcomes everyone else, once). Never published for an agent or a
1019/// token: only a person joins.
1020#[derive(Clone, Debug, PartialEq, Eq, Serialize, serde::Deserialize)]
1021#[serde(rename_all = "camelCase")]
1022pub struct MemberJoined {
1023 pub workspace_id: String,
1024 /// The workspace's slug.
1025 pub workspace: String,
1026 pub user_id: String,
1027 pub username: String,
1028 pub role: crate::Role,
1029 pub how: JoinedHow,
1030}
1031
1032/// `invite.created`: someone (or staff) made an invite. Never the code or
1033/// the address it is for.
1034#[derive(Debug, Serialize, serde::Deserialize)]
1035#[serde(rename_all = "camelCase")]
1036pub struct InviteCreated {
1037 pub invite_id: String,
1038 /// The account that made it; null when staff did.
1039 pub inviter_id: Option<String>,
1040 /// The workspace it joins.
1041 pub workspace_id: Option<String>,
1042 /// Whether it is bound to one email address.
1043 pub bound: bool,
1044}
1045
1046/// `invite.redeemed`: an invite was used, by a new account or by an
1047/// existing one joining a workspace.
1048#[derive(Debug, Serialize, serde::Deserialize)]
1049#[serde(rename_all = "camelCase")]
1050pub struct InviteRedeemed {
1051 /// The invite's id, or a shared invite link's (`sinv_…`) when one made
1052 /// the account.
1053 pub invite_id: String,
1054 pub user_id: String,
1055 pub inviter_id: Option<String>,
1056 pub workspace_id: Option<String>,
1057 /// Whether it made the account.
1058 pub created_account: bool,
1059}
1060
1061/// The payload of `package.published`, `package.version_deleted`,
1062/// `package.deleted` and `package.visibility_changed`; each uses the fields
1063/// that apply to it. `repo_id` is the repository the package is linked to.
1064#[derive(Clone, Debug, Default, Serialize)]
1065#[serde(rename_all = "camelCase")]
1066pub struct PackageEvent {
1067 pub package_id: String,
1068 pub workspace: String,
1069 pub ecosystem: String,
1070 pub name: String,
1071 pub repo_id: Option<String>,
1072 /// The version published or deleted: for a container image, its
1073 /// manifest's digest.
1074 #[serde(skip_serializing_if = "Option::is_none")]
1075 pub version: Option<String>,
1076 #[serde(skip_serializing_if = "Option::is_none")]
1077 pub digest: Option<String>,
1078 #[serde(skip_serializing_if = "Option::is_none")]
1079 pub size: Option<u64>,
1080 /// On publish: the tags that now point to the version.
1081 #[serde(skip_serializing_if = "Option::is_none")]
1082 pub tags: Option<Vec<String>>,
1083 /// On `package.visibility_changed`: `public` or `private`.
1084 #[serde(skip_serializing_if = "Option::is_none")]
1085 pub visibility: Option<String>,
1086}
1087
1088/// `queue.changed`: a repository's merge queue gained, lost or settled an
1089/// entry, so the next batch may be ready to test.
1090#[derive(Debug, Serialize)]
1091#[serde(rename_all = "camelCase")]
1092pub struct QueueChanged {
1093 pub repo_id: String,
1094}
1095
1096/// The `doc.page.*` types the artifacts service (services/artifacts, TypeScript)
1097/// publishes, with no `repoId` on the event: a page may be in a private
1098/// space, so it never reaches a repository's timeline or webhooks.
1099pub const DOC_PAGE_EVENTS: [&str; 4] = ["doc.page.created", "doc.page.updated", "doc.page.archived", "doc.page.stale"];
1100
1101/// The `folio.*` types (Artifacts mode), with their payloads, live in
1102/// [`crate::folios`]; nothing publishes or subscribes to them yet.
1103pub use crate::folios::FOLIO_EVENTS;
1104
1105/// What every `doc.page.*` event carries (`DocPageEventData` in
1106/// events.ts). `doc.page.updated` adds `versionId`, `kind` and `authors`;
1107/// `doc.page.stale` adds `repoId`, `repo`, `commit`, `pull`, `paths` and
1108/// `owners` ([`DocPageStale`]).
1109#[derive(Clone, Debug, Serialize, serde::Deserialize)]
1110#[serde(rename_all = "camelCase")]
1111pub struct DocPageEvent {
1112 pub workspace: String,
1113 pub workspace_id: String,
1114 pub page_id: String,
1115 pub space_id: String,
1116 pub title: String,
1117 /// The page's address on the site.
1118 pub path: String,
1119}
1120
1121/// `doc.page.stale`: code a page cites changed.
1122#[derive(Clone, Debug, Serialize, serde::Deserialize)]
1123#[serde(rename_all = "camelCase")]
1124pub struct DocPageStale {
1125 #[serde(flatten)]
1126 pub page: DocPageEvent,
1127 pub repo_id: String,
1128 /// `owner/name`.
1129 pub repo: String,
1130 pub commit: String,
1131 /// The merged pull request's number, when a pull request made the change.
1132 pub pull: Option<u32>,
1133 pub paths: Vec<String>,
1134 /// Member keys: `user:<id>`, `agent:<id>`.
1135 pub owners: Vec<String>,
1136}
1137
1138/// `activity_digest`: what happened in some repositories, and to a
1139/// workspace's artifacts, over a span, counted. Returns [`ActivityDigest`].
1140/// Home reads it for what people and agents did since you were last there.
1141/// Fields are snake_case, as every service's arguments are.
1142///
1143/// The span is `[from, until)` in RFC 3339. Event ids sort by time, so the
1144/// service reads each repository's events of each type it counts as one
1145/// range of the `(repo_id, type, id)` index, from `id_floor(from)` to
1146/// `id_floor(until)`; a workspace's folio events (which carry no
1147/// repository) are the same range under a null repository, narrowed to
1148/// the workspace. That is indexed range scans per repository and type, and
1149/// it suits a workspace of tens of repositories. When a workspace has
1150/// hundreds, the next step is a daily rollup per workspace that this
1151/// method reads instead of the log; it is not built yet.
1152#[derive(Debug, Default, Serialize, serde::Deserialize)]
1153pub struct ActivityDigestArgs {
1154 /// The repositories to count, by id. The caller has checked the
1155 /// viewer may read each. At most `MAX_DIGEST_REPOS` are read.
1156 #[serde(default)]
1157 pub repo_ids: Vec<String>,
1158 /// The workspace's slug, for its `folio.*` events; none leaves
1159 /// artifacts out.
1160 #[serde(default)]
1161 pub workspace: Option<String>,
1162 /// The start of the span, inclusive. RFC 3339.
1163 pub from: String,
1164 /// The end of the span, exclusive. RFC 3339.
1165 pub until: String,
1166}
1167
1168/// The most repositories one digest reads.
1169pub const MAX_DIGEST_REPOS: usize = 50;
1170/// The most events one digest reads of repositories, and of folios; past
1171/// either the digest says it is not complete.
1172pub const MAX_DIGEST_EVENTS: u32 = 5000;
1173/// The most releases, packages and edited folios a digest lists.
1174pub const MAX_DIGEST_LISTED: usize = 50;
1175
1176/// What `activity_digest` returns.
1177#[derive(Debug, Default, Serialize, serde::Deserialize, PartialEq)]
1178pub struct ActivityDigest {
1179 pub from: String,
1180 pub until: String,
1181 /// One per repository that had any event counted; none for a quiet one.
1182 pub repos: Vec<RepoDigest>,
1183 /// The workspace's artifacts, when a workspace was named.
1184 pub folios: Option<FolioDigest>,
1185 /// False when more events fell in the span than were read, or more
1186 /// repositories were named than are read, so counts are low.
1187 pub complete: bool,
1188}
1189
1190/// How many times one actor did something. The actor is a member key:
1191/// `user:<id>` for a person (or g1t, `user:usr_g1t_agent`), `agent:<id>`
1192/// for one of the workspace's agents acting as itself, or empty when the
1193/// event named nobody.
1194#[derive(Debug, Clone, Default, Serialize, serde::Deserialize, PartialEq, Eq)]
1195pub struct ActorCount {
1196 pub actor: String,
1197 pub count: u32,
1198}
1199
1200/// Pushes by one actor, with the commits they brought.
1201#[derive(Debug, Clone, Default, Serialize, serde::Deserialize, PartialEq, Eq)]
1202pub struct PushesBy {
1203 pub actor: String,
1204 pub count: u32,
1205 pub commits: u32,
1206}
1207
1208/// Pushes to a repository's branches (`git.push` events for `refs/heads/`;
1209/// tags are not pushes here). A push whose commits were not counted
1210/// counts as one commit.
1211#[derive(Debug, Default, Serialize, serde::Deserialize, PartialEq, Eq)]
1212pub struct PushDigest {
1213 pub count: u32,
1214 pub commits: u32,
1215 /// The branches pushed to, by name, sorted.
1216 pub branches: Vec<String>,
1217 /// Most pushes first.
1218 pub by: Vec<PushesBy>,
1219 /// Of those, the pushes straight to the default branch: what landed
1220 /// without a pull request.
1221 pub default_branch: DefaultBranchPushes,
1222}
1223
1224#[derive(Debug, Default, Serialize, serde::Deserialize, PartialEq, Eq)]
1225pub struct DefaultBranchPushes {
1226 pub count: u32,
1227 pub commits: u32,
1228 pub by: Vec<PushesBy>,
1229 /// When the newest of them was. RFC 3339.
1230 pub last_at: Option<String>,
1231}
1232
1233/// Pull requests opened, merged and closed without merging, each by who did it.
1234#[derive(Debug, Default, Serialize, serde::Deserialize, PartialEq, Eq)]
1235pub struct PullDigest {
1236 pub opened: Vec<ActorCount>,
1237 pub merged: Vec<ActorCount>,
1238 pub closed: Vec<ActorCount>,
1239}
1240
1241/// Issues opened and closed, each by who did it.
1242#[derive(Debug, Default, Serialize, serde::Deserialize, PartialEq, Eq)]
1243pub struct IssueDigest {
1244 pub opened: Vec<ActorCount>,
1245 pub closed: Vec<ActorCount>,
1246}
1247
1248/// Builds that finished, by who set them off, and how many of the
1249/// successes were production.
1250#[derive(Debug, Default, Serialize, serde::Deserialize, PartialEq, Eq)]
1251pub struct DeploymentDigest {
1252 pub succeeded: Vec<ActorCount>,
1253 pub failed: Vec<ActorCount>,
1254 pub production: u32,
1255}
1256
1257/// A release published in the span.
1258#[derive(Debug, Default, Serialize, serde::Deserialize, PartialEq, Eq)]
1259pub struct ReleaseDigest {
1260 pub tag: String,
1261 pub name: Option<String>,
1262 pub actor: String,
1263 /// RFC 3339.
1264 pub at: String,
1265}
1266
1267/// A package version published in the span.
1268#[derive(Debug, Default, Serialize, serde::Deserialize, PartialEq, Eq)]
1269pub struct PackageDigest {
1270 pub ecosystem: String,
1271 pub name: String,
1272 pub version: String,
1273 pub actor: String,
1274 /// RFC 3339.
1275 pub at: String,
1276}
1277
1278/// One repository's span.
1279#[derive(Debug, Default, Serialize, serde::Deserialize, PartialEq)]
1280pub struct RepoDigest {
1281 pub repo_id: String,
1282 pub pushes: PushDigest,
1283 pub pulls: PullDigest,
1284 pub issues: IssueDigest,
1285 /// Reviews: `review.completed` (g1t's), and a comment with a verdict (a person's).
1286 pub reviews: Vec<ActorCount>,
1287 /// Comments without a verdict; one by an agent as itself is the agent's.
1288 pub comments: Vec<ActorCount>,
1289 pub deployments: DeploymentDigest,
1290 /// Newest first, at most `MAX_DIGEST_LISTED`.
1291 pub releases: Vec<ReleaseDigest>,
1292 /// Newest first, at most `MAX_DIGEST_LISTED`.
1293 pub packages: Vec<PackageDigest>,
1294}
1295
1296/// One folio (an artifact: a doc, slides, a design, a dashboard) whose
1297/// content changed, with everyone whose changes are in it, as member
1298/// keys. Never its title.
1299#[derive(Debug, Default, Serialize, serde::Deserialize, PartialEq, Eq)]
1300pub struct FolioEdited {
1301 pub folio_id: String,
1302 pub kind: String,
1303 pub authors: Vec<String>,
1304}
1305
1306/// A workspace's artifacts over the span: `folio.created` by who made
1307/// them, and the folios whose content changed (`folio.updated`).
1308#[derive(Debug, Default, Serialize, serde::Deserialize, PartialEq, Eq)]
1309pub struct FolioDigest {
1310 pub created: Vec<ActorCount>,
1311 /// Each folio once, at most `MAX_DIGEST_LISTED`.
1312 pub edited: Vec<FolioEdited>,
1313 /// How many folios changed, counting those past the cap.
1314 pub edited_count: u32,
1315}
1316
1317#[cfg(test)]
1318mod tests {
1319 use super::*;
1320
1321 #[test]
1322 fn comment_edits_and_deletes_say_what_it_was() {
1323 let edited = CommentEdited {
1324 comment_id: "cmt_1".into(),
1325 repo_id: "rep_1".into(),
1326 number: 7,
1327 pull_id: Some("pr_1".into()),
1328 changes: CommentChanges { body: ChangedFrom { from: "Before".into() } },
1329 };
1330 assert_eq!(
1331 serde_json::to_value(edited).unwrap(),
1332 serde_json::json!({
1333 "commentId": "cmt_1", "repoId": "rep_1", "number": 7, "pullId": "pr_1",
1334 "changes": { "body": { "from": "Before" } },
1335 })
1336 );
1337 let deleted = CommentDeleted {
1338 comment_id: "cmt_1".into(),
1339 repo_id: "rep_1".into(),
1340 number: 7,
1341 pull_id: None,
1342 comment: DeletedComment {
1343 id: "cmt_1".into(),
1344 body: "Gone".into(),
1345 author: crate::credentials::Principal { id: "usr_1".into(), username: "ana".into() },
1346 created_at: "2026-10-08T00:00:00Z".into(),
1347 path: None,
1348 line: None,
1349 },
1350 };
1351 assert_eq!(
1352 serde_json::to_value(deleted).unwrap(),
1353 serde_json::json!({
1354 "commentId": "cmt_1", "repoId": "rep_1", "number": 7,
1355 "comment": {
1356 "id": "cmt_1", "body": "Gone", "author": { "id": "usr_1", "username": "ana" },
1357 "createdAt": "2026-10-08T00:00:00Z", "path": null, "line": null,
1358 },
1359 })
1360 );
1361 }
1362
1363 #[test]
1364 fn a_release_change_is_githubs_activity_types() {
1365 let state = |draft, prerelease| Some(ReleaseState { draft, prerelease });
1366 assert_eq!(release_actions(None, state(true, false)), ["created"]);
1367 assert_eq!(release_actions(None, state(false, false)), ["created", "published", "released"]);
1368 assert_eq!(release_actions(None, state(false, true)), ["created", "published", "prereleased"]);
1369 assert_eq!(release_actions(state(true, true), state(false, true)), ["published", "prereleased"]);
1370 assert_eq!(release_actions(state(false, false), state(true, false)), ["unpublished"]);
1371 assert_eq!(release_actions(state(false, true), state(false, false)), ["edited", "released"]);
1372 assert_eq!(release_actions(state(false, false), state(false, true)), ["edited"]);
1373 assert_eq!(release_actions(state(true, false), state(true, false)), ["edited"]);
1374 assert_eq!(release_actions(state(false, false), None), ["deleted"]);
1375 for action in ["created", "published", "released", "prereleased", "edited", "unpublished", "deleted"] {
1376 assert_eq!(release_kind(action).map(|kind| kind.trim_start_matches("release.")), Some(action));
1377 }
1378 assert_eq!(release_kind("archived"), None);
1379 }
1380
1381 #[test]
1382 fn what_a_job_token_did_is_marked_and_carried_on() {
1383 let mut actor = crate::User { id: "wsp_1".into(), username: "acme".into(), ..crate::User::default() };
1384 let plain = marked(serde_json::json!({ "number": 4 }), Some(&actor));
1385 assert_eq!(caused_by_job(&plain), None);
1386 actor.token = Some(Box::new(crate::scopes::TokenAccess {
1387 job: Some(crate::scopes::JobToken { run_id: "run_9".into(), job_id: "job_1".into(), pull_requests: false }),
1388 ..Default::default()
1389 }));
1390 let by_job = marked(serde_json::json!({ "number": 4 }), Some(&actor));
1391 assert_eq!(caused_by_job(&by_job), Some("run_9"));
1392 assert_eq!(by_job["number"], 4);
1393 // A push by the job's token, and the pull request it moves.
1394 let push = GitPush {
1395 repo_id: "rep_1".into(),
1396 git_ref: "refs/heads/fix".into(),
1397 before: Some("a".into()),
1398 after: "b".into(),
1399 default_branch: false,
1400 unscanned: false,
1401 caused_by_job: job_run_of(&actor).map(str::to_owned),
1402 commits: Some(3),
1403 landed_pull: None,
1404 };
1405 let push = serde_json::to_value(push).unwrap();
1406 assert_eq!(caused_by_job(&push), Some("run_9"));
1407 assert_eq!(caused_by_job(&carried(serde_json::json!({ "number": 4 }), &push)), Some("run_9"));
1408 assert_eq!(caused_by_job(&carried(serde_json::json!({ "number": 4 }), &serde_json::json!({}))), None);
1409 }
1410
1411 #[test]
1412 fn a_push_says_it_was_unscanned_only_when_it_was() {
1413 let push = |unscanned| GitPush {
1414 repo_id: "rep_1".into(),
1415 git_ref: "refs/heads/import".into(),
1416 before: None,
1417 after: "abc".into(),
1418 default_branch: false,
1419 unscanned,
1420 caused_by_job: None,
1421 commits: None,
1422 landed_pull: None,
1423 };
1424 let quiet = serde_json::to_value(push(false)).unwrap();
1425 assert!(quiet.get("unscanned").is_none());
1426 let flagged = serde_json::to_value(push(true)).unwrap();
1427 assert_eq!(flagged["unscanned"], true);
1428 assert_eq!(flagged["ref"], "refs/heads/import");
1429 assert!(quiet.get("landedPull").is_none());
1430 }
1431
1432 fn renamed(from: &str, to: &str) -> WorkspaceRenamed {
1433 WorkspaceRenamed {
1434 workspace_id: "wsp_1".into(),
1435 from: from.into(),
1436 to: to.into(),
1437 }
1438 }
1439
1440 #[test]
1441 fn stale_slugs_leave_out_the_current_one() {
1442 assert_eq!(renamed("a", "b").stale_slugs("b"), vec!["a"]);
1443 // Delivered after a second rename, b → c: both move to c.
1444 assert_eq!(renamed("a", "b").stale_slugs("c"), vec!["a", "b"]);
1445 // Renamed back: a → b → a.
1446 assert_eq!(renamed("a", "b").stale_slugs("a"), vec!["b"]);
1447 }
1448
1449 fn transferred(from: &str, to: &str) -> RepoTransferred {
1450 RepoTransferred {
1451 repo_id: "rep_1".into(),
1452 name: "rocket".into(),
1453 from: from.into(),
1454 to: to.into(),
1455 }
1456 }
1457
1458 #[test]
1459 fn stale_paths_leave_out_the_current_one() {
1460 assert_eq!(transferred("a", "b").stale_paths("b/rocket"), vec!["a/rocket"]);
1461 // Delivered after a second transfer, b → c: both move to c.
1462 assert_eq!(
1463 transferred("a", "b").stale_paths("c/rocket"),
1464 vec!["a/rocket", "b/rocket"]
1465 );
1466 // Transferred back: a → b → a.
1467 assert_eq!(transferred("a", "b").stale_paths("a/rocket"), vec!["b/rocket"]);
1468 }
1469
1470 #[test]
1471 fn a_transfer_reads_as_published() {
1472 let data = serde_json::json!({ "repoId": "rep_1", "name": "rocket", "from": "a", "to": "b" });
1473 let event: RepoTransferred = serde_json::from_value(data).unwrap();
1474 assert_eq!((event.from.as_str(), event.to.as_str()), ("a", "b"));
1475 }
1476
1477 #[test]
1478 fn a_rename_names_both_paths_in_its_workspace() {
1479 let renamed = RepoRenamed {
1480 repo_id: "rep_1".into(),
1481 namespace: "acme".into(),
1482 from: "old".into(),
1483 to: "new".into(),
1484 };
1485 assert_eq!(renamed.stale_paths("acme/new"), vec!["acme/old"]);
1486 // Delivered after a transfer: both names in acme move.
1487 assert_eq!(renamed.stale_paths("flagon/new"), vec!["acme/old", "acme/new"]);
1488 }
1489
1490 #[test]
1491 fn a_member_joining_says_by_which_door() {
1492 let joined = MemberJoined {
1493 workspace_id: "wsp_1".into(),
1494 workspace: "acme".into(),
1495 user_id: "usr_ada".into(),
1496 username: "ada".into(),
1497 role: crate::Role::Member,
1498 how: JoinedHow::Invitation,
1499 };
1500 let data = serde_json::to_value(&joined).unwrap();
1501 assert_eq!(
1502 data,
1503 serde_json::json!({
1504 "workspaceId": "wsp_1",
1505 "workspace": "acme",
1506 "userId": "usr_ada",
1507 "username": "ada",
1508 "role": "member",
1509 "how": "invitation",
1510 })
1511 );
1512 let back: MemberJoined = serde_json::from_value(data).unwrap();
1513 assert_eq!(back, joined);
1514 assert_eq!(serde_json::to_value(JoinedHow::Created).unwrap(), "created");
1515 assert_eq!(serde_json::to_value(JoinedHow::Joined).unwrap(), "joined");
1516 }
1517
1518 #[test]
1519 fn reads_the_published_payload() {
1520 let data = serde_json::json!({ "workspaceId": "wsp_1", "from": "a", "to": "b" });
1521 let event: WorkspaceRenamed = serde_json::from_value(data).unwrap();
1522 assert_eq!((event.from.as_str(), event.to.as_str()), ("a", "b"));
1523 }
1524
1525 #[test]
1526 fn a_stale_page_reads_as_published() {
1527 let data = serde_json::json!({
1528 "workspace": "acme", "workspaceId": "wsp_1", "pageId": "pag_1", "spaceId": "spc_1",
1529 "title": "Exports", "path": "/acme/-/docs/general/exports-pag_1",
1530 "repoId": "rep_1", "repo": "acme/web", "commit": "abc", "pull": 431,
1531 "paths": ["src/export.ts"], "owners": ["user:usr_1"]
1532 });
1533 let event: DocPageStale = serde_json::from_value(data).unwrap();
1534 assert_eq!((event.page.page_id.as_str(), event.pull), ("pag_1", Some(431)));
1535 assert!(DOC_PAGE_EVENTS.contains(&"doc.page.stale"));
1536 }
1537}