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.

443 linesCodeBlameRaw
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, and [`broker`] the stand-ins
13//! jobs are given for brokered secrets.
14//! - [`protection`] keeps a repository's workflow settings and its
15//! environments' protection rules, holds jobs at those rules until they
16//! pass, and lets pull requests' runs from outside wait for approval.
17//! - [`cache`] lists `actions/cache` entries, which the API keeps in R2.
18//! - [`reach`] finds the actions and reusable workflows of other
19//! repositories on g1t, and [`registry`] resolves those from GitHub to
20//! commits and keeps their archives, for jobs to download from g1t.
21//! - [`runners`] keeps self-hosted runners, hands them jobs (and agent
22//! work from the runner service) when they ask, and hears back.
23//!
24//! The service acts as the repository's workspace: it reads what the
25//! workspace can read, and a job's `GITHUB_TOKEN` is a token of the
26//! workspace's that reaches the job's repository only, with the scopes its
27//! `permissions:` give it, revoked when the job ends.
28
29mod run_artifacts;
30mod broker;
31mod cache;
32mod limits;
33mod managed;
34mod payload;
35mod plan;
36mod protection;
37mod reach;
38mod registry;
39mod rename;
40mod retention;
41pub mod runtime;
42mod runners;
43mod settings;
44mod sync;
45mod trigger;
46mod views;
47
48use g1t_contracts::access::{self, Capability};
49use g1t_contracts::events::Event;
50use g1t_contracts::identity::{SlugArgs, Workspace};
51use g1t_contracts::repos::{GetArgs, GetByIdArgs, Repo, RepoPath};
52use g1t_contracts::{FailureCode, Membership, Outcome, PrincipalKind, User, Viewer};
53use g1t_kit::{args, reply, rpc_method};
54use g1t_secrets::Sealer;
55use serde::Deserialize;
56use serde_json::Value;
57use worker::wasm_bindgen::JsValue;
58use worker::{Context, D1Database, Env, Fetcher, MessageBatch, MessageExt, Request, Response, Result, ScheduleContext, ScheduledEvent, event};
59
60/// The most workflow files read from a repository.
61pub const MAX_WORKFLOWS: usize = 50;
62/// Jobs on g1t's own machines one workspace may always have running at
63/// once; the rest wait their turn, unless the pool has room (`has_room`).
64pub const RUNNING_PER_WORKSPACE: u32 = 4;
65/// The most one workspace may run at once while the pool has room to spare.
66pub const BURST_PER_WORKSPACE: u32 = 12;
67/// Sandboxes g1t's own machines have between them (services/runner's
68/// wrangler.jsonc: 20 standard, 10 g1t-2core, 30 g1t-4core, which every
69/// public repository's ubuntu-latest jobs run on).
70pub const HOSTED_POOL: u32 = 60;
71/// Kept free while workspaces run past their share, so another workspace's
72/// first jobs still start at once.
73pub const POOL_HEADROOM: u32 = 8;
74
75/// Whether a workspace running `in_workspace` jobs on g1t's machines may
76/// start another while `in_pool` run across every workspace: always within
77/// its share, and past it, up to the burst, while the pool keeps its
78/// headroom.
79pub fn has_room(in_workspace: u32, in_pool: u32) -> bool {
80 in_workspace < RUNNING_PER_WORKSPACE
81 || (in_workspace < BURST_PER_WORKSPACE && in_pool + POOL_HEADROOM < HOSTED_POOL)
82}
83/// The longest a job on g1t's own machines may run, whatever its
84/// `timeout-minutes`.
85pub const MAX_TIMEOUT_MINUTES: u32 = g1t_actions::workflow::HOSTED_MAX_TIMEOUT_MINUTES;
86/// The longest a job on a self-hosted runner may run: the machine is the
87/// workspace's own, and its time costs nothing.
88pub const SELF_HOSTED_MAX_TIMEOUT_MINUTES: u32 = 24 * 60;
89/// A running job that has said nothing for this long is taken as lost.
90pub const SILENT_MS: u64 = 10 * 60 * 1000;
91/// Schedules pause in a repository that has had no push for this long; the
92/// next push resumes them.
93pub const SCHEDULE_IDLE_MS: u64 = 60 * 24 * 60 * 60 * 1000;
94/// How long a workflow's schedule waits after billing refused to start a
95/// job of one of its scheduled runs, before it tries again.
96pub const SCHEDULE_REFUSED_MS: u64 = 60 * 60 * 1000;
97pub const SITE: &str = "https://g1t.sh";
98pub const API: &str = "https://api.g1t.sh";
99
100#[derive(Deserialize)]
101struct Count {
102 n: u32,
103}
104
105pub fn optional(value: Option<&str>) -> JsValue {
106 value.map_or(JsValue::NULL, JsValue::from)
107}
108
109pub fn fail<T>(code: FailureCode, message: impl Into<String>) -> Outcome<T> {
110 Outcome::fail(code, message)
111}
112
113/// `owner/name` as a path.
114pub fn repo_path(full_name: &str) -> RepoPath {
115 let (namespace, name) = full_name.split_once('/').unwrap_or((full_name, ""));
116 RepoPath {
117 namespace: namespace.to_owned(),
118 name: name.to_owned(),
119 }
120}
121
122pub struct Actions {
123 db: D1Database,
124 repos: Fetcher,
125 work: Fetcher,
126 identity: Fetcher,
127 runner: Fetcher,
128 events: Fetcher,
129 /// Projects: a repository's secrets and variables belong to its project.
130 projects: Fetcher,
131 /// Billing: self-hosted runners' time, recorded at $0, and the
132 /// cache's storage.
133 billing: Fetcher,
134 /// Deployments: a job with an `environment:` deploys to it, and its
135 /// run's deployment is recorded there (plan.rs `report_deployment`).
136 deployments: Fetcher,
137 /// Notify, optional: pages open on a repository hear its runs' jobs
138 /// start and finish (plan.rs `tell_live`). Without it they catch up
139 /// on their own.
140 notify: Option<Fetcher>,
141 /// Where the API keeps cache entries, for deleting evicted ones.
142 cache: Option<worker::Bucket>,
143 /// Seals secrets; absent until `ACTIONS_KEY` is set, when secrets
144 /// cannot be saved.
145 sealer: Option<Sealer>,
146 /// Signs the toolkit's blob links (runtime.rs), from `ACTIONS_KEY`.
147 blob_key: Option<String>,
148 /// Log retention and free workspaces' caps, from wrangler vars (limits.rs).
149 limits: limits::Limits,
150 /// Whether repositories' Actions are on, read once per request.
151 actions_on: protection::ActionsOn,
152}
153
154impl Actions {
155 fn new(env: &Env) -> Result<Self> {
156 Ok(Actions {
157 db: env.d1("DB")?,
158 repos: env.service("REPOS")?,
159 work: env.service("WORK")?,
160 identity: env.service("IDENTITY")?,
161 runner: env.service("RUNNER")?,
162 events: env.service("EVENTS")?,
163 projects: env.service("PROJECTS")?,
164 billing: env.service("BILLING")?,
165 deployments: env.service("DEPLOYMENTS")?,
166 notify: env.service("NOTIFY").ok(),
167 cache: env.bucket("ACTIONS_CACHE").ok(),
168 sealer: env.secret("ACTIONS_KEY").ok().and_then(|key| Sealer::new(&key.to_string())),
169 blob_key: env.secret("ACTIONS_KEY").ok().map(|key| runtime::blob_key(&key.to_string())),
170 limits: limits::Limits::from_env(env),
171 actions_on: protection::ActionsOn::default(),
172 })
173 }
174
175 /// The workspace itself, as the service acts.
176 async fn workspace_actor(&self, slug: &str) -> Result<Option<User>> {
177 let workspace: Option<Workspace> = g1t_kit::call(&self.identity, "get_workspace", &SlugArgs { slug: slug.to_owned() }).await?;
178 Ok(workspace.map(|workspace| User {
179 id: workspace.id,
180 username: workspace.slug.clone(),
181 kind: PrincipalKind::Workspace,
182 verified: true,
183 workspaces: vec![Membership::member(workspace.slug)],
184 ..User::default()
185 }))
186 }
187
188 /// The repository, if the viewer may see it and it is not a pull
189 /// request's working copy.
190 async fn visible_repo(&self, path: &RepoPath, viewer: &Viewer) -> Result<Option<Repo>> {
191 let found: Outcome<Repo> = g1t_kit::call(
192 &self.repos,
193 "get",
194 &GetArgs {
195 path: path.clone(),
196 viewer: viewer.clone(),
197 },
198 )
199 .await?;
200 Ok(found.into_result().ok().filter(|repo| repo.fork_of.is_none()))
201 }
202
203 /// A repository by id, as its workspace sees it.
204 async fn repo_by_id(&self, id: &str) -> Result<Option<(Repo, User)>> {
205 let path: Option<RepoPath> = g1t_kit::call(&self.repos, "path_by_id", &g1t_contracts::repos::PathByIdArgs { id: id.to_owned() }).await?;
206 let Some(path) = path else { return Ok(None) };
207 let Some(actor) = self.workspace_actor(&path.namespace).await? else {
208 return Ok(None);
209 };
210 let found: Outcome<Repo> = g1t_kit::call(
211 &self.repos,
212 "get_by_id",
213 &GetByIdArgs {
214 id: id.to_owned(),
215 viewer: Some(actor.clone()),
216 },
217 )
218 .await?;
219 Ok(found.into_result().ok().filter(|repo| repo.fork_of.is_none()).map(|repo| (repo, actor)))
220 }
221
222 /// The repository at `path`, when `actor` may do `capability` in it:
223 /// not found when they cannot read it, forbidden when their role falls
224 /// short.
225 async fn may(&self, actor: &User, path: &RepoPath, capability: Capability) -> Result<Outcome<Repo>> {
226 let Some(repo) = self.visible_repo(path, &Some(actor.clone())).await? else {
227 return Ok(fail(FailureCode::NotFound, "There is no such repository."));
228 };
229 if !access::can(Some(actor), &repo, capability) {
230 return Ok(fail(
231 FailureCode::Forbidden,
232 access::needs(capability, &format!("{}/{}", repo.namespace, repo.name)),
233 ));
234 }
235 Ok(Outcome::Ok(repo))
236 }
237}
238
239/// Unwraps an `Outcome`, or returns its failure from the enclosing method.
240#[macro_export]
241macro_rules! check {
242 ($outcome:expr) => {
243 match $outcome {
244 g1t_contracts::Outcome::Ok(value) => value,
245 g1t_contracts::Outcome::Fail(refused) => return Ok(g1t_contracts::Outcome::Fail(refused)),
246 }
247 };
248}
249
250#[event(fetch)]
251async fn fetch(mut request: Request, env: Env, _ctx: Context) -> Result<Response> {
252 let Some(method) = rpc_method(&request) else {
253 return Response::error("Not found", 404);
254 };
255 let body: Value = request.json().await?;
256 let service = Actions::new(&env)?;
257 match method.as_str() {
258 "workflows" => reply(&service.workflows(args(body)?).await?),
259 "workflow" => reply(&service.workflow(args(body)?).await?),
260 "runs" => reply(&service.runs(args(body)?).await?),
261 "run" => reply(&service.run(args(body)?).await?),
262 "logs" => reply(&service.logs(args(body)?).await?),
263 "job_log_text" => reply(&service.job_log_text(args(body)?).await?),
264 "run_logs" => reply(&service.run_logs(args(body)?).await?),
265 "summaries" => reply(&service.summaries(args(body)?).await?),
266 "dispatch" => reply(&service.dispatch(args(body)?).await?),
267 "repository_dispatch" => reply(&service.repository_dispatch(args(body)?).await?),
268 "approve_run" => reply(&service.approve_run(args(body)?).await?),
269 "pending_deployments" => reply(&service.pending_deployments(args(body)?).await?),
270 "review_deployments" => reply(&service.review_deployments(args(body)?).await?),
271 "actions_settings" => reply(&service.actions_settings(args(body)?).await?),
272 "set_actions_settings" => reply(&service.set_actions_settings(args(body)?).await?),
273 "workspace_actions_settings" => reply(&service.workspace_actions_settings(args(body)?).await?),
274 "set_workspace_actions_settings" => reply(&service.set_workspace_actions_settings(args(body)?).await?),
275 "environments" => reply(&service.environments(args(body)?).await?),
276 "set_environment" => reply(&service.set_environment(args(body)?).await?),
277 "delete_environment" => reply(&service.delete_environment(args(body)?).await?),
278 "merge_group" => reply(&service.merge_group(args(body)?).await?),
279 "cancel" => reply(&service.cancel(args(body)?).await?),
280 "rerun" => reply(&service.rerun(args(body)?).await?),
281 "set_workflow_enabled" => reply(&service.set_workflow_enabled(args(body)?).await?),
282 "settings" => reply(&service.settings(args(body)?).await?),
283 "set_setting" => reply(&service.set_setting(args(body)?).await?),
284 "delete_setting" => reply(&service.delete_setting(args(body)?).await?),
285 "resolve_settings" => reply(&service.resolve_settings(args(body)?).await?),
286 // Managed workflows: g1t's services' side only.
287 "set_managed_workflow" => reply(&service.set_managed_workflow(args(body)?).await?),
288 "remove_managed_workflow" => reply(&service.remove_managed_workflow(args(body)?).await?),
289 "set_managed_deploy" => reply(&service.set_managed_deploy(args(body)?).await?),
290 // A workspace's managed workflows: its owners'.
291 "workspace_managed_workflows" => reply(&service.workspace_managed_workflows(args(body)?).await?),
292 "set_workspace_managed_workflow" => reply(&service.set_workspace_managed_workflow(args(body)?).await?),
293 "remove_workspace_managed_workflow" => reply(&service.remove_workspace_managed_workflow(args(body)?).await?),
294 "job_spec" => reply(&service.job_spec(args(body)?).await?),
295 "job_auth" => reply(&service.job_auth(args(body)?).await?),
296 "job_action" => reply(&service.job_action(args(body)?).await?),
297 "job_action_archive" => reply(&service.job_action_archive(args(body)?).await?),
298 "check_runs" => reply(&service.check_runs(args(body)?).await?),
299 "job_report" => reply(&service.job_report(args(body)?).await?),
300 // A running job's stand-ins for brokered secrets: the runner
301 // Worker's alone, never passed on by the API.
302 "brokered_secrets" => reply(&service.brokered_secrets(args(body)?).await?),
303 // The same for a self-hosted job's broker requests, which the
304 // runner Worker relays (`POST /actions/jobs/{job}/broker`): with
305 // the job's current token only.
306 "relayed_secrets" => reply(&service.relayed_secrets(args(body)?).await?),
307 // actions/cache, through the API with the job's token.
308 "cache_lookup" => reply(&service.cache_lookup(args(body)?).await?),
309 "cache_reserve" => reply(&service.cache_reserve(args(body)?).await?),
310 "cache_commit" => reply(&service.cache_commit(args(body)?).await?),
311 "cache_abort" => reply(&service.cache_abort(args(body)?).await?),
312 "cache_upload" => reply(&service.cache_upload(args(body)?).await?),
313 // The cache: people's side, listing what is saved and deleting it.
314 "caches" => reply(&service.caches(args(body)?).await?),
315 "cache_usage" => reply(&service.cache_usage(args(body)?).await?),
316 "delete_caches" => reply(&service.delete_caches(args(body)?).await?),
317 // Artifacts: a job's side, with its token or its runtime token.
318 "artifact_reserve" => reply(&service.artifact_reserve(args(body)?).await?),
319 "artifact_commit" => reply(&service.artifact_commit(args(body)?).await?),
320 "artifact_abort" => reply(&service.artifact_abort(args(body)?).await?),
321 "job_artifacts" => reply(&service.job_artifacts(args(body)?).await?),
322 "job_artifact" => reply(&service.job_artifact(args(body)?).await?),
323 "job_delete_artifact" => reply(&service.job_delete_artifact(args(body)?).await?),
324 // Artifacts: people's side.
325 "artifacts" => reply(&service.artifacts(args(body)?).await?),
326 "artifact" => reply(&service.artifact(args(body)?).await?),
327 "artifact_download" => reply(&service.artifact_download(args(body)?).await?),
328 "delete_artifact" => reply(&service.delete_artifact(args(body)?).await?),
329 "artifact_retention" => reply(&service.artifact_retention(args(body)?).await?),
330 // The toolkit's protocols: the runtime token, OIDC, blob links.
331 "runtime_auth" => reply(&service.runtime_auth(args(body)?).await?),
332 "oidc_claims" => reply(&service.oidc_claims(args(body)?).await?),
333 "blob_sign" => reply(&service.blob_sign(args(body)?).await?),
334 "blob_open" => reply(&service.blob_open(args(body)?).await?),
335 "blob_part" => reply(&service.blob_part(args(body)?).await?),
336 "blob_parts" => reply(&service.blob_parts(args(body)?).await?),
337 "blob_done" => reply(&service.blob_done(args(body)?).await?),
338 // Self-hosted runners: people's side.
339 "runners" => reply(&service.runners(args(body)?).await?),
340 "create_registration_token" => reply(&service.create_registration_token(args(body)?).await?),
341 "remove_runner" => reply(&service.remove_runner(args(body)?).await?),
342 // Staff only, from sudo: a workspace's runners, and removing them.
343 "admin_runners" => reply(&service.admin_runners(args(body)?).await?),
344 "admin_remove_runners" => reply(&service.admin_remove_runners(args(body)?).await?),
345 "runner_groups" => reply(&service.runner_groups(args(body)?).await?),
346 "set_runner_group" => reply(&service.set_runner_group(args(body)?).await?),
347 "delete_runner_group" => reply(&service.delete_runner_group(args(body)?).await?),
348 "runner_settings" => reply(&service.runner_settings(args(body)?).await?),
349 "set_runner_settings" => reply(&service.set_runner_settings(args(body)?).await?),
350 // The desktop app's runners, as each app says they are.
351 "report_desktop" => reply(&service.report_desktop(args(body)?).await?),
352 "desktop_runners" => reply(&service.desktop_runners(args(body)?).await?),
353 // The runner's own side, through the API with its credential.
354 "runner_register" => reply(&service.runner_register(args(body)?).await?),
355 "runner_poll" => reply(&service.runner_poll(args(body)?).await?),
356 "runner_finished" => reply(&service.runner_finished(args(body)?).await?),
357 "runner_remove_self" => reply(&service.runner_remove_self(args(body)?).await?),
358 // Agent work, from the runner service.
359 "runner_route" => reply(&service.runner_route(args(body)?).await?),
360 "stuck_jobs" => reply(&service.stuck_jobs(args(body)?).await?),
361 "runner_activity" => reply(&service.runner_activity(args(body)?).await?),
362 "enqueue_task" => reply(&service.enqueue_task(args(body)?).await?),
363 "cancel_task" => reply(&service.cancel_task(args(body)?).await?),
364 _ => Response::error("Unknown method", 404),
365 }
366}
367
368/// Events from the bus, on this service's own queue.
369#[event(queue)]
370async fn queue(batch: MessageBatch<Event>, env: Env, _ctx: Context) -> Result<()> {
371 let service = Actions::new(&env)?;
372 for message in batch.messages()? {
373 // A workspace renamed: its rows move to the slug it has now.
374 if g1t_kit::rename::on_event(&env, &env.d1("DB")?, message.body(), rename::STATEMENTS).await? {
375 message.ack();
376 continue;
377 }
378 // A repository renamed or transferred: its rows follow its new path.
379 if g1t_kit::transfer::on_event(&env, &env.d1("DB")?, message.body(), rename::TRANSFERRED).await? {
380 message.ack();
381 continue;
382 }
383 // A workspace deleted: what it kept for itself goes.
384 if g1t_kit::deleted::on_event(&env.d1("DB")?, message.body(), rename::DELETED).await? {
385 message.ack();
386 continue;
387 }
388 // A repository purged: every row kept for it goes.
389 if g1t_kit::lifecycle::on_purged(&env.d1("DB")?, message.body(), rename::PURGED).await? {
390 message.ack();
391 continue;
392 }
393 // A repository deleted or archived: its runs stop.
394 if let Some(repo_id) = plan::stops_runs(message.body()) {
395 if let Err(error) = service.stop_runs(&repo_id).await {
396 worker::console_error!("actions: event {} failed: {error}", message.body().id);
397 message.retry();
398 continue;
399 }
400 message.ack();
401 continue;
402 }
403 if let Err(error) = service.on_event(message.body()).await {
404 worker::console_error!("actions: event {} failed: {error}", message.body().id);
405 message.retry();
406 continue;
407 }
408 message.ack();
409 }
410 Ok(())
411}
412
413/// Every minute: schedules that fire, jobs waiting for room, and jobs
414/// whose sandbox went quiet.
415#[event(scheduled)]
416async fn scheduled(_event: ScheduledEvent, env: Env, _ctx: ScheduleContext) {
417 match Actions::new(&env) {
418 Ok(service) => {
419 if let Err(error) = service.on_minute(g1t_kit::now_ms()).await {
420 worker::console_error!("actions: the sweep failed: {error}");
421 }
422 }
423 Err(error) => worker::console_error!("actions: could not start: {error}"),
424 }
425}
426
427#[cfg(test)]
428mod room_tests {
429 use super::*;
430
431 #[test]
432 fn a_workspace_always_has_its_share() {
433 assert!(has_room(RUNNING_PER_WORKSPACE - 1, HOSTED_POOL));
434 assert!(!has_room(RUNNING_PER_WORKSPACE, HOSTED_POOL));
435 }
436
437 #[test]
438 fn past_its_share_a_workspace_runs_more_while_the_pool_keeps_its_headroom() {
439 assert!(has_room(RUNNING_PER_WORKSPACE, HOSTED_POOL - POOL_HEADROOM - 1));
440 assert!(!has_room(RUNNING_PER_WORKSPACE, HOSTED_POOL - POOL_HEADROOM));
441 assert!(!has_room(BURST_PER_WORKSPACE, 0));
442 }
443}