Skip to content

g1t/services/actions/src/lib.rs

306 lines13,358 bytesCodeBlame

Pick any line to see why it is the way it is: the commit, the pull request and issue it came from, and what the agent was thinking.

GitHub Actions on g1t, part two: running workflows1//! The actions service: a repository's GitHub Actions workflows, run on
2//! g1t as they are. See `g1t_contracts::actions` for the methods and
3//! `g1t_actions` for how workflows, expressions and filters are read.
4//!
5//! - [`sync`] reads workflow files, at the default branch for the list and
6//! at an event's own commit for its runs.
7//! - [`trigger`] turns events, schedules and manual runs into runs.
8//! - [`plan`] moves a run's jobs along: each waits for the jobs it needs,
9//! is skipped or expanded into its matrix, queued, started in a sandbox
10//! when the workspace has room, and finished by the sandbox's report.
11//! - [`payload`] builds the webhook-shaped `github.event`.
12//! - [`settings`] keeps secrets and variables.
Fast pages, required checks on the branch, self-hosted runners, honest incidents13//! - [`cache`] lists `actions/cache` entries, which the API keeps in R2.
14//! - [`runners`] keeps self-hosted runners, hands them jobs (and agent
15//! work from the runner service) when they ask, and hears back.
GitHub Actions on g1t, part two: running workflows16//!
17//! The service acts as the repository's workspace: it reads what the
18//! workspace can read, and a job's `GITHUB_TOKEN` is a short-lived token of
19//! the workspace's.
20
Fast pages, required checks on the branch, self-hosted runners, honest incidents21mod cache;
GitHub Actions on g1t, part two: running workflows22mod payload;
23mod plan;
Agents and memory, checks and conflicts, profiles, slug renames, custom domains24mod rename;
Fast pages, required checks on the branch, self-hosted runners, honest incidents25mod runners;
GitHub Actions on g1t, part two: running workflows26mod settings;
27mod sync;
28mod trigger;
29mod views;
30
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look31use g1t_contracts::access::{self, Capability};
GitHub Actions on g1t, part two: running workflows32use g1t_contracts::events::Event;
33use g1t_contracts::identity::{SlugArgs, Workspace};
34use g1t_contracts::repos::{GetArgs, GetByIdArgs, Repo, RepoPath};
Workspace names and icons, and a component kit for every control35use g1t_contracts::{FailureCode, Membership, Outcome, PrincipalKind, User, Viewer};
GitHub Actions on g1t, part two: running workflows36use g1t_kit::{args, reply, rpc_method};
37use g1t_secrets::Sealer;
38use serde::Deserialize;
39use serde_json::Value;
40use worker::wasm_bindgen::JsValue;
41use worker::{Context, D1Database, Env, Fetcher, MessageBatch, MessageExt, Request, Response, Result, ScheduleContext, ScheduledEvent, event};
42
43/// The most workflow files read from a repository.
44pub const MAX_WORKFLOWS: usize = 50;
45/// Jobs one workspace may have running at once; the rest wait their turn.
46pub const RUNNING_PER_WORKSPACE: u32 = 4;
47/// The longest a job may run, whatever its `timeout-minutes`.
48pub const MAX_TIMEOUT_MINUTES: u32 = 60;
Fast pages, required checks on the branch, self-hosted runners, honest incidents49/// The longest a job on a self-hosted runner may run: the machine is the
50/// workspace's own, and its time costs nothing.
51pub const SELF_HOSTED_MAX_TIMEOUT_MINUTES: u32 = 24 * 60;
GitHub Actions on g1t, part two: running workflows52/// A running job that has said nothing for this long is taken as lost.
53pub const SILENT_MS: u64 = 10 * 60 * 1000;
54pub const SITE: &str = "https://g1t.sh";
55pub const API: &str = "https://api.g1t.sh";
56
57#[derive(Deserialize)]
58struct Count {
59 n: u32,
60}
61
62pub fn optional(value: Option<&str>) -> JsValue {
63 value.map_or(JsValue::NULL, JsValue::from)
64}
65
66pub fn fail<T>(code: FailureCode, message: impl Into<String>) -> Outcome<T> {
67 Outcome::fail(code, message)
68}
69
70/// `owner/name` as a path.
71pub fn repo_path(full_name: &str) -> RepoPath {
72 let (namespace, name) = full_name.split_once('/').unwrap_or((full_name, ""));
73 RepoPath {
74 namespace: namespace.to_owned(),
75 name: name.to_owned(),
76 }
77}
78
79pub struct Actions {
80 db: D1Database,
81 repos: Fetcher,
82 work: Fetcher,
83 identity: Fetcher,
84 runner: Fetcher,
Actions: workflow_run, workflow.completed, artifacts on the run page, Node 2485 events: Fetcher,
Projects: what a workspace builds and runs, first on every page86 /// Projects: a repository's secrets and variables belong to its project.
87 projects: Fetcher,
Fast pages, required checks on the branch, self-hosted runners, honest incidents88 /// Billing: self-hosted runners' time, recorded at $0, and the
89 /// cache's storage.
90 billing: Fetcher,
Merge branch 'main' into worktree-agent-a69aeabc4b0deeb9791 /// Deployments: a job with an `environment:` deploys to it, and its
92 /// run's deployment is recorded there (plan.rs `report_deployment`).
93 deployments: Fetcher,
Fast pages, required checks on the branch, self-hosted runners, honest incidents94 /// Where the API keeps cache entries, for deleting evicted ones.
95 cache: Option<worker::Bucket>,
GitHub Actions on g1t, part two: running workflows96 /// Seals secrets; absent until `ACTIONS_KEY` is set, when secrets
97 /// cannot be saved.
98 sealer: Option<Sealer>,
99}
100
101impl Actions {
102 fn new(env: &Env) -> Result<Self> {
103 Ok(Actions {
104 db: env.d1("DB")?,
105 repos: env.service("REPOS")?,
106 work: env.service("WORK")?,
107 identity: env.service("IDENTITY")?,
108 runner: env.service("RUNNER")?,
Actions: workflow_run, workflow.completed, artifacts on the run page, Node 24109 events: env.service("EVENTS")?,
Projects: what a workspace builds and runs, first on every page110 projects: env.service("PROJECTS")?,
Fast pages, required checks on the branch, self-hosted runners, honest incidents111 billing: env.service("BILLING")?,
Merge branch 'main' into worktree-agent-a69aeabc4b0deeb97112 deployments: env.service("DEPLOYMENTS")?,
Fast pages, required checks on the branch, self-hosted runners, honest incidents113 cache: env.bucket("ACTIONS_CACHE").ok(),
GitHub Actions on g1t, part two: running workflows114 sealer: env.secret("ACTIONS_KEY").ok().and_then(|key| Sealer::new(&key.to_string())),
115 })
116 }
117
118 /// The workspace itself, as the service acts.
119 async fn workspace_actor(&self, slug: &str) -> Result<Option<User>> {
120 let workspace: Option<Workspace> = g1t_kit::call(&self.identity, "get_workspace", &SlugArgs { slug: slug.to_owned() }).await?;
121 Ok(workspace.map(|workspace| User {
122 id: workspace.id,
123 username: workspace.slug.clone(),
124 kind: PrincipalKind::Workspace,
125 verified: true,
Workspace names and icons, and a component kit for every control126 workspaces: vec![Membership::member(workspace.slug)],
127 ..User::default()
GitHub Actions on g1t, part two: running workflows128 }))
129 }
130
131 /// The repository, if the viewer may see it and it is not a pull
132 /// request's working copy.
133 async fn visible_repo(&self, path: &RepoPath, viewer: &Viewer) -> Result<Option<Repo>> {
134 let found: Outcome<Repo> = g1t_kit::call(
135 &self.repos,
136 "get",
137 &GetArgs {
138 path: path.clone(),
139 viewer: viewer.clone(),
140 },
141 )
142 .await?;
143 Ok(found.into_result().ok().filter(|repo| repo.fork_of.is_none()))
144 }
145
146 /// A repository by id, as its workspace sees it.
147 async fn repo_by_id(&self, id: &str) -> Result<Option<(Repo, User)>> {
148 let path: Option<RepoPath> = g1t_kit::call(&self.repos, "path_by_id", &g1t_contracts::repos::PathByIdArgs { id: id.to_owned() }).await?;
149 let Some(path) = path else { return Ok(None) };
150 let Some(actor) = self.workspace_actor(&path.namespace).await? else {
151 return Ok(None);
152 };
153 let found: Outcome<Repo> = g1t_kit::call(
154 &self.repos,
155 "get_by_id",
156 &GetByIdArgs {
157 id: id.to_owned(),
158 viewer: Some(actor.clone()),
159 },
160 )
161 .await?;
162 Ok(found.into_result().ok().filter(|repo| repo.fork_of.is_none()).map(|repo| (repo, actor)))
163 }
164
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look165 /// The repository at `path`, when `actor` may do `capability` in it:
166 /// not found when they cannot read it, forbidden when their role falls
167 /// short. Agents never may: people and tokens run and change workflows.
168 async fn may(&self, actor: &User, path: &RepoPath, capability: Capability) -> Result<Outcome<Repo>> {
169 if actor.kind == PrincipalKind::Agent {
170 return Ok(fail(FailureCode::Forbidden, "An agent cannot do that. Ask a person."));
171 }
172 let Some(repo) = self.visible_repo(path, &Some(actor.clone())).await? else {
173 return Ok(fail(FailureCode::NotFound, "There is no such repository."));
174 };
175 if !access::can(Some(actor), &repo, capability) {
176 return Ok(fail(
177 FailureCode::Forbidden,
178 access::needs(capability, &format!("{}/{}", repo.namespace, repo.name)),
179 ));
180 }
181 Ok(Outcome::Ok(repo))
GitHub Actions on g1t, part two: running workflows182 }
183}
184
185/// Unwraps an `Outcome`, or returns its failure from the enclosing method.
186#[macro_export]
187macro_rules! check {
188 ($outcome:expr) => {
189 match $outcome {
190 g1t_contracts::Outcome::Ok(value) => value,
191 g1t_contracts::Outcome::Fail(refused) => return Ok(g1t_contracts::Outcome::Fail(refused)),
192 }
193 };
194}
195
196#[event(fetch)]
197async fn fetch(mut request: Request, env: Env, _ctx: Context) -> Result<Response> {
198 let Some(method) = rpc_method(&request) else {
199 return Response::error("Not found", 404);
200 };
201 let body: Value = request.json().await?;
202 let service = Actions::new(&env)?;
203 match method.as_str() {
204 "workflows" => reply(&service.workflows(args(body)?).await?),
205 "runs" => reply(&service.runs(args(body)?).await?),
206 "run" => reply(&service.run(args(body)?).await?),
207 "logs" => reply(&service.logs(args(body)?).await?),
208 "dispatch" => reply(&service.dispatch(args(body)?).await?),
Sidebar: the panels really slide209 "merge_group" => reply(&service.merge_group(args(body)?).await?),
GitHub Actions on g1t, part two: running workflows210 "cancel" => reply(&service.cancel(args(body)?).await?),
211 "rerun" => reply(&service.rerun(args(body)?).await?),
212 "set_workflow_enabled" => reply(&service.set_workflow_enabled(args(body)?).await?),
213 "settings" => reply(&service.settings(args(body)?).await?),
214 "set_setting" => reply(&service.set_setting(args(body)?).await?),
215 "delete_setting" => reply(&service.delete_setting(args(body)?).await?),
Secrets and variables: one list, rows per environment, for workflows and deployments216 "resolve_settings" => reply(&service.resolve_settings(args(body)?).await?),
GitHub Actions on g1t, part two: running workflows217 "job_spec" => reply(&service.job_spec(args(body)?).await?),
A repository has its own sidebar, as settings do218 "job_auth" => reply(&service.job_auth(args(body)?).await?),
Merge checks: statuses and check runs on every commit219 "check_runs" => reply(&service.check_runs(args(body)?).await?),
GitHub Actions on g1t, part two: running workflows220 "job_report" => reply(&service.job_report(args(body)?).await?),
Fast pages, required checks on the branch, self-hosted runners, honest incidents221 // actions/cache, through the API with the job's token.
222 "cache_lookup" => reply(&service.cache_lookup(args(body)?).await?),
223 "cache_reserve" => reply(&service.cache_reserve(args(body)?).await?),
224 "cache_commit" => reply(&service.cache_commit(args(body)?).await?),
225 "cache_abort" => reply(&service.cache_abort(args(body)?).await?),
226 // Self-hosted runners: people's side.
227 "runners" => reply(&service.runners(args(body)?).await?),
228 "create_registration_token" => reply(&service.create_registration_token(args(body)?).await?),
229 "remove_runner" => reply(&service.remove_runner(args(body)?).await?),
230 "runner_groups" => reply(&service.runner_groups(args(body)?).await?),
231 "set_runner_group" => reply(&service.set_runner_group(args(body)?).await?),
232 "delete_runner_group" => reply(&service.delete_runner_group(args(body)?).await?),
233 "runner_settings" => reply(&service.runner_settings(args(body)?).await?),
234 "set_runner_settings" => reply(&service.set_runner_settings(args(body)?).await?),
235 // The runner's own side, through the API with its credential.
236 "runner_register" => reply(&service.runner_register(args(body)?).await?),
237 "runner_poll" => reply(&service.runner_poll(args(body)?).await?),
238 "runner_finished" => reply(&service.runner_finished(args(body)?).await?),
239 "runner_remove_self" => reply(&service.runner_remove_self(args(body)?).await?),
240 // Agent work, from the runner service.
241 "runner_route" => reply(&service.runner_route(args(body)?).await?),
242 "stuck_jobs" => reply(&service.stuck_jobs(args(body)?).await?),
243 "enqueue_task" => reply(&service.enqueue_task(args(body)?).await?),
244 "cancel_task" => reply(&service.cancel_task(args(body)?).await?),
GitHub Actions on g1t, part two: running workflows245 _ => Response::error("Unknown method", 404),
246 }
247}
248
249/// Events from the bus, on this service's own queue.
250#[event(queue)]
251async fn queue(batch: MessageBatch<Event>, env: Env, _ctx: Context) -> Result<()> {
252 let service = Actions::new(&env)?;
253 for message in batch.messages()? {
Agents and memory, checks and conflicts, profiles, slug renames, custom domains254 // A workspace renamed: its rows move to the slug it has now.
255 if g1t_kit::rename::on_event(&env, &env.d1("DB")?, message.body(), rename::STATEMENTS).await? {
256 message.ack();
257 continue;
258 }
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look259 // A repository renamed or transferred: its rows follow its new path.
260 if g1t_kit::transfer::on_event(&env, &env.d1("DB")?, message.body(), rename::TRANSFERRED).await? {
261 message.ack();
262 continue;
263 }
264 // A workspace deleted: what it kept for itself goes.
265 if g1t_kit::deleted::on_event(&env.d1("DB")?, message.body(), rename::DELETED).await? {
266 message.ack();
267 continue;
268 }
269 // A repository purged: every row kept for it goes.
270 if g1t_kit::lifecycle::on_purged(&env.d1("DB")?, message.body(), rename::PURGED).await? {
271 message.ack();
272 continue;
273 }
274 // A repository deleted or archived: its runs stop.
275 if let Some(repo_id) = plan::stops_runs(message.body()) {
276 if let Err(error) = service.stop_runs(&repo_id).await {
277 worker::console_error!("actions: event {} failed: {error}", message.body().id);
278 message.retry();
279 continue;
280 }
281 message.ack();
282 continue;
283 }
GitHub Actions on g1t, part two: running workflows284 if let Err(error) = service.on_event(message.body()).await {
285 worker::console_error!("actions: event {} failed: {error}", message.body().id);
286 message.retry();
287 continue;
288 }
289 message.ack();
290 }
291 Ok(())
292}
293
294/// Every minute: schedules that fire, jobs waiting for room, and jobs
295/// whose sandbox went quiet.
296#[event(scheduled)]
297async fn scheduled(_event: ScheduledEvent, env: Env, _ctx: ScheduleContext) {
298 match Actions::new(&env) {
299 Ok(service) => {
300 if let Err(error) = service.on_minute(g1t_kit::now_ms()).await {
301 worker::console_error!("actions: the sweep failed: {error}");
302 }
303 }
304 Err(error) => worker::console_error!("actions: could not start: {error}"),
305 }
306}

This file's history is long; its oldest lines are credited to the oldest commit read.