g1t/services/actions/src/lib.rs

211 lines8,112 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 /// Seals secrets; absent until `ACTIONS_KEY` is set, when secrets
76 /// cannot be saved.
77 sealer: Option<Sealer>,
78}
79
80impl Actions {
81 fn new(env: &Env) -> Result<Self> {
82 Ok(Actions {
83 db: env.d1("DB")?,
84 repos: env.service("REPOS")?,
85 work: env.service("WORK")?,
86 identity: env.service("IDENTITY")?,
87 runner: env.service("RUNNER")?,
88 sealer: env.secret("ACTIONS_KEY").ok().and_then(|key| Sealer::new(&key.to_string())),
89 })
90 }
91
92 /// The workspace itself, as the service acts.
93 async fn workspace_actor(&self, slug: &str) -> Result<Option<User>> {
94 let workspace: Option<Workspace> = g1t_kit::call(&self.identity, "get_workspace", &SlugArgs { slug: slug.to_owned() }).await?;
95 Ok(workspace.map(|workspace| User {
96 id: workspace.id,
97 username: workspace.slug.clone(),
98 kind: PrincipalKind::Workspace,
99 verified: true,
100 workspaces: vec![Membership {
101 slug: workspace.slug,
102 role: Role::Member,
103 }],
104 }))
105 }
106
107 /// The repository, if the viewer may see it and it is not a pull
108 /// request's working copy.
109 async fn visible_repo(&self, path: &RepoPath, viewer: &Viewer) -> Result<Option<Repo>> {
110 let found: Outcome<Repo> = g1t_kit::call(
111 &self.repos,
112 "get",
113 &GetArgs {
114 path: path.clone(),
115 viewer: viewer.clone(),
116 },
117 )
118 .await?;
119 Ok(found.into_result().ok().filter(|repo| repo.fork_of.is_none()))
120 }
121
122 /// A repository by id, as its workspace sees it.
123 async fn repo_by_id(&self, id: &str) -> Result<Option<(Repo, User)>> {
124 let path: Option<RepoPath> = g1t_kit::call(&self.repos, "path_by_id", &g1t_contracts::repos::PathByIdArgs { id: id.to_owned() }).await?;
125 let Some(path) = path else { return Ok(None) };
126 let Some(actor) = self.workspace_actor(&path.namespace).await? else {
127 return Ok(None);
128 };
129 let found: Outcome<Repo> = g1t_kit::call(
130 &self.repos,
131 "get_by_id",
132 &GetByIdArgs {
133 id: id.to_owned(),
134 viewer: Some(actor.clone()),
135 },
136 )
137 .await?;
138 Ok(found.into_result().ok().filter(|repo| repo.fork_of.is_none()).map(|repo| (repo, actor)))
139 }
140
141 /// Refuses anyone but a member of the repository's workspace.
142 fn member(actor: &User, repo: &RepoPath) -> Option<Outcome<()>> {
143 (actor.kind == PrincipalKind::Agent || !actor.is_member(&repo.namespace.to_lowercase()))
144 .then(|| fail(FailureCode::Forbidden, format!("Only members of {} can do that.", repo.namespace)))
145 }
146}
147
148/// Unwraps an `Outcome`, or returns its failure from the enclosing method.
149#[macro_export]
150macro_rules! check {
151 ($outcome:expr) => {
152 match $outcome {
153 g1t_contracts::Outcome::Ok(value) => value,
154 g1t_contracts::Outcome::Fail(refused) => return Ok(g1t_contracts::Outcome::Fail(refused)),
155 }
156 };
157}
158
159#[event(fetch)]
160async fn fetch(mut request: Request, env: Env, _ctx: Context) -> Result<Response> {
161 let Some(method) = rpc_method(&request) else {
162 return Response::error("Not found", 404);
163 };
164 let body: Value = request.json().await?;
165 let service = Actions::new(&env)?;
166 match method.as_str() {
167 "workflows" => reply(&service.workflows(args(body)?).await?),
168 "runs" => reply(&service.runs(args(body)?).await?),
169 "run" => reply(&service.run(args(body)?).await?),
170 "logs" => reply(&service.logs(args(body)?).await?),
171 "dispatch" => reply(&service.dispatch(args(body)?).await?),
172 "cancel" => reply(&service.cancel(args(body)?).await?),
173 "rerun" => reply(&service.rerun(args(body)?).await?),
174 "set_workflow_enabled" => reply(&service.set_workflow_enabled(args(body)?).await?),
175 "settings" => reply(&service.settings(args(body)?).await?),
176 "set_setting" => reply(&service.set_setting(args(body)?).await?),
177 "delete_setting" => reply(&service.delete_setting(args(body)?).await?),
178 "job_spec" => reply(&service.job_spec(args(body)?).await?),
179 "job_report" => reply(&service.job_report(args(body)?).await?),
180 _ => Response::error("Unknown method", 404),
181 }
182}
183
184/// Events from the bus, on this service's own queue.
185#[event(queue)]
186async fn queue(batch: MessageBatch<Event>, env: Env, _ctx: Context) -> Result<()> {
187 let service = Actions::new(&env)?;
188 for message in batch.messages()? {
189 if let Err(error) = service.on_event(message.body()).await {
190 worker::console_error!("actions: event {} failed: {error}", message.body().id);
191 message.retry();
192 continue;
193 }
194 message.ack();
195 }
196 Ok(())
197}
198
199/// Every minute: schedules that fire, jobs waiting for room, and jobs
200/// whose sandbox went quiet.
201#[event(scheduled)]
202async fn scheduled(_event: ScheduledEvent, env: Env, _ctx: ScheduleContext) {
203 match Actions::new(&env) {
204 Ok(service) => {
205 if let Err(error) = service.on_minute(g1t_kit::now_ms()).await {
206 worker::console_error!("actions: the sweep failed: {error}");
207 }
208 }
209 Err(error) => worker::console_error!("actions: could not start: {error}"),
210 }
211}