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