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