Skip to content
333 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//! - [`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.
16//!
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
21mod artifacts;
22mod cache;
23mod payload;
24mod plan;
25mod rename;
26pub mod runtime;
27mod runners;
28mod settings;
29mod sync;
30mod trigger;
31mod views;
32
33use g1t_contracts::access::{self, Capability};
34use g1t_contracts::events::Event;
35use g1t_contracts::identity::{SlugArgs, Workspace};
36use g1t_contracts::repos::{GetArgs, GetByIdArgs, Repo, RepoPath};
37use g1t_contracts::{FailureCode, Membership, Outcome, PrincipalKind, User, Viewer};
38use g1t_kit::{args, reply, rpc_method};
39use g1t_secrets::Sealer;
40use serde::Deserialize;
41use serde_json::Value;
42use worker::wasm_bindgen::JsValue;
43use worker::{Context, D1Database, Env, Fetcher, MessageBatch, MessageExt, Request, Response, Result, ScheduleContext, ScheduledEvent, event};
44
45/// The most workflow files read from a repository.
46pub const MAX_WORKFLOWS: usize = 50;
47/// Jobs one workspace may have running at once; the rest wait their turn.
48pub const RUNNING_PER_WORKSPACE: u32 = 4;
49/// The longest a job may run, whatever its `timeout-minutes`.
50pub const MAX_TIMEOUT_MINUTES: u32 = 60;
51/// The longest a job on a self-hosted runner may run: the machine is the
52/// workspace's own, and its time costs nothing.
53pub const SELF_HOSTED_MAX_TIMEOUT_MINUTES: u32 = 24 * 60;
54/// A running job that has said nothing for this long is taken as lost.
55pub const SILENT_MS: u64 = 10 * 60 * 1000;
56pub const SITE: &str = "https://g1t.sh";
57pub const API: &str = "https://api.g1t.sh";
58
59#[derive(Deserialize)]
60struct Count {
61 n: u32,
62}
63
64pub fn optional(value: Option<&str>) -> JsValue {
65 value.map_or(JsValue::NULL, JsValue::from)
66}
67
68pub fn fail<T>(code: FailureCode, message: impl Into<String>) -> Outcome<T> {
69 Outcome::fail(code, message)
70}
71
72/// `owner/name` as a path.
73pub fn repo_path(full_name: &str) -> RepoPath {
74 let (namespace, name) = full_name.split_once('/').unwrap_or((full_name, ""));
75 RepoPath {
76 namespace: namespace.to_owned(),
77 name: name.to_owned(),
78 }
79}
80
81pub struct Actions {
82 db: D1Database,
83 repos: Fetcher,
84 work: Fetcher,
85 identity: Fetcher,
86 runner: Fetcher,
87 events: Fetcher,
88 /// Projects: a repository's secrets and variables belong to its project.
89 projects: Fetcher,
90 /// Billing: self-hosted runners' time, recorded at $0, and the
91 /// cache's storage.
92 billing: Fetcher,
93 /// Deployments: a job with an `environment:` deploys to it, and its
94 /// run's deployment is recorded there (plan.rs `report_deployment`).
95 deployments: Fetcher,
96 /// Where the API keeps cache entries, for deleting evicted ones.
97 cache: Option<worker::Bucket>,
98 /// Seals secrets; absent until `ACTIONS_KEY` is set, when secrets
99 /// cannot be saved.
100 sealer: Option<Sealer>,
101 /// Signs the toolkit's blob links (runtime.rs), from `ACTIONS_KEY`.
102 blob_key: Option<String>,
103}
104
105impl Actions {
106 fn new(env: &Env) -> Result<Self> {
107 Ok(Actions {
108 db: env.d1("DB")?,
109 repos: env.service("REPOS")?,
110 work: env.service("WORK")?,
111 identity: env.service("IDENTITY")?,
112 runner: env.service("RUNNER")?,
113 events: env.service("EVENTS")?,
114 projects: env.service("PROJECTS")?,
115 billing: env.service("BILLING")?,
116 deployments: env.service("DEPLOYMENTS")?,
117 cache: env.bucket("ACTIONS_CACHE").ok(),
118 sealer: env.secret("ACTIONS_KEY").ok().and_then(|key| Sealer::new(&key.to_string())),
119 blob_key: env.secret("ACTIONS_KEY").ok().map(|key| runtime::blob_key(&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,
131 workspaces: vec![Membership::member(workspace.slug)],
132 ..User::default()
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
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))
187 }
188}
189
190/// Unwraps an `Outcome`, or returns its failure from the enclosing method.
191#[macro_export]
192macro_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)]
202async 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?),
214 "merge_group" => reply(&service.merge_group(args(body)?).await?),
215 "cancel" => reply(&service.cancel(args(body)?).await?),
216 "rerun" => reply(&service.rerun(args(body)?).await?),
217 "set_workflow_enabled" => reply(&service.set_workflow_enabled(args(body)?).await?),
218 "settings" => reply(&service.settings(args(body)?).await?),
219 "set_setting" => reply(&service.set_setting(args(body)?).await?),
220 "delete_setting" => reply(&service.delete_setting(args(body)?).await?),
221 "resolve_settings" => reply(&service.resolve_settings(args(body)?).await?),
222 "job_spec" => reply(&service.job_spec(args(body)?).await?),
223 "job_auth" => reply(&service.job_auth(args(body)?).await?),
224 "check_runs" => reply(&service.check_runs(args(body)?).await?),
225 "job_report" => reply(&service.job_report(args(body)?).await?),
226 // actions/cache, through the API with the job's token.
227 "cache_lookup" => reply(&service.cache_lookup(args(body)?).await?),
228 "cache_reserve" => reply(&service.cache_reserve(args(body)?).await?),
229 "cache_commit" => reply(&service.cache_commit(args(body)?).await?),
230 "cache_abort" => reply(&service.cache_abort(args(body)?).await?),
231 "cache_upload" => reply(&service.cache_upload(args(body)?).await?),
232 // Artifacts: a job's side, with its token or its runtime token.
233 "artifact_reserve" => reply(&service.artifact_reserve(args(body)?).await?),
234 "artifact_commit" => reply(&service.artifact_commit(args(body)?).await?),
235 "artifact_abort" => reply(&service.artifact_abort(args(body)?).await?),
236 "job_artifacts" => reply(&service.job_artifacts(args(body)?).await?),
237 "job_artifact" => reply(&service.job_artifact(args(body)?).await?),
238 "job_delete_artifact" => reply(&service.job_delete_artifact(args(body)?).await?),
239 // Artifacts: people's side.
240 "artifacts" => reply(&service.artifacts(args(body)?).await?),
241 "artifact" => reply(&service.artifact(args(body)?).await?),
242 "artifact_download" => reply(&service.artifact_download(args(body)?).await?),
243 "delete_artifact" => reply(&service.delete_artifact(args(body)?).await?),
244 "artifact_retention" => reply(&service.artifact_retention(args(body)?).await?),
245 // The toolkit's protocols: the runtime token, OIDC, blob links.
246 "runtime_auth" => reply(&service.runtime_auth(args(body)?).await?),
247 "oidc_claims" => reply(&service.oidc_claims(args(body)?).await?),
248 "blob_sign" => reply(&service.blob_sign(args(body)?).await?),
249 "blob_open" => reply(&service.blob_open(args(body)?).await?),
250 "blob_part" => reply(&service.blob_part(args(body)?).await?),
251 "blob_parts" => reply(&service.blob_parts(args(body)?).await?),
252 "blob_done" => reply(&service.blob_done(args(body)?).await?),
253 // Self-hosted runners: people's side.
254 "runners" => reply(&service.runners(args(body)?).await?),
255 "create_registration_token" => reply(&service.create_registration_token(args(body)?).await?),
256 "remove_runner" => reply(&service.remove_runner(args(body)?).await?),
257 "runner_groups" => reply(&service.runner_groups(args(body)?).await?),
258 "set_runner_group" => reply(&service.set_runner_group(args(body)?).await?),
259 "delete_runner_group" => reply(&service.delete_runner_group(args(body)?).await?),
260 "runner_settings" => reply(&service.runner_settings(args(body)?).await?),
261 "set_runner_settings" => reply(&service.set_runner_settings(args(body)?).await?),
262 // The runner's own side, through the API with its credential.
263 "runner_register" => reply(&service.runner_register(args(body)?).await?),
264 "runner_poll" => reply(&service.runner_poll(args(body)?).await?),
265 "runner_finished" => reply(&service.runner_finished(args(body)?).await?),
266 "runner_remove_self" => reply(&service.runner_remove_self(args(body)?).await?),
267 // Agent work, from the runner service.
268 "runner_route" => reply(&service.runner_route(args(body)?).await?),
269 "stuck_jobs" => reply(&service.stuck_jobs(args(body)?).await?),
270 "enqueue_task" => reply(&service.enqueue_task(args(body)?).await?),
271 "cancel_task" => reply(&service.cancel_task(args(body)?).await?),
272 _ => Response::error("Unknown method", 404),
273 }
274}
275
276/// Events from the bus, on this service's own queue.
277#[event(queue)]
278async fn queue(batch: MessageBatch<Event>, env: Env, _ctx: Context) -> Result<()> {
279 let service = Actions::new(&env)?;
280 for message in batch.messages()? {
281 // A workspace renamed: its rows move to the slug it has now.
282 if g1t_kit::rename::on_event(&env, &env.d1("DB")?, message.body(), rename::STATEMENTS).await? {
283 message.ack();
284 continue;
285 }
286 // A repository renamed or transferred: its rows follow its new path.
287 if g1t_kit::transfer::on_event(&env, &env.d1("DB")?, message.body(), rename::TRANSFERRED).await? {
288 message.ack();
289 continue;
290 }
291 // A workspace deleted: what it kept for itself goes.
292 if g1t_kit::deleted::on_event(&env.d1("DB")?, message.body(), rename::DELETED).await? {
293 message.ack();
294 continue;
295 }
296 // A repository purged: every row kept for it goes.
297 if g1t_kit::lifecycle::on_purged(&env.d1("DB")?, message.body(), rename::PURGED).await? {
298 message.ack();
299 continue;
300 }
301 // A repository deleted or archived: its runs stop.
302 if let Some(repo_id) = plan::stops_runs(message.body()) {
303 if let Err(error) = service.stop_runs(&repo_id).await {
304 worker::console_error!("actions: event {} failed: {error}", message.body().id);
305 message.retry();
306 continue;
307 }
308 message.ack();
309 continue;
310 }
311 if let Err(error) = service.on_event(message.body()).await {
312 worker::console_error!("actions: event {} failed: {error}", message.body().id);
313 message.retry();
314 continue;
315 }
316 message.ack();
317 }
318 Ok(())
319}
320
321/// Every minute: schedules that fire, jobs waiting for room, and jobs
322/// whose sandbox went quiet.
323#[event(scheduled)]
324async fn scheduled(_event: ScheduledEvent, env: Env, _ctx: ScheduleContext) {
325 match Actions::new(&env) {
326 Ok(service) => {
327 if let Err(error) = service.on_minute(g1t_kit::now_ms()).await {
328 worker::console_error!("actions: the sweep failed: {error}");
329 }
330 }
331 Err(error) => worker::console_error!("actions: could not start: {error}"),
332 }
333}