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.

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