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.

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