g1t/services/actions/src/lib.rs

216 lines8,403 bytesCodeBlame
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//!
14//! The service acts as the repository's workspace: it reads what the
15//! workspace can read, and a job's `GITHUB_TOKEN` is a short-lived token of
16//! the workspace's.
17
18mod payload;
19mod plan;
20mod settings;
21mod sync;
22mod trigger;
23mod views;
24
25use g1t_contracts::events::Event;
26use g1t_contracts::identity::{SlugArgs, Workspace};
27use g1t_contracts::repos::{GetArgs, GetByIdArgs, Repo, RepoPath};
28use g1t_contracts::{FailureCode, Membership, Outcome, PrincipalKind, Role, User, Viewer};
29use g1t_kit::{args, reply, rpc_method};
30use g1t_secrets::Sealer;
31use serde::Deserialize;
32use serde_json::Value;
33use worker::wasm_bindgen::JsValue;
34use worker::{Context, D1Database, Env, Fetcher, MessageBatch, MessageExt, Request, Response, Result, ScheduleContext, ScheduledEvent, event};
35
36/// The most workflow files read from a repository.
37pub const MAX_WORKFLOWS: usize = 50;
38/// Jobs one workspace may have running at once; the rest wait their turn.
39pub const RUNNING_PER_WORKSPACE: u32 = 4;
40/// The longest a job may run, whatever its `timeout-minutes`.
41pub const MAX_TIMEOUT_MINUTES: u32 = 60;
42/// A running job that has said nothing for this long is taken as lost.
43pub const SILENT_MS: u64 = 10 * 60 * 1000;
44pub const SITE: &str = "https://g1t.sh";
45pub const API: &str = "https://api.g1t.sh";
46
47#[derive(Deserialize)]
48struct Count {
49 n: u32,
50}
51
52pub fn optional(value: Option<&str>) -> JsValue {
53 value.map_or(JsValue::NULL, JsValue::from)
54}
55
56pub fn fail<T>(code: FailureCode, message: impl Into<String>) -> Outcome<T> {
57 Outcome::fail(code, message)
58}
59
60/// `owner/name` as a path.
61pub fn repo_path(full_name: &str) -> RepoPath {
62 let (namespace, name) = full_name.split_once('/').unwrap_or((full_name, ""));
63 RepoPath {
64 namespace: namespace.to_owned(),
65 name: name.to_owned(),
66 }
67}
68
69pub struct Actions {
70 db: D1Database,
71 repos: Fetcher,
72 work: Fetcher,
73 identity: Fetcher,
74 runner: Fetcher,
75 events: Fetcher,
76 /// Seals secrets; absent until `ACTIONS_KEY` is set, when secrets
77 /// cannot be saved.
78 sealer: Option<Sealer>,
79}
80
81impl Actions {
82 fn new(env: &Env) -> Result<Self> {
83 Ok(Actions {
84 db: env.d1("DB")?,
85 repos: env.service("REPOS")?,
86 work: env.service("WORK")?,
87 identity: env.service("IDENTITY")?,
88 runner: env.service("RUNNER")?,
89 events: env.service("EVENTS")?,
90 sealer: env.secret("ACTIONS_KEY").ok().and_then(|key| Sealer::new(&key.to_string())),
91 })
92 }
93
94 /// The workspace itself, as the service acts.
95 async fn workspace_actor(&self, slug: &str) -> Result<Option<User>> {
96 let workspace: Option<Workspace> = g1t_kit::call(&self.identity, "get_workspace", &SlugArgs { slug: slug.to_owned() }).await?;
97 Ok(workspace.map(|workspace| User {
98 id: workspace.id,
99 username: workspace.slug.clone(),
100 kind: PrincipalKind::Workspace,
101 verified: true,
102 workspaces: vec![Membership {
103 slug: workspace.slug,
104 role: Role::Member,
105 }],
106 }))
107 }
108
109 /// The repository, if the viewer may see it and it is not a pull
110 /// request's working copy.
111 async fn visible_repo(&self, path: &RepoPath, viewer: &Viewer) -> Result<Option<Repo>> {
112 let found: Outcome<Repo> = g1t_kit::call(
113 &self.repos,
114 "get",
115 &GetArgs {
116 path: path.clone(),
117 viewer: viewer.clone(),
118 },
119 )
120 .await?;
121 Ok(found.into_result().ok().filter(|repo| repo.fork_of.is_none()))
122 }
123
124 /// A repository by id, as its workspace sees it.
125 async fn repo_by_id(&self, id: &str) -> Result<Option<(Repo, User)>> {
126 let path: Option<RepoPath> = g1t_kit::call(&self.repos, "path_by_id", &g1t_contracts::repos::PathByIdArgs { id: id.to_owned() }).await?;
127 let Some(path) = path else { return Ok(None) };
128 let Some(actor) = self.workspace_actor(&path.namespace).await? else {
129 return Ok(None);
130 };
131 let found: Outcome<Repo> = g1t_kit::call(
132 &self.repos,
133 "get_by_id",
134 &GetByIdArgs {
135 id: id.to_owned(),
136 viewer: Some(actor.clone()),
137 },
138 )
139 .await?;
140 Ok(found.into_result().ok().filter(|repo| repo.fork_of.is_none()).map(|repo| (repo, actor)))
141 }
142
143 /// Refuses anyone but a member of the repository's workspace.
144 fn member(actor: &User, repo: &RepoPath) -> Option<Outcome<()>> {
145 (actor.kind == PrincipalKind::Agent || !actor.is_member(&repo.namespace.to_lowercase()))
146 .then(|| fail(FailureCode::Forbidden, format!("Only members of {} can do that.", repo.namespace)))
147 }
148}
149
150/// Unwraps an `Outcome`, or returns its failure from the enclosing method.
151#[macro_export]
152macro_rules! check {
153 ($outcome:expr) => {
154 match $outcome {
155 g1t_contracts::Outcome::Ok(value) => value,
156 g1t_contracts::Outcome::Fail(refused) => return Ok(g1t_contracts::Outcome::Fail(refused)),
157 }
158 };
159}
160
161#[event(fetch)]
162async fn fetch(mut request: Request, env: Env, _ctx: Context) -> Result<Response> {
163 let Some(method) = rpc_method(&request) else {
164 return Response::error("Not found", 404);
165 };
166 let body: Value = request.json().await?;
167 let service = Actions::new(&env)?;
168 match method.as_str() {
169 "workflows" => reply(&service.workflows(args(body)?).await?),
170 "runs" => reply(&service.runs(args(body)?).await?),
171 "run" => reply(&service.run(args(body)?).await?),
172 "logs" => reply(&service.logs(args(body)?).await?),
173 "dispatch" => reply(&service.dispatch(args(body)?).await?),
174 "merge_group" => reply(&service.merge_group(args(body)?).await?),
175 "cancel" => reply(&service.cancel(args(body)?).await?),
176 "rerun" => reply(&service.rerun(args(body)?).await?),
177 "set_workflow_enabled" => reply(&service.set_workflow_enabled(args(body)?).await?),
178 "settings" => reply(&service.settings(args(body)?).await?),
179 "set_setting" => reply(&service.set_setting(args(body)?).await?),
180 "delete_setting" => reply(&service.delete_setting(args(body)?).await?),
181 "resolve_settings" => reply(&service.resolve_settings(args(body)?).await?),
182 "job_spec" => reply(&service.job_spec(args(body)?).await?),
183 "job_auth" => reply(&service.job_auth(args(body)?).await?),
184 "job_report" => reply(&service.job_report(args(body)?).await?),
185 _ => Response::error("Unknown method", 404),
186 }
187}
188
189/// Events from the bus, on this service's own queue.
190#[event(queue)]
191async fn queue(batch: MessageBatch<Event>, env: Env, _ctx: Context) -> Result<()> {
192 let service = Actions::new(&env)?;
193 for message in batch.messages()? {
194 if let Err(error) = service.on_event(message.body()).await {
195 worker::console_error!("actions: event {} failed: {error}", message.body().id);
196 message.retry();
197 continue;
198 }
199 message.ack();
200 }
201 Ok(())
202}
203
204/// Every minute: schedules that fire, jobs waiting for room, and jobs
205/// whose sandbox went quiet.
206#[event(scheduled)]
207async fn scheduled(_event: ScheduledEvent, env: Env, _ctx: ScheduleContext) {
208 match Actions::new(&env) {
209 Ok(service) => {
210 if let Err(error) = service.on_minute(g1t_kit::now_ms()).await {
211 worker::console_error!("actions: the sweep failed: {error}");
212 }
213 }
214 Err(error) => worker::console_error!("actions: could not start: {error}"),
215 }
216}