Skip to content

g1t/services/work/src/retired.rs

323 lines13,532 bytesCodeBlame
1//! Repositories that are archived, deleted or purged, and branches
2//! renamed: what issues, pull requests and agents do about each.
3//!
4//! An archived repository is read-only: its issues and pull requests are
5//! locked and nothing new starts on it. A deleted one looks missing (repos
6//! hides it) and keeps its rows for a restore. A purged one is gone, and
7//! every row kept for it goes with it.
8
9use g1t_contracts::events::{BranchRenamed, Event, RepoArchived, RepoDeleted};
10use g1t_contracts::repos::{Repo, RepoStatus, StatusByIdArgs, archived_message};
11use g1t_contracts::{FailureCode, Outcome};
12use g1t_contracts::time::rfc3339;
13use g1t_kit::now_ms;
14use serde::{Deserialize, Serialize};
15use worker::Result;
16
17use crate::Work;
18
19/// `Ok` when `repo` may be changed; refused, saying why, when it is
20/// archived.
21pub(crate) fn writable(repo: &Repo) -> Outcome<()> {
22 if repo.archived() {
23 Outcome::fail(FailureCode::Forbidden, archived_message(&repo.namespace, &repo.name))
24 } else {
25 Outcome::Ok(())
26 }
27}
28
29/// `repo` as found, unless it is archived: then refused, as [`writable`]
30/// says. For the steps g1t starts by itself, which stop on a refusal.
31pub(crate) fn unless_archived(repo: Outcome<Repo>) -> Outcome<Repo> {
32 match repo {
33 Outcome::Ok(repo) => match writable(&repo) {
34 Outcome::Ok(()) => Outcome::Ok(repo),
35 Outcome::Fail(failure) => Outcome::Fail(failure),
36 },
37 failed => failed,
38 }
39}
40
41/// `repo.purged`: every row kept for the repository, `?1` its id. Rows
42/// kept by pull request go first, while the pull requests still name them.
43pub(crate) const PURGED: &[&str] = &[
44 "DELETE FROM session_entries WHERE pull_id IN (SELECT id FROM pulls WHERE repo_id = ?1)",
45 "DELETE FROM check_runs WHERE pull_id IN (SELECT id FROM pulls WHERE repo_id = ?1)",
46 "DELETE FROM review_runs WHERE pull_id IN (SELECT id FROM pulls WHERE repo_id = ?1)",
47 "DELETE FROM agent_messages WHERE repo_id = ?1 OR pull_id IN (SELECT id FROM pulls WHERE repo_id = ?1)",
48 "DELETE FROM queue_entries WHERE repo_id = ?1",
49 "DELETE FROM agent_mentions WHERE repo_id = ?1",
50 "DELETE FROM agent_rules WHERE repo_id = ?1",
51 "DELETE FROM pull_confidence WHERE repo_id = ?1",
52 "DELETE FROM run_confidence WHERE repo_id = ?1",
53 "DELETE FROM confidence_rules WHERE repo_id = ?1",
54 "DELETE FROM agent_runs WHERE repo_id = ?1",
55 "DELETE FROM commit_statuses WHERE repo_id = ?1",
56 "DELETE FROM plans WHERE repo_id = ?1",
57 "DELETE FROM comments WHERE repo_id = ?1",
58 "DELETE FROM pulls WHERE repo_id = ?1",
59 "DELETE FROM issues WHERE repo_id = ?1",
60 "DELETE FROM labels WHERE repo_id = ?1",
61 "DELETE FROM milestones WHERE repo_id = ?1",
62 "DELETE FROM counters WHERE repo_id = ?1",
63 "DELETE FROM repo_settings WHERE repo_id = ?1",
64 "DELETE FROM memories WHERE scope = 'project' AND scope_key = ?1",
65 "DELETE FROM guardrails WHERE scope <> 'workspace' AND scope_key = ?1",
66];
67
68/// A repository renamed or transferred (see `g1t_kit::transfer`): runs
69/// waiting for an agent slot name it by path in their payload, at `$.repo`
70/// or `$.job.repo`; they follow it, into its workspace's queue now.
71pub(crate) const WAITS_MOVED: &[&str] = &[
72 "UPDATE agent_waits SET workspace = lower(?3),
73 payload = json_set(payload, '$.repo.namespace', ?3, '$.repo.name', ?6)
74 WHERE json_valid(payload)
75 AND lower(json_extract(payload, '$.repo.namespace')) = lower(?4)
76 AND lower(json_extract(payload, '$.repo.name')) = lower(?7)",
77 "UPDATE agent_waits SET workspace = lower(?3),
78 payload = json_set(payload, '$.job.repo.namespace', ?3, '$.job.repo.name', ?6)
79 WHERE json_valid(payload)
80 AND lower(json_extract(payload, '$.job.repo.namespace')) = lower(?4)
81 AND lower(json_extract(payload, '$.job.repo.name')) = lower(?7)",
82];
83
84/// What a run stopped because its repository was archived or deleted says
85/// as its last step; [`Work::runs_in_repo`] finds such runs by it.
86const STOPPED_STEP: &str = "Stopped: the repository was archived or deleted.";
87
88/// `repo.deleted` and `repo.archived`: the repository's agent runs that
89/// are queued or running stop, `?1` the step they end on, `?2` the time,
90/// `?3` its id.
91const STOP_RUNS: &str = "UPDATE agent_runs SET status = 'stopped', step = ?1, finished_at = ?2, updated_at = ?2
92 WHERE repo_id = ?3 AND status IN ('queued', 'running')";
93
94/// And runs waiting for an agent slot in it are dropped: `?1` its
95/// workspace, `?2` its name, as the payload names it (see [`WAITS_MOVED`]).
96const DROP_WAITS: &[&str] = &[
97 "DELETE FROM agent_waits WHERE json_valid(payload)
98 AND lower(json_extract(payload, '$.repo.namespace')) = lower(?1)
99 AND lower(json_extract(payload, '$.repo.name')) = lower(?2)",
100 "DELETE FROM agent_waits WHERE json_valid(payload)
101 AND lower(json_extract(payload, '$.job.repo.namespace')) = lower(?1)
102 AND lower(json_extract(payload, '$.job.repo.name')) = lower(?2)",
103];
104
105/// `runs_in_repo` (internal, for the runner): the agent runs of a
106/// repository whose sandboxes should be stopped: those queued or running,
107/// and those work stopped in the last hour because the repository was
108/// archived or deleted. Takes `{ "repoId" }`; returns `[RepoRun]`.
109#[derive(Deserialize)]
110#[serde(rename_all = "camelCase")]
111pub(crate) struct RunsInRepoArgs {
112 pub repo_id: String,
113}
114
115#[derive(Debug, Deserialize, Serialize)]
116#[serde(rename_all = "camelCase")]
117pub(crate) struct RepoRun {
118 pub run_id: String,
119 pub sandbox: String,
120 pub kind: String,
121 pub status: String,
122 pub pull_id: Option<String>,
123}
124
125/// The repository, by id and path, that `event` says was deleted or
126/// archived (not unarchived): its runs stop.
127fn stopping(event: &Event) -> Option<(String, String, String)> {
128 let data = event.data.clone();
129 match event.kind.as_str() {
130 "repo.deleted" => serde_json::from_value::<RepoDeleted>(data).ok().map(|e| (e.repo_id, e.namespace, e.name)),
131 "repo.archived" => serde_json::from_value::<RepoArchived>(data)
132 .ok()
133 .filter(|e| e.archived)
134 .map(|e| (e.repo_id, e.namespace, e.name)),
135 _ => None,
136 }
137}
138
139/// `branch.renamed`: open pull requests from `?2` in repository `?1`
140/// come from `?3` now. A fork carries its change on its own default
141/// branch, so only branches of the repository itself are named.
142const BRANCH_RENAMED: &str = "UPDATE pulls SET source_branch = ?3
143 WHERE repo_id = ?1 AND source_branch = ?2 AND fork_repo_id IS NULL
144 AND status IN ('draft', 'open')";
145
146/// `branch.renamed`: open pull requests into `?2` merge into `?3` now.
147/// Those into the default branch name none, and follow it as they are.
148const BASE_RENAMED: &str = "UPDATE pulls SET base_branch = ?3
149 WHERE repo_id = ?1 AND base_branch = ?2 AND status IN ('draft', 'open')";
150
151impl Work {
152 /// Whether work may start on the repository: neither archived nor
153 /// deleted. When repos cannot say, it is taken as active, and the
154 /// repos calls that follow (which hide deleted repositories) decide.
155 pub(crate) async fn repo_active(&self, repo_id: &str) -> Result<bool> {
156 let status: Result<RepoStatus> = g1t_kit::call(
157 &self.repos,
158 "status_by_id",
159 &StatusByIdArgs {
160 id: repo_id.to_owned(),
161 },
162 )
163 .await;
164 Ok(match status {
165 Ok(status) => status.active(),
166 Err(error) => {
167 worker::console_error!("status_by_id {repo_id}: {error}");
168 true
169 }
170 })
171 }
172
173 /// See [`RunsInRepoArgs`].
174 pub(crate) async fn runs_in_repo(&self, a: RunsInRepoArgs) -> Result<Vec<RepoRun>> {
175 let hour_ago = rfc3339(now_ms().saturating_sub(60 * 60 * 1000));
176 self.db
177 .prepare(
178 "SELECT id AS run_id, sandbox, kind, status, pull_id FROM agent_runs
179 WHERE repo_id = ?1 AND (status IN ('queued', 'running')
180 OR (status = 'stopped' AND step = ?2 AND finished_at >= ?3))
181 ORDER BY created_at LIMIT 200",
182 )
183 .bind(&[a.repo_id.as_str().into(), STOPPED_STEP.into(), hour_ago.as_str().into()])?
184 .all()
185 .await?
186 .results::<RepoRun>()
187 }
188
189 /// `repo.deleted` and `repo.archived`: its agent runs stop (the runner
190 /// stops their sandboxes, see [`RunsInRepoArgs`]) and runs waiting for
191 /// a slot in it are dropped. Rows are kept, for a restore.
192 async fn stop_runs_in(&self, repo_id: &str, namespace: &str, name: &str) -> Result<()> {
193 let now = rfc3339(now_ms());
194 let mut batch = vec![self
195 .db
196 .prepare(STOP_RUNS)
197 .bind(&[STOPPED_STEP.into(), now.as_str().into(), repo_id.into()])?];
198 if !namespace.is_empty() && !name.is_empty() {
199 for sql in DROP_WAITS {
200 batch.push(self.db.prepare(*sql).bind(&[namespace.into(), name.into()])?);
201 }
202 }
203 self.db.batch(batch).await?;
204 Ok(())
205 }
206
207 /// `repo.purged`, `repo.deleted`, `repo.archived` and `branch.renamed`.
208 /// Says whether `event` was one this handles completely.
209 pub(crate) async fn on_retired(&self, event: &Event) -> Result<bool> {
210 if g1t_kit::lifecycle::on_purged(&self.db, event, PURGED).await? {
211 return Ok(true);
212 }
213 if let Some((repo_id, namespace, name)) = stopping(event) {
214 self.stop_runs_in(&repo_id, &namespace, &name).await?;
215 return Ok(true);
216 }
217 if event.kind != "branch.renamed" {
218 return Ok(false);
219 }
220 let Ok(renamed) = serde_json::from_value::<BranchRenamed>(event.data.clone()) else {
221 worker::console_error!("branch.renamed {} could not be read", event.id);
222 return Ok(true);
223 };
224 if renamed.from == renamed.to {
225 return Ok(true);
226 }
227 let names = [
228 renamed.repo_id.as_str().into(),
229 renamed.from.as_str().into(),
230 renamed.to.as_str().into(),
231 ];
232 self.db
233 .batch(vec![
234 self.db.prepare(BRANCH_RENAMED).bind(&names)?,
235 self.db.prepare(BASE_RENAMED).bind(&names)?,
236 ])
237 .await?;
238 Ok(true)
239 }
240}
241
242#[cfg(test)]
243mod tests {
244 use super::*;
245
246 fn repo(archived_at: Option<&str>) -> Repo {
247 Repo {
248 id: "rep_1".into(),
249 namespace: "acme".into(),
250 name: "web".into(),
251 description: None,
252 is_private: false,
253 owner_id: "usr_1".into(),
254 default_branch: "main".into(),
255 fork_of: None,
256 protected: false,
257 created_at: "2026-10-05T00:00:00Z".into(),
258 topics: Vec::new(),
259 website: None,
260 archived_at: archived_at.map(str::to_owned),
261 }
262 }
263
264 #[test]
265 fn an_archived_repository_refuses_changes() {
266 assert!(matches!(writable(&repo(None)), Outcome::Ok(())));
267 match writable(&repo(Some("2026-10-05T00:00:00Z"))) {
268 Outcome::Fail(failure) => {
269 assert_eq!(failure.code, FailureCode::Forbidden);
270 assert!(failure.message.contains("acme/web is archived"));
271 }
272 Outcome::Ok(()) => panic!("an archived repository was writable"),
273 }
274 }
275
276 #[test]
277 fn purging_takes_only_the_repository_id() {
278 for sql in PURGED {
279 assert_eq!(g1t_kit::transfer::parameters(sql), 1, "{sql}");
280 }
281 // Rows kept by pull request go before the pull requests do.
282 let pulls = PURGED.iter().position(|sql| sql.starts_with("DELETE FROM pulls")).unwrap();
283 for table in ["session_entries", "check_runs", "review_runs", "agent_messages"] {
284 let at = PURGED.iter().position(|sql| sql.contains(&format!("FROM {table} "))).unwrap();
285 assert!(at < pulls, "{table}");
286 }
287 }
288
289 fn event(kind: &str, data: serde_json::Value) -> Event {
290 Event {
291 id: "evt_1".into(),
292 kind: kind.into(),
293 source: "repos".into(),
294 time: "2026-10-05T00:00:00Z".into(),
295 repo_id: Some("rep_1".into()),
296 actor: None,
297 data,
298 }
299 }
300
301 #[test]
302 fn deleting_or_archiving_stops_runs_and_unarchiving_does_not() {
303 let named = Some(("rep_1".to_owned(), "acme".to_owned(), "web".to_owned()));
304 let data = serde_json::json!({ "repoId": "rep_1", "namespace": "acme", "name": "web", "archived": true });
305 assert_eq!(stopping(&event("repo.deleted", data.clone())), named);
306 assert_eq!(stopping(&event("repo.archived", data)), named);
307 let unarchived = serde_json::json!({ "repoId": "rep_1", "namespace": "acme", "name": "web", "archived": false });
308 assert_eq!(stopping(&event("repo.unarchived", unarchived.clone())), None);
309 assert_eq!(stopping(&event("repo.archived", unarchived)), None);
310 assert_eq!(STOP_RUNS.matches('?').count(), 4);
311 for sql in DROP_WAITS {
312 assert_eq!(g1t_kit::transfer::parameters(sql), 2, "{sql}");
313 }
314 }
315
316 #[test]
317 fn waiting_runs_follow_with_the_names_they_bind() {
318 for sql in WAITS_MOVED {
319 assert_eq!(g1t_kit::transfer::parameters(sql), 7, "{sql}");
320 }
321 assert_eq!(g1t_kit::transfer::parameters(BRANCH_RENAMED), 3);
322 }
323}