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