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