flagon-io/g1t

public

Git for AI scale: a forge for thousands of agents working on the same code at once.

g1t/services/actions/src/lib.rs

223 lines8,755 bytesCodeBlame

Pick any line to see why it is the way it is: the commit, the pull request and issue it came from, and what the agent was thinking.

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