| b64e2537 Andy McCall ↶ |
1 |
|
| 2 |
|
| 3 |
|
| 4 |
|
| d23464c0 Andy McCall ↶ |
5 |
|
| b64e2537 Andy McCall ↶ |
6 |
use crate::auth::{self, Access, Role}; |
| 7 |
use crate::db::{self, accounts::Account}; |
| d23464c0 Andy McCall ↶ |
8 |
use crate::repos::{view, RepoError, RepoName}; |
| b64e2537 Andy McCall ↶ |
9 |
use crate::Shared; |
| 10 |
use axum::extract::{Path, Query, State}; |
| 11 |
use axum::http::{HeaderMap, StatusCode}; |
| d23464c0 Andy McCall ↶ |
12 |
use axum::response::{IntoResponse, Response}; |
| b64e2537 Andy McCall ↶ |
13 |
use axum::routing::{get, post}; |
| d23464c0 Andy McCall ↶ |
14 |
use axum::{Json, Router}; |
| b64e2537 Andy McCall ↶ |
15 |
use hub_api::*; |
| 16 |
use serde::Deserialize; |
| d23464c0 Andy McCall ↶ |
17 |
|
| 2e9188ca Andy McCall ↶ |
18 |
mod backups; |
| df71c789 Andy McCall ↶ |
19 |
pub mod device; |
| 166f6e9b Andy McCall |
20 |
mod drops; |
| 92a797b2 Andy McCall ↶ |
21 |
mod images; |
| ef20fdc1 Andy McCall ↶ |
22 |
mod projects; |
| 617c2840 Andy McCall ↶ |
23 |
mod reports; |
| ef20fdc1 Andy McCall ↶ |
24 |
|
| 90326c96 Andy McCall ↶ |
25 |
|
| e9bfea8e Andy McCall ↶ |
26 |
|
| 27 |
|
| 28 |
async fn version() -> Json<serde_json::Value> { |
| 29 |
Json(crate::web::home::versions()) |
| 30 |
} |
| 31 |
|
| 90326c96 Andy McCall ↶ |
32 |
async fn no_route() -> ApiError { |
| 33 |
ApiError(StatusCode::NOT_FOUND, "no such API route".into()) |
| 34 |
} |
| 35 |
|
| 17a3a84b Andy McCall ↶ |
36 |
|
| 37 |
|
| 38 |
async fn wrong_method(method: axum::http::Method, uri: axum::http::Uri) -> ApiError { |
| 39 |
ApiError(StatusCode::METHOD_NOT_ALLOWED, format!("{} is an API route, but not for {method}", uri.path())) |
| 40 |
} |
| 41 |
|
| 5533e91a Andy McCall ↶ |
42 |
|
| 43 |
|
| 44 |
pub fn router(asset_limit: usize) -> Router<Shared> { |
| d23464c0 Andy McCall ↶ |
45 |
Router::new() |
| 90326c96 Andy McCall ↶ |
46 |
.fallback(no_route) |
| 026a76d2 Andy McCall ↶ |
47 |
.route("/keyless/certify", post(crate::keyless::certify)) |
| 8aa5ef38 Andy McCall ↶ |
48 |
.route("/agents/grants", get(crate::keyless::grants_list).post(crate::keyless::grants_create)) |
| 8dcaeeb8 Andy McCall ↶ |
49 |
.route( |
| 50 |
"/repos/{owner}/{name}/terraform/state/{state}", |
| 51 |
axum::routing::any(crate::terraform::state) |
| 52 |
.layer(axum::extract::DefaultBodyLimit::max(crate::terraform::MAX_STATE_BYTES + 4096)), |
| 53 |
) |
| 67523e06 Andy McCall ↶ |
54 |
.route("/repos/{owner}/{name}/terraform/state/{state}/versions", axum::routing::get(crate::terraform::versions)) |
| 55 |
.route("/repos/{owner}/{name}/terraform/state/{state}/versions/{id}", axum::routing::get(crate::terraform::version)) |
| 56 |
.route( |
| 57 |
"/repos/{owner}/{name}/terraform/state/{state}/versions/{id}/restore", |
| 58 |
axum::routing::post(crate::terraform::restore_version), |
| 59 |
) |
| 8aa5ef38 Andy McCall ↶ |
60 |
.route("/agents/grants/{id}", axum::routing::delete(crate::keyless::grants_revoke)) |
| 42fa9554 Andy McCall ↶ |
61 |
.route("/flow/claim", post(crate::flow::claim)) |
| b6b7e4cf Andy McCall ↶ |
62 |
.route("/flow/runners/register", post(crate::flow::register)) |
| e9b9619c Andy McCall ↶ |
63 |
.route("/flow/runners/heartbeat", post(crate::flow::heartbeat)) |
| 8501fd58 Andy McCall ↶ |
64 |
.route("/flow/runner/update", get(crate::flow::runner_update).post(crate::flow::report_update)) |
| 750579ec Andy McCall ↶ |
65 |
.route("/flow/images/missing", post(images::missing).layer(axum::extract::DefaultBodyLimit::max(images::MAX_ASK_BYTES))) |
| 951aed50 Andy McCall ↶ |
66 |
.route("/flow/images/held", post(images::held)) |
| a46d15e7 Andy McCall ↶ |
67 |
.route("/flow/swarm/announce", post(crate::swarm::announce)) |
| 92a797b2 Andy McCall ↶ |
68 |
.route("/flow/images/chunks/{hash}", axum::routing::put(images::put_chunk).get(images::get_chunk)) |
| 69 |
.route( |
| 70 |
"/flow/images/{hash}", |
| 71 |
axum::routing::put(images::put_manifest).get(images::get_manifest).layer(axum::extract::DefaultBodyLimit::max(64 << 20)), |
| 72 |
) |
| 951aed50 Andy McCall ↶ |
73 |
|
| 74 |
|
| 75 |
.route("/flow/images/{hash}/held", axum::routing::put(images::put_held).layer(axum::extract::DefaultBodyLimit::max(64 << 20))) |
| 42fa9554 Andy McCall ↶ |
76 |
.route("/flow/jobs/{id}/log", post(crate::flow::log)) |
| 77 |
.route("/flow/jobs/{id}/finish", post(crate::flow::finish)) |
| 4d2e44d7 Andy McCall ↶ |
78 |
.route("/flow/jobs/{id}/decline", post(crate::flow::decline)) |
| ab4df6aa Andy McCall ↶ |
79 |
.route("/flow/jobs/{id}/release", post(crate::flow::release)) |
| a3c8288b Andy McCall ↶ |
80 |
.route( |
| e4203e14 Andy McCall ↶ |
81 |
"/flow/jobs/{id}/checkpoint", |
| 82 |
post(crate::flow::save_checkpoint) |
| 83 |
.get(crate::flow::checkpoint) |
| 84 |
.layer(axum::extract::DefaultBodyLimit::max(crate::flow::MAX_ARTIFACT_BYTES + (1 << 20))), |
| 85 |
) |
| 86 |
.route( |
| a3c8288b Andy McCall ↶ |
87 |
"/flow/jobs/{id}/artifacts/{name}", |
| 88 |
post(crate::flow::artifact).layer(axum::extract::DefaultBodyLimit::max(crate::flow::MAX_ARTIFACT_BYTES + (1 << 20))), |
| 89 |
) |
| cd437c4f Andy McCall ↶ |
90 |
.route("/flow/jobs/{id}/inputs/{index}", get(crate::flow::input)) |
| a36bab6b Andy McCall ↶ |
91 |
.route( |
| 92 |
"/flow/jobs/{id}/reports/{name}/files", |
| 93 |
post(crate::flow::report_file).layer(axum::extract::DefaultBodyLimit::max(crate::flow::MAX_ARTIFACT_BYTES + (1 << 20))), |
| 94 |
) |
| ef20fdc1 Andy McCall ↶ |
95 |
.route("/projects/{owner}", get(projects::list).post(projects::create)) |
| 96 |
.route("/projects/{owner}/{number}", get(projects::board).patch(projects::edit)) |
| 17a3a84b Andy McCall ↶ |
97 |
.route("/projects/{owner}/{number}/cards", get(projects::cards).post(projects::add_card)) |
| 456f4197 Andy McCall ↶ |
98 |
.route("/projects/{owner}/{number}/cards/move", post(projects::move_cards)) |
| 439ecd87 Andy McCall ↶ |
99 |
.route("/projects/{owner}/{number}/cards/archive", post(projects::archive_cards)) |
| 100 |
.route("/projects/{owner}/{number}/cards/{id}/restore", post(projects::restore_card)) |
| ef20fdc1 Andy McCall ↶ |
101 |
.route("/projects/{owner}/{number}/cards/{id}", axum::routing::patch(projects::move_card).delete(projects::remove_card)) |
| ecac6e8d Andy McCall ↶ |
102 |
.route("/device/code", post(device::code).delete(device::cancel)) |
| df71c789 Andy McCall ↶ |
103 |
.route("/device/token", post(device::token)) |
| b66e70b7 Andy McCall ↶ |
104 |
.route("/runners", get(runners)) |
| 105 |
.route("/runners/queue", get(runner_queue)) |
| 106 |
.route("/runners/{id}/jobs", get(runner_jobs)) |
| b64e2537 Andy McCall ↶ |
107 |
.route("/user", get(me)) |
| ecac6e8d Andy McCall ↶ |
108 |
.route("/user/repos", get(user_repos)) |
| 109 |
.route("/user/orgs", get(user_orgs)) |
| f4e13830 Andy McCall ↶ |
110 |
.route("/user/proposals", get(user_proposals)) |
| 4dfa4599 Andy McCall ↶ |
111 |
.route("/user/sky", get(user_sky)) |
| 3d086bc3 Andy McCall ↶ |
112 |
.route("/user/starter", get(user_starter)) |
| 113 |
.route("/user/flow/runs", get(user_flow_runs)) |
| 5714347a Andy McCall ↶ |
114 |
.route("/user/runner-token", post(user_runner_token)) |
| 60f11b71 Andy McCall ↶ |
115 |
.route("/user/token", axum::routing::delete(revoke_own_token)) |
| aeed63c0 Andy McCall ↶ |
116 |
.route("/user/push", axum::routing::put(register_push).delete(forget_push)) |
| e9bfea8e Andy McCall ↶ |
117 |
.route("/version", get(version)) |
| 42a0ba4b Andy McCall ↶ |
118 |
.route("/notifications", get(notifications)) |
| 119 |
.route("/notifications/read", post(notifications_read_all)) |
| 120 |
.route("/notifications/{id}/read", post(notification_read)) |
| b64e2537 Andy McCall ↶ |
121 |
.route("/users/{name}", get(user)) |
| 166f6e9b Andy McCall |
122 |
.route("/users/{name}/drops", get(drops::of_user)) |
| 123 |
.route("/drops", get(drops::mine).post(drops::create)) |
| 124 |
.route("/drops/{id}", get(drops::view).patch(drops::edit).delete(drops::delete)) |
| b64e2537 Andy McCall ↶ |
125 |
.route("/orgs/{name}", get(org)) |
| 126 |
.route("/search", get(search)) |
| 127 |
.route("/repos", get(list_repos).post(create_repo)) |
| d23464c0 Andy McCall ↶ |
128 |
.route("/repos/{owner}/{name}", get(get_repo)) |
| 129 |
.route("/repos/{owner}/{name}/bookmarks", get(bookmarks)) |
| ba0a55bb Andy McCall ↶ |
130 |
.route("/repos/{owner}/{name}/tags", get(tags).post(create_tag)) |
| 131 |
.route("/repos/{owner}/{name}/tags/{tag}", axum::routing::delete(withdraw_tag)) |
| f677d627 Andy McCall ↶ |
132 |
.route("/repos/{owner}/{name}/consumers", get(consumers)) |
| eb2a3502 Andy McCall ↶ |
133 |
.route("/repos/{owner}/{name}/diffusion", get(diffusion).put(set_diffusion)) |
| d3b048b2 Andy McCall ↶ |
134 |
.route("/repos/{owner}/{name}/backup", axum::routing::put(set_backup)) |
| 2e9188ca Andy McCall ↶ |
135 |
.route("/user/backups", get(backups::user_get).put(backups::user_put)) |
| 136 |
.route("/user/backups/test", post(backups::user_test)) |
| 137 |
.route("/user/backups/run", post(backups::user_run)) |
| 138 |
.route("/user/backups/runs", get(backups::user_runs)) |
| 139 |
.route("/orgs/{name}/backups", get(backups::org_get).put(backups::org_put)) |
| 140 |
.route("/orgs/{name}/backups/test", post(backups::org_test)) |
| 141 |
.route("/orgs/{name}/backups/run", post(backups::org_run)) |
| 142 |
.route("/orgs/{name}/backups/runs", get(backups::org_runs)) |
| b64e2537 Andy McCall ↶ |
143 |
.route("/repos/{owner}/{name}/history/{r}", get(history)) |
| 144 |
.route("/repos/{owner}/{name}/changes/{hash}", get(change)) |
| 145 |
.route("/repos/{owner}/{name}/tree/{r}", get(tree_root)) |
| 146 |
.route("/repos/{owner}/{name}/tree/{r}/{*path}", get(tree)) |
| 147 |
.route("/repos/{owner}/{name}/file/{r}/{*path}", get(file)) |
| 148 |
.route("/repos/{owner}/{name}/blame/{r}/{*path}", get(blame)) |
| 149 |
.route("/repos/{owner}/{name}/conflicts", get(conflicts)) |
| 150 |
.route("/repos/{owner}/{name}/trust", get(trust)) |
| df940d75 Andy McCall ↶ |
151 |
.route("/repos/{owner}/{name}/releases/trust/{*tag}", get(release_trust)) |
| b64e2537 Andy McCall ↶ |
152 |
.route("/repos/{owner}/{name}/pushes", get(pushes)) |
| 153 |
.route("/repos/{owner}/{name}/proposals", get(proposals).post(create_proposal)) |
| 739a763a Andy McCall ↶ |
154 |
.route("/repos/{owner}/{name}/proposals/{number}", get(proposal).patch(edit_proposal)) |
| 1f1eb06a Andy McCall ↶ |
155 |
.route("/repos/{owner}/{name}/proposals/{number}/land", post(land_proposal)) |
| 86a69b53 Andy McCall ↶ |
156 |
.route("/repos/{owner}/{name}/proposals/{number}/auto-land", post(auto_land_on).delete(auto_land_off)) |
| b64e2537 Andy McCall ↶ |
157 |
.route("/repos/{owner}/{name}/proposals/{number}/comments", get(proposal_comments).post(proposal_comment)) |
| 158 |
.route("/repos/{owner}/{name}/proposals/{number}/reviews", get(proposal_reviews).post(proposal_review)) |
| cc1cd197 Andy McCall ↶ |
159 |
.route("/repos/{owner}/{name}/proposals/{number}/reviewers", post(request_reviewers)) |
| 7d2eb590 Andy McCall ↶ |
160 |
.route("/repos/{owner}/{name}/proposals/{number}/review-requests", post(request_assistant)) |
| cc1cd197 Andy McCall ↶ |
161 |
.route("/repos/{owner}/{name}/proposals/{number}/reviewers/{username}", axum::routing::delete(withdraw_reviewer)) |
| b64e2537 Andy McCall ↶ |
162 |
.route("/repos/{owner}/{name}/proposals/{number}/checks", get(proposal_checks)) |
| 3f02e5ea Andy McCall ↶ |
163 |
.route("/repos/{owner}/{name}/proposals/{number}/files", get(proposal_files)) |
| 164 |
.route("/repos/{owner}/{name}/proposals/{number}/content/{side}/{*path}", get(proposal_content)) |
| b64e2537 Andy McCall ↶ |
165 |
.route("/repos/{owner}/{name}/issues", get(issues).post(create_issue)) |
| 76f262e1 Andy McCall ↶ |
166 |
.route("/repos/{owner}/{name}/issues/{number}", get(issue).post(issue_state).patch(issue_edit)) |
| b64e2537 Andy McCall ↶ |
167 |
.route("/repos/{owner}/{name}/issues/{number}/comments", get(issue_comments).post(issue_comment)) |
| 76f262e1 Andy McCall ↶ |
168 |
.route("/repos/{owner}/{name}/labels", get(labels).post(create_label)) |
| 169 |
.route("/repos/{owner}/{name}/labels/{label}", axum::routing::delete(delete_label)) |
| 5ea4872f Andy McCall ↶ |
170 |
.route("/repos/{owner}/{name}/milestones", get(milestones).post(create_milestone)) |
| 40dd3f86 Andy McCall ↶ |
171 |
.route( |
| 172 |
"/repos/{owner}/{name}/coverage", |
| 173 |
get(reports::coverage_list) |
| 174 |
.post(reports::coverage_upload) |
| 175 |
.layer(axum::extract::DefaultBodyLimit::max(crate::coverage::MAX_REPORT + (1 << 20))), |
| 176 |
) |
| 617c2840 Andy McCall ↶ |
177 |
.route("/repos/{owner}/{name}/coverage/{id}", get(reports::coverage_one)) |
| 178 |
.route("/repos/{owner}/{name}/tests", get(reports::tests_list)) |
| 179 |
.route("/repos/{owner}/{name}/tests/{id}", get(reports::tests_one)) |
| 5ea4872f Andy McCall ↶ |
180 |
.route("/repos/{owner}/{name}/milestones/{title}", axum::routing::patch(edit_milestone)) |
| b64e2537 Andy McCall ↶ |
181 |
.route("/repos/{owner}/{name}/hooks", get(hooks).post(create_hook)) |
| 62ceb2ee Andy McCall ↶ |
182 |
.route("/repos/{owner}/{name}/assistants", get(repo_assistants).post(repo_assistant_put)) |
| 183 |
.route("/repos/{owner}/{name}/assistants/prompt", get(repo_prompt).put(repo_prompt_put)) |
| 184 |
.route("/repos/{owner}/{name}/assistants/{assistant}", axum::routing::delete(repo_assistant_delete)) |
| 185 |
.route("/orgs/{org}/assistants", get(org_assistants).post(org_assistant_put)) |
| 186 |
.route("/orgs/{org}/assistants/prompt", get(org_prompt).put(org_prompt_put)) |
| 187 |
.route("/orgs/{org}/assistants/{assistant}", axum::routing::delete(org_assistant_delete)) |
| 9bbca80f Andy McCall ↶ |
188 |
.route("/admin/runner-updates", get(runner_updates)) |
| 189 |
.route("/admin/runner-updates/settings", axum::routing::put(runner_update_setting)) |
| 190 |
.route("/admin/runner-updates/holds/{version}/lift", post(runner_update_lift)) |
| 62ceb2ee Andy McCall ↶ |
191 |
.route("/admin/assistants", get(site_assistants).post(site_assistant_put)) |
| 192 |
.route("/admin/assistants/prompt", get(site_prompt).put(site_prompt_put)) |
| 193 |
.route("/admin/assistants/{assistant}", axum::routing::delete(site_assistant_delete)) |
| b64e2537 Andy McCall ↶ |
194 |
.route("/repos/{owner}/{name}/hooks/{id}/delete", post(delete_hook)) |
| 195 |
.route("/repos/{owner}/{name}/checks", post(post_check)) |
| 90326c96 Andy McCall ↶ |
196 |
.route("/repos/{owner}/{name}/flow/runs", get(flow_runs).post(start_flow_run)) |
| 197 |
.route("/repos/{owner}/{name}/flow/runs/{number}", get(flow_run)) |
| 198 |
.route("/repos/{owner}/{name}/flow/runs/{number}/jobs/{job}/log", get(flow_job_log)) |
| fac6853c Andy McCall ↶ |
199 |
.route("/repos/{owner}/{name}/flow/runs/{number}/jobs/{job}/reports", get(reports::job_reports)) |
| 200 |
.route("/repos/{owner}/{name}/flow/runs/{number}/jobs/{job}/report", get(reports::job_report_one)) |
| 201 |
.route("/repos/{owner}/{name}/flow/runs/{number}/jobs/{job}/report/{*path}", get(reports::job_report_file)) |
| 202 |
.route("/repos/{owner}/{name}/reports", get(reports::latest_reports)) |
| 203 |
.route("/repos/{owner}/{name}/reports/{report}", get(reports::named_report_one)) |
| 204 |
.route("/repos/{owner}/{name}/reports/{report}/files/{*path}", get(reports::named_report_file)) |
| 1edac4b6 Andy McCall ↶ |
205 |
.route("/repos/{owner}/{name}/flow/runs/{number}/rerun", post(rerun_flow_run)) |
| e8fa5369 Andy McCall ↶ |
206 |
.route("/repos/{owner}/{name}/flow/runs/{number}/jobs/{job}/rerun", post(rerun_flow_job)) |
| 745d225d Andy McCall ↶ |
207 |
.route("/repos/{owner}/{name}/flow/runs/{number}/cancel", post(cancel_flow_run)) |
| b644e175 Andy McCall ↶ |
208 |
.route("/repos/{owner}/{name}/deployments", get(list_deployments)) |
| b1860d60 Andy McCall ↶ |
209 |
.route("/repos/{owner}/{name}/flow/runs/{number}/expedite", post(expedite_flow_run)) |
| 417184c7 Andy McCall ↶ |
210 |
.route("/repos/{owner}/{name}/flow/runs/{number}/jobs/{job}/approve", post(approve_flow_job)) |
| 211 |
.route("/repos/{owner}/{name}/flow/runs/{number}/jobs/{job}/reject", post(reject_flow_job)) |
| 47e37402 Andy McCall ↶ |
212 |
.route("/repos/{owner}/{name}/flow/runs/{number}/jobs/{job}/approval", get(flow_job_statement)) |
| 213 |
.route("/repos/{owner}/{name}/flow/runs/{number}/jobs/{job}/seal", post(seal_flow_job)) |
| 961c10be Andy McCall ↶ |
214 |
.route("/repos/{owner}/{name}/checks/required", get(required_checks).put(set_required_checks)) |
| b64e2537 Andy McCall ↶ |
215 |
.route("/repos/{owner}/{name}/checks/{state}", get(checks_for_state)) |
| 3f4b0ea6 Andy McCall ↶ |
216 |
.route("/repos/{owner}/{name}/releases", get(releases).post(create_release)) |
| 851a26a2 Andy McCall ↶ |
217 |
.route("/repos/{owner}/{name}/sky", get(repo_sky)) |
| 3d086bc3 Andy McCall ↶ |
218 |
.route("/repos/{owner}/{name}/starter", get(starter_status).post(start_starter)) |
| ced6d3af Andy McCall ↶ |
219 |
.route("/repos/{owner}/{name}/releases/{tag}", axum::routing::patch(edit_release)) |
| 5533e91a Andy McCall ↶ |
220 |
.route( |
| 221 |
"/repos/{owner}/{name}/releases/{tag}/assets", |
| 222 |
post(upload_asset).layer(axum::extract::DefaultBodyLimit::max(asset_limit + (1 << 20))), |
| 223 |
) |
| 17a3a84b Andy McCall ↶ |
224 |
|
| 225 |
.method_not_allowed_fallback(wrong_method) |
| 3f4b0ea6 Andy McCall ↶ |
226 |
} |
| 227 |
|
| 228 |
async fn releases( |
| 229 |
State(app): State<Shared>, |
| 230 |
headers: HeaderMap, |
| 231 |
Path((owner, name)): Path<(String, String)>, |
| 232 |
) -> Result<Json<Vec<Release>>, ApiError> { |
| 233 |
let c = caller(&app, &headers).await?; |
| 234 |
let (repo, row, _) = reach(&app, &c, &owner, &name, Access::Read).await?; |
| 235 |
Ok(Json(crate::web::releases::api_views(&app, &repo, &row).await?)) |
| 236 |
} |
| 237 |
|
| 851a26a2 Andy McCall ↶ |
238 |
|
| 239 |
|
| 240 |
|
| 241 |
async fn repo_sky( |
| 242 |
State(app): State<Shared>, |
| 243 |
headers: HeaderMap, |
| 244 |
Path((owner, name)): Path<(String, String)>, |
| 245 |
) -> Result<Json<hub_api::UserSky>, ApiError> { |
| 246 |
let c = caller(&app, &headers).await?; |
| 247 |
let (_, row, _) = reach(&app, &c, &owner, &name, Access::Read).await?; |
| 248 |
let now = db::now_ms(); |
| 249 |
let since = now - crate::web::home::SKY_DAYS * 86_400_000; |
| 250 |
let events = db::activity::sky(&app.db, &[row.id], since, crate::web::home::SKY_EVENTS).await?; |
| 251 |
Ok(Json(hub_api::UserSky { |
| 252 |
now, |
| 253 |
repos: vec![format!("{}/{}", row.owner, row.name)], |
| 254 |
events: events.iter().map(|e| [0, e.kind, e.at_ms, e.n]).collect(), |
| 255 |
})) |
| 256 |
} |
| 257 |
|
| 3f4b0ea6 Andy McCall ↶ |
258 |
async fn create_release( |
| 259 |
State(app): State<Shared>, |
| 260 |
headers: HeaderMap, |
| 261 |
Path((owner, name)): Path<(String, String)>, |
| 262 |
Json(body): Json<NewRelease>, |
| 263 |
) -> Result<(StatusCode, Json<Release>), ApiError> { |
| 264 |
let c = caller(&app, &headers).await?; |
| 265 |
let me = c.require("repo:write")?.clone(); |
| 266 |
let (repo, row, _) = reach(&app, &c, &owner, &name, Access::Write).await?; |
| 267 |
crate::web::releases::create_release(&app, &repo, &row, &me, &body.tag, &body.title, body.notes, body.prerelease) |
| 268 |
.await |
| 269 |
.map_err(|m| ApiError(StatusCode::BAD_REQUEST, m))?; |
| 270 |
let r = crate::web::releases::api_views(&app, &repo, &row) |
| 271 |
.await? |
| 272 |
.into_iter() |
| 273 |
.find(|r| r.tag == body.tag) |
| 274 |
.ok_or_else(|| not_found("no such release"))?; |
| 275 |
Ok((StatusCode::CREATED, Json(r))) |
| 276 |
} |
| 277 |
|
| ced6d3af Andy McCall ↶ |
278 |
|
| 279 |
|
| 280 |
async fn edit_release( |
| 281 |
State(app): State<Shared>, |
| 282 |
headers: HeaderMap, |
| 283 |
Path((owner, name, tag)): Path<(String, String, String)>, |
| 284 |
Json(body): Json<ReleaseEdit>, |
| 285 |
) -> Result<Json<Release>, ApiError> { |
| 286 |
let c = caller(&app, &headers).await?; |
| 287 |
let me = c.require("repo:write")?.clone(); |
| 288 |
let (repo, row, _) = reach(&app, &c, &owner, &name, Access::Write).await?; |
| 289 |
let r = db::releases::get(&app.db, row.id, &tag).await?.ok_or_else(|| not_found("no such release"))?; |
| 290 |
let title = body.title.as_deref().map(str::trim).filter(|t| !t.is_empty()).unwrap_or(&r.title); |
| 291 |
let notes = body.notes.as_deref().map(str::trim).unwrap_or(&r.notes); |
| 292 |
db::releases::edit(&app.db, r.id, title, notes, body.prerelease.unwrap_or(r.prerelease)).await?; |
| 293 |
db::accounts::audit(&app.db, Some(&me), "release.edited", &format!("{owner}/{name}@{tag}"), "").await.ok(); |
| 294 |
let r = crate::web::releases::api_views(&app, &repo, &row) |
| 295 |
.await? |
| 296 |
.into_iter() |
| 297 |
.find(|r| r.tag == tag) |
| 298 |
.ok_or_else(|| not_found("no such release"))?; |
| 299 |
Ok(Json(r)) |
| 300 |
} |
| 301 |
|
| 3f4b0ea6 Andy McCall ↶ |
302 |
#[derive(Deserialize)] |
| 303 |
struct AssetQuery { |
| 304 |
name: String, |
| de505df5 Andy McCall ↶ |
305 |
} |
| 306 |
|
| 3f4b0ea6 Andy McCall ↶ |
307 |
|
| 308 |
async fn upload_asset( |
| 309 |
State(app): State<Shared>, |
| 310 |
headers: HeaderMap, |
| 311 |
Path((owner, name, tag)): Path<(String, String, String)>, |
| 312 |
Query(q): Query<AssetQuery>, |
| 313 |
body: axum::body::Bytes, |
| 314 |
) -> Result<(StatusCode, Json<Release>), ApiError> { |
| 315 |
let c = caller(&app, &headers).await?; |
| 316 |
c.require("repo:write")?; |
| 317 |
let (repo, row, _) = reach(&app, &c, &owner, &name, Access::Write).await?; |
| 318 |
let r = db::releases::get(&app.db, row.id, &tag).await?.ok_or_else(|| not_found("no such release"))?; |
| 319 |
let ct = headers.get(axum::http::header::CONTENT_TYPE).and_then(|v| v.to_str().ok()).unwrap_or("application/octet-stream").to_string(); |
| 320 |
crate::web::releases::store_asset(&app, r.id, &q.name, &ct, &body).await.map_err(|m| ApiError(StatusCode::BAD_REQUEST, m))?; |
| 321 |
let r = crate::web::releases::api_views(&app, &repo, &row) |
| 322 |
.await? |
| 323 |
.into_iter() |
| 324 |
.find(|r| r.tag == tag) |
| 325 |
.ok_or_else(|| not_found("no such release"))?; |
| 326 |
Ok((StatusCode::CREATED, Json(r))) |
| 327 |
} |
| 328 |
|
| 42fa9554 Andy McCall ↶ |
329 |
pub struct ApiError(pub StatusCode, pub String); |
| b64e2537 Andy McCall ↶ |
330 |
|
| 331 |
impl IntoResponse for ApiError { |
| 332 |
fn into_response(self) -> Response { |
| 333 |
let body = Problem { status: self.0.as_u16(), title: self.0.canonical_reason().unwrap_or("error").into(), detail: self.1 }; |
| 334 |
(self.0, [("content-type", "application/problem+json")], Json(body)).into_response() |
| de505df5 Andy McCall ↶ |
335 |
} |
| b64e2537 Andy McCall ↶ |
336 |
} |
| 337 |
|
| 338 |
impl From<RepoError> for ApiError { |
| 339 |
fn from(e: RepoError) -> ApiError { |
| 340 |
match e { |
| 341 |
RepoError::NotFound => not_found("no such repository"), |
| 342 |
RepoError::Oxy(oxy_core::repo::RepoError::Msg(m)) => ApiError(StatusCode::NOT_FOUND, m), |
| 343 |
other => ApiError(StatusCode::INTERNAL_SERVER_ERROR, other.to_string()), |
| 344 |
} |
| 345 |
} |
| 346 |
} |
| 347 |
|
| 348 |
impl From<sqlx::Error> for ApiError { |
| 349 |
fn from(e: sqlx::Error) -> ApiError { |
| 350 |
ApiError(StatusCode::INTERNAL_SERVER_ERROR, e.to_string()) |
| 351 |
} |
| 352 |
} |
| 353 |
|
| ef20fdc1 Andy McCall ↶ |
354 |
pub(crate) fn not_found(what: &str) -> ApiError { |
| b64e2537 Andy McCall ↶ |
355 |
ApiError(StatusCode::NOT_FOUND, what.into()) |
| 356 |
} |
| 357 |
|
| ef20fdc1 Andy McCall ↶ |
358 |
pub(crate) fn forbidden(what: &str) -> ApiError { |
| b64e2537 Andy McCall ↶ |
359 |
ApiError(StatusCode::FORBIDDEN, what.into()) |
| 360 |
} |
| 361 |
|
| 60f11b71 Andy McCall ↶ |
362 |
|
| 363 |
|
| 364 |
|
| 365 |
pub fn client_addr(app: &Shared, headers: &HeaderMap, extensions: &axum::http::Extensions) -> String { |
| 366 |
let from_proxy = || { |
| 367 |
["cf-connecting-ip", "x-forwarded-for", "x-real-ip"] |
| 368 |
.iter() |
| 369 |
.find_map(|h| headers.get(*h).and_then(|v| v.to_str().ok()).and_then(|v| v.split(',').next()).map(|v| v.trim().to_string())) |
| 370 |
}; |
| 371 |
let addr = if app.config.server.behind_proxy { |
| 372 |
from_proxy() |
| 373 |
} else { |
| 374 |
extensions.get::<axum::extract::ConnectInfo<std::net::SocketAddr>>().map(|c| c.0.ip().to_string()) |
| 375 |
}; |
| 376 |
addr.map(|a| a.chars().filter(|c| c.is_ascii_hexdigit() || matches!(c, '.' | ':')).take(45).collect()).unwrap_or_default() |
| 377 |
} |
| 378 |
|
| 379 |
|
| 380 |
|
| 381 |
async fn revoke_own_token(State(app): State<Shared>, headers: HeaderMap) -> Result<StatusCode, ApiError> { |
| 382 |
let c = caller(&app, &headers).await?; |
| 383 |
let (Some(account), Some(id)) = (c.account.as_ref(), c.token_id) else { |
| 384 |
return Err(ApiError(StatusCode::UNAUTHORIZED, "revoking needs the personal access token to revoke".into())); |
| 385 |
}; |
| 386 |
db::accounts::delete_token(&app.db, account.id, id).await?; |
| 387 |
db::accounts::audit(&app.db, Some(account), "token.revoke", &c.token, "").await.ok(); |
| 388 |
Ok(StatusCode::NO_CONTENT) |
| 389 |
} |
| 390 |
|
| aeed63c0 Andy McCall ↶ |
391 |
#[derive(Deserialize)] |
| 392 |
struct PushRegistration { |
| 393 |
|
| 394 |
fcm_token: String, |
| 395 |
|
| 396 |
public_key: String, |
| 397 |
} |
| 398 |
|
| 399 |
|
| 400 |
|
| 401 |
|
| 402 |
async fn register_push( |
| 403 |
State(app): State<Shared>, |
| 404 |
headers: HeaderMap, |
| 405 |
Json(r): Json<PushRegistration>, |
| 406 |
) -> Result<Json<serde_json::Value>, ApiError> { |
| 407 |
let c = caller(&app, &headers).await?; |
| 408 |
let (Some(account), Some(id)) = (c.account.as_ref(), c.token_id) else { |
| 409 |
return Err(ApiError(StatusCode::UNAUTHORIZED, "a phone registers with the token it signed in with".into())); |
| 410 |
}; |
| 411 |
let key = r.public_key.trim().to_ascii_lowercase(); |
| 412 |
if key.len() != 64 || hex::decode(&key).is_err() { |
| 413 |
return Err(ApiError(StatusCode::BAD_REQUEST, "public_key is 32 bytes of hex".into())); |
| 414 |
} |
| 415 |
let fcm = r.fcm_token.trim(); |
| 416 |
if fcm.is_empty() || fcm.len() > 4096 { |
| 417 |
return Err(ApiError(StatusCode::BAD_REQUEST, "fcm_token is the phone's registration token".into())); |
| 418 |
} |
| 419 |
db::push::register(&app.db, id, account.id, fcm, &key).await?; |
| 420 |
Ok(Json(serde_json::json!({ "alerts": crate::push::enabled(&app) }))) |
| 421 |
} |
| 422 |
|
| 423 |
|
| 424 |
async fn forget_push(State(app): State<Shared>, headers: HeaderMap) -> Result<StatusCode, ApiError> { |
| 425 |
let c = caller(&app, &headers).await?; |
| 426 |
let Some(id) = c.token_id.filter(|_| c.account.is_some()) else { |
| 427 |
return Err(ApiError(StatusCode::UNAUTHORIZED, "a phone unregisters with the token it signed in with".into())); |
| 428 |
}; |
| 429 |
db::push::forget(&app.db, id).await?; |
| 430 |
Ok(StatusCode::NO_CONTENT) |
| 431 |
} |
| 432 |
|
| b64e2537 Andy McCall ↶ |
433 |
|
| 434 |
pub struct Caller { |
| 435 |
pub account: Option<Account>, |
| 436 |
pub scopes: Vec<String>, |
| 437 |
pub site: bool, |
| 0b20f1ec Andy McCall ↶ |
438 |
|
| 439 |
pub token: String, |
| 60f11b71 Andy McCall ↶ |
440 |
|
| 441 |
pub token_id: Option<i64>, |
| 05f1a85a Andy McCall ↶ |
442 |
|
| 443 |
pub agent: bool, |
| b64e2537 Andy McCall ↶ |
444 |
} |
| 445 |
|
| 446 |
impl Caller { |
| 447 |
fn has(&self, scope: &str) -> bool { |
| 448 |
self.site |
| 449 |
|| self.scopes.iter().any(|s| { |
| 450 |
s == scope |
| 451 |
|| (scope == "repo:read" && (s == "repo:write" || s == "repo:admin")) |
| 452 |
|| (scope == "repo:write" && s == "repo:admin") |
| 453 |
}) |
| 454 |
} |
| 455 |
|
| 456 |
fn require(&self, scope: &str) -> Result<&Account, ApiError> { |
| ecac6e8d Andy McCall ↶ |
457 |
|
| 458 |
let Some(account) = self.account.as_ref() else { |
| 459 |
return Err(ApiError(StatusCode::UNAUTHORIZED, "a personal access token is required: sign in (`oh auth login`)".into())); |
| 460 |
}; |
| b64e2537 Andy McCall ↶ |
461 |
if !self.has(scope) { |
| 462 |
return Err(forbidden(&format!("this token lacks the {scope} scope"))); |
| 463 |
} |
| ecac6e8d Andy McCall ↶ |
464 |
Ok(account) |
| b64e2537 Andy McCall ↶ |
465 |
} |
| 466 |
} |
| 467 |
|
| 468 |
pub async fn caller(app: &Shared, headers: &HeaderMap) -> Result<Caller, ApiError> { |
| 0b20f1ec Andy McCall ↶ |
469 |
let Some(t) = oxy_server::bearer_token(headers) else { |
| 05f1a85a Andy McCall ↶ |
470 |
return Ok(Caller { account: None, scopes: vec![], site: false, token: String::new(), token_id: None, agent: false }); |
| 0b20f1ec Andy McCall ↶ |
471 |
}; |
| b64e2537 Andy McCall ↶ |
472 |
if app.config.auth.push_tokens.iter().any(|x| auth::mac_equal(x, t)) { |
| 473 |
let admin = db::accounts::accounts(&app.db).await?.into_iter().find(|a| a.is_admin); |
| 0b20f1ec Andy McCall ↶ |
474 |
return Ok(Caller { |
| 475 |
account: admin, |
| 476 |
scopes: vec!["repo:admin".into(), "user:read".into(), "checks:write".into()], |
| 477 |
site: true, |
| 478 |
token: "site token".into(), |
| 60f11b71 Andy McCall ↶ |
479 |
token_id: None, |
| 05f1a85a Andy McCall ↶ |
480 |
agent: false, |
| 0b20f1ec Andy McCall ↶ |
481 |
}); |
| b64e2537 Andy McCall ↶ |
482 |
} |
| 483 |
let token = db::accounts::token_by_hash(&app.db, &auth::token_hash(t)).await?; |
| de505df5 Andy McCall ↶ |
484 |
match token { |
| b64e2537 Andy McCall ↶ |
485 |
Some(tok) if !tok.expired(db::now_ms()) => { |
| 6a178055 Andy McCall ↶ |
486 |
let account = db::accounts::account_by_id(&app.db, tok.account_id).await?.filter(|a| !a.blocked()); |
| b64e2537 Andy McCall ↶ |
487 |
db::accounts::touch_token(&app.db, tok.id).await.ok(); |
| 60f11b71 Andy McCall ↶ |
488 |
Ok(Caller { |
| 489 |
account, |
| 490 |
scopes: tok.scope_list().iter().map(|s| s.to_string()).collect(), |
| 491 |
site: false, |
| 492 |
token: tok.name.clone(), |
| 493 |
token_id: Some(tok.id), |
| 05f1a85a Andy McCall ↶ |
494 |
agent: tok.agent, |
| 60f11b71 Andy McCall ↶ |
495 |
}) |
| b64e2537 Andy McCall ↶ |
496 |
} |
| de505df5 Andy McCall ↶ |
497 |
_ => Err(ApiError(StatusCode::UNAUTHORIZED, "unknown or expired token".into())), |
| 498 |
} |
| 499 |
} |
| 500 |
|
| b64e2537 Andy McCall ↶ |
501 |
fn repository(app: &Shared, r: &db::repos::RepoRow) -> Repository { |
| 502 |
Repository { |
| 503 |
owner: r.owner.clone(), |
| 504 |
name: r.name.clone(), |
| 505 |
description: r.description.clone(), |
| 506 |
default_bookmark: r.default_bookmark.clone(), |
| 507 |
visibility: r.visibility(), |
| 508 |
created_ms: r.created_ms, |
| 509 |
updated_ms: r.updated_ms, |
| 510 |
clone_url: format!("{}/{}/{}", app.config.base_url(), r.owner, r.name), |
| 511 |
} |
| 512 |
} |
| 513 |
|
| 514 |
|
| 617c2840 Andy McCall ↶ |
515 |
pub(super) async fn reach( |
| de505df5 Andy McCall ↶ |
516 |
app: &Shared, |
| b64e2537 Andy McCall ↶ |
517 |
c: &Caller, |
| de505df5 Andy McCall ↶ |
518 |
owner: &str, |
| 519 |
name: &str, |
| b64e2537 Andy McCall ↶ |
520 |
access: Access, |
| 521 |
) -> Result<(RepoName, db::repos::RepoRow, Role), ApiError> { |
| 522 |
let repo = RepoName::new(owner, name).ok_or_else(|| not_found("no such repository"))?; |
| 523 |
let row = db::repos::get(&app.db, owner, name).await?.ok_or_else(|| not_found("no such repository"))?; |
| 166f6e9b Andy McCall |
524 |
|
| 525 |
if row.is_drop() { |
| 526 |
return Err(not_found("no such repository")); |
| 527 |
} |
| b64e2537 Andy McCall ↶ |
528 |
let role = auth::roles::role_for(&app.db, c.account.as_ref(), &row).await?; |
| 529 |
if !auth::roles::allows(role, access) { |
| 530 |
return Err(not_found("no such repository")); |
| 531 |
} |
| 532 |
Ok((repo, row, role.unwrap_or(Role::Read))) |
| 533 |
} |
| 534 |
|
| 535 |
fn summary(c: &view::ChangeView) -> ChangeSummary { |
| 536 |
ChangeSummary { |
| 537 |
hash: c.hash.clone(), |
| 538 |
message: if c.body.is_empty() { c.title.clone() } else { format!("{}\n\n{}", c.title, c.body) }, |
| 539 |
author: Author { |
| 540 |
name: c.author.name.clone(), |
| 541 |
email: c.author.email.clone(), |
| 542 |
key: c.author.key.clone(), |
| 543 |
account: c.author.account.clone(), |
| 760a7dd3 Andy McCall ↶ |
544 |
note: Author::note_for(&c.author.key, &c.author.account), |
| b64e2537 Andy McCall ↶ |
545 |
}, |
| 546 |
when_ms: c.when_ms, |
| 547 |
deps: c.deps.clone(), |
| 548 |
head: c.head, |
| 8933faff Andy McCall ↶ |
549 |
via: c.via.as_ref().map(|v| Via { |
| 550 |
name: v.name.clone(), |
| 551 |
key: v.key.clone(), |
| 552 |
scope: v.scope.clone(), |
| 553 |
expires_ms: v.expires_ms, |
| 554 |
revoked: v.revoked, |
| 555 |
}), |
| b64e2537 Andy McCall ↶ |
556 |
signature: match &c.signature { |
| 557 |
view::SigView::Unsigned => Signature::Unsigned, |
| 558 |
view::SigView::Valid { key, sealed, revoked, .. } => Signature::Valid { key: key.clone(), sealed: *sealed, revoked: *revoked }, |
| 559 |
view::SigView::Invalid(why) => Signature::Invalid { reason: why.clone() }, |
| 560 |
}, |
| 561 |
} |
| 562 |
} |
| 563 |
|
| 564 |
|
| 565 |
|
| 566 |
async fn me(State(app): State<Shared>, headers: HeaderMap) -> Result<Json<User>, ApiError> { |
| 567 |
let c = caller(&app, &headers).await?; |
| 568 |
let a = c.require("user:read")?; |
| 569 |
Ok(Json(user_of(&app, a).await?)) |
| 570 |
} |
| 571 |
|
| 42a0ba4b Andy McCall ↶ |
572 |
#[derive(Deserialize)] |
| 573 |
struct InboxQuery { |
| 574 |
#[serde(default)] |
| 575 |
limit: Option<i64>, |
| 576 |
} |
| 577 |
|
| 578 |
|
| 579 |
|
| 580 |
async fn notifications( |
| 581 |
State(app): State<Shared>, |
| 582 |
headers: HeaderMap, |
| 583 |
Query(q): Query<InboxQuery>, |
| 584 |
) -> Result<Json<hub_api::Inbox>, ApiError> { |
| 585 |
let c = caller(&app, &headers).await?; |
| 586 |
let a = c.require("user:read")?; |
| 587 |
let limit = q.limit.unwrap_or(50).clamp(1, 200); |
| 588 |
let base = app.config.base_url().trim_end_matches('/').to_string(); |
| ecac6e8d Andy McCall ↶ |
589 |
let rows = db::notify::inbox(&app.db, a.id, limit).await?; |
| 590 |
|
| 591 |
let mut repos: std::collections::HashMap<i64, Option<String>> = std::collections::HashMap::new(); |
| 592 |
for id in rows.iter().filter_map(|n| n.repo_id) { |
| 593 |
if let std::collections::hash_map::Entry::Vacant(e) = repos.entry(id) { |
| 594 |
e.insert(db::repos::get_by_id(&app.db, id).await?.map(|r| format!("{}/{}", r.owner, r.name))); |
| 595 |
} |
| 596 |
} |
| 597 |
let absolute = |u: String| if u.starts_with('/') { format!("{base}{u}") } else { u }; |
| 598 |
let items = rows |
| 42a0ba4b Andy McCall ↶ |
599 |
.into_iter() |
| 600 |
.map(|n| hub_api::Notification { |
| 601 |
id: n.id, |
| 602 |
at_ms: n.at_ms, |
| ecac6e8d Andy McCall ↶ |
603 |
label: crate::notify::label(&n.kind).map(String::from), |
| 42a0ba4b Andy McCall ↶ |
604 |
kind: n.kind, |
| 605 |
title: n.title, |
| ecac6e8d Andy McCall ↶ |
606 |
url: absolute(n.url), |
| 42a0ba4b Andy McCall ↶ |
607 |
actor: n.actor, |
| 608 |
read: n.read, |
| ecac6e8d Andy McCall ↶ |
609 |
repository: n.repo_id.and_then(|id| repos.get(&id).cloned().flatten()), |
| 610 |
reason: n.reason, |
| 611 |
thread: if n.thread.is_empty() { String::new() } else { absolute(n.thread) }, |
| 42a0ba4b Andy McCall ↶ |
612 |
}) |
| 613 |
.collect(); |
| 614 |
Ok(Json(hub_api::Inbox { unread: db::notify::unread(&app.db, a.id).await?, items })) |
| 615 |
} |
| 616 |
|
| 617 |
async fn notification_read(State(app): State<Shared>, headers: HeaderMap, Path(id): Path<i64>) -> Result<StatusCode, ApiError> { |
| 618 |
let c = caller(&app, &headers).await?; |
| 619 |
let a = c.require("user:read")?; |
| 620 |
db::notify::mark_read(&app.db, a.id, Some(id)).await?; |
| 621 |
Ok(StatusCode::NO_CONTENT) |
| 622 |
} |
| 623 |
|
| 624 |
async fn notifications_read_all(State(app): State<Shared>, headers: HeaderMap) -> Result<StatusCode, ApiError> { |
| 625 |
let c = caller(&app, &headers).await?; |
| 626 |
let a = c.require("user:read")?; |
| 627 |
db::notify::mark_read(&app.db, a.id, None).await?; |
| 628 |
Ok(StatusCode::NO_CONTENT) |
| 629 |
} |
| 630 |
|
| b64e2537 Andy McCall ↶ |
631 |
async fn user_of(app: &Shared, a: &Account) -> Result<User, ApiError> { |
| 632 |
let keys = db::accounts::identities_of(&app.db, a.id).await?.into_iter().map(|i| i.key).collect(); |
| 633 |
Ok(User { username: a.username.clone(), display_name: a.display_name.clone(), is_admin: a.is_admin, keys, created_ms: a.created_ms }) |
| 634 |
} |
| 635 |
|
| 636 |
async fn user(State(app): State<Shared>, Path(name): Path<String>) -> Result<Json<User>, ApiError> { |
| 637 |
let a = db::accounts::account_by_name(&app.db, &name).await?.ok_or_else(|| not_found("no such account"))?; |
| 638 |
Ok(Json(user_of(&app, &a).await?)) |
| 639 |
} |
| 640 |
|
| 641 |
async fn org(State(app): State<Shared>, Path(name): Path<String>) -> Result<Json<Organisation>, ApiError> { |
| 642 |
let o = db::accounts::org_by_name(&app.db, &name).await?.ok_or_else(|| not_found("no such organisation"))?; |
| 643 |
let members = db::accounts::org_members(&app.db, o.id).await?.into_iter().map(|(a, _)| a.username).collect(); |
| 644 |
Ok(Json(Organisation { name: o.name, display_name: o.display_name, description: o.description, members })) |
| 645 |
} |
| 646 |
|
| 647 |
#[derive(Deserialize)] |
| 648 |
struct SearchQuery { |
| 649 |
q: String, |
| 650 |
} |
| 651 |
|
| 652 |
async fn search( |
| 653 |
State(app): State<Shared>, |
| 654 |
headers: HeaderMap, |
| 655 |
Query(q): Query<SearchQuery>, |
| 656 |
) -> Result<Json<Vec<serde_json::Value>>, ApiError> { |
| 657 |
let c = caller(&app, &headers).await?; |
| 658 |
let mut out = Vec::new(); |
| 659 |
for h in db::notify::search(&app.db, &q.q, None, 50).await? { |
| 660 |
let Some(row) = db::repos::get_by_id(&app.db, h.repo_id).await? else { continue }; |
| 661 |
let role = auth::roles::role_for(&app.db, c.account.as_ref(), &row).await?; |
| 662 |
if !auth::roles::allows(role, Access::Read) { |
| 663 |
continue; |
| 664 |
} |
| 665 |
out.push( |
| 666 |
serde_json::json!({ "kind": h.kind, "repository": row.slug(), "number": h.number, "title": h.title, "snippet": h.snippet }), |
| 667 |
); |
| 668 |
} |
| 669 |
Ok(Json(out)) |
| 670 |
} |
| 671 |
|
| 672 |
|
| 673 |
|
| 674 |
async fn list_repos(State(app): State<Shared>, headers: HeaderMap) -> Result<Json<Vec<Repository>>, ApiError> { |
| 675 |
let c = caller(&app, &headers).await?; |
| 676 |
let mut out = Vec::new(); |
| 677 |
for r in db::repos::list(&app.db).await? { |
| 678 |
let role = auth::roles::role_for(&app.db, c.account.as_ref(), &r).await?; |
| 679 |
if auth::roles::allows(role, Access::Read) { |
| 680 |
out.push(repository(&app, &r)); |
| 681 |
} |
| de505df5 Andy McCall ↶ |
682 |
} |
| b64e2537 Andy McCall ↶ |
683 |
Ok(Json(out)) |
| ecac6e8d Andy McCall ↶ |
684 |
} |
| 685 |
|
| 686 |
#[derive(Deserialize)] |
| 687 |
struct UserReposQuery { |
| 688 |
|
| 689 |
#[serde(default)] |
| 690 |
affiliation: Option<String>, |
| 691 |
|
| 692 |
#[serde(default)] |
| 693 |
after: Option<String>, |
| 694 |
#[serde(default)] |
| 695 |
limit: Option<usize>, |
| 696 |
} |
| 697 |
|
| 698 |
|
| 699 |
|
| 700 |
|
| 5714347a Andy McCall ↶ |
701 |
|
| 702 |
|
| 703 |
|
| 704 |
|
| 705 |
async fn user_runner_token(State(app): State<Shared>, headers: HeaderMap) -> Result<(StatusCode, Json<RunnerToken>), ApiError> { |
| 706 |
let c = caller(&app, &headers).await?; |
| 707 |
let me = c.require("repo:write")?.clone(); |
| 708 |
let token = format!("flowreg_{}", crate::auth::random_hex(24)); |
| 709 |
let scope = db::runners::Scope { owner: me.username.clone(), repo_id: None }; |
| 710 |
db::runners::add_registration(&app.db, &blake3::hash(token.as_bytes()).to_hex(), &me.username, &scope).await?; |
| 711 |
db::accounts::audit(&app.db, Some(&me), "flow.runner.token", &me.username, "registration token for the caller's repositories (API)") |
| 712 |
.await |
| 713 |
.ok(); |
| 714 |
Ok((StatusCode::CREATED, Json(RunnerToken { token, owner: me.username }))) |
| 715 |
} |
| 716 |
|
| 5d818ec7 Andy McCall ↶ |
717 |
|
| 718 |
|
| 719 |
async fn user_proposals( |
| 720 |
State(app): State<Shared>, |
| 721 |
headers: HeaderMap, |
| 722 |
Query(q): Query<UserProposalsQuery>, |
| 723 |
) -> Result<Json<UserProposals>, ApiError> { |
| f4e13830 Andy McCall ↶ |
724 |
let c = caller(&app, &headers).await?; |
| 725 |
let me = c.require("repo:read")?.clone(); |
| 726 |
|
| 727 |
|
| 728 |
let member = db::accounts::visible_repo_ids(&app.db, me.id).await?; |
| 729 |
let seen: Vec<i64> = db::repos::list(&app.db) |
| 730 |
.await? |
| 731 |
.into_iter() |
| 732 |
.filter(|r| me.is_admin || r.visibility() != Visibility::Private || member.contains(&r.id)) |
| 733 |
.map(|r| r.id) |
| 734 |
.collect(); |
| 735 |
let base = app.config.base_url().trim_end_matches('/').to_string(); |
| 736 |
let brief = |p: db::activity::ProposalLine| ProposalBrief { |
| 737 |
url: format!("{base}/{}/{}/proposal/{}", p.owner, p.name, p.number), |
| 738 |
repository: format!("{}/{}", p.owner, p.name), |
| 739 |
number: p.number, |
| 740 |
title: p.title, |
| 741 |
author: p.author, |
| 742 |
state: match p.state.as_str() { |
| 743 |
"draft" => ProposalState::Draft, |
| 744 |
"landed" => ProposalState::Landed, |
| 745 |
"closed" => ProposalState::Closed, |
| 746 |
_ => ProposalState::Open, |
| 747 |
}, |
| 748 |
conflicted: p.conflicted, |
| 749 |
updated_ms: p.updated_ms, |
| 750 |
}; |
| 5d818ec7 Andy McCall ↶ |
751 |
let landable = if q.landable { landable_for(&app, &c, &member, &base).await? } else { Vec::new() }; |
| f4e13830 Andy McCall ↶ |
752 |
Ok(Json(UserProposals { |
| 753 |
review: db::activity::awaiting_review(&app.db, me.id, &member).await?.into_iter().map(brief).collect(), |
| 754 |
authored: db::activity::authored(&app.db, me.id, &seen).await?.into_iter().map(brief).collect(), |
| 5d818ec7 Andy McCall ↶ |
755 |
landable, |
| f4e13830 Andy McCall ↶ |
756 |
})) |
| 5d818ec7 Andy McCall ↶ |
757 |
} |
| 758 |
|
| 759 |
|
| 760 |
|
| 761 |
|
| 762 |
|
| 763 |
async fn landable_for(app: &Shared, c: &Caller, member: &[i64], base: &str) -> Result<Vec<ProposalBrief>, ApiError> { |
| 764 |
use futures::StreamExt; |
| 765 |
let mut todo = Vec::new(); |
| 766 |
for row in db::repos::list(&app.db).await?.into_iter().filter(|r| member.contains(&r.id) && !r.is_drop()) { |
| 767 |
let role = auth::roles::role_for(&app.db, c.account.as_ref(), &row).await?; |
| 768 |
if !auth::roles::allows(role, Access::Write) { |
| 769 |
continue; |
| 770 |
} |
| 771 |
let Some(repo) = RepoName::new(&row.owner, &row.name) else { continue }; |
| 772 |
for p in db::proposals::list(&app.db, row.id, &["open"]).await? { |
| 773 |
todo.push((repo.clone(), row.clone(), p)); |
| 774 |
} |
| 775 |
} |
| 776 |
let found: Vec<Option<ProposalBrief>> = futures::stream::iter(todo) |
| 777 |
.map(|(repo, row, p)| { |
| 778 |
let (app, base) = (app.clone(), base.to_string()); |
| 779 |
async move { |
| 780 |
let (number, title, author, updated_ms) = (p.number, p.title.clone(), p.author.clone(), p.updated_ms); |
| 781 |
let loaded = crate::web::proposals::load_summary(&app, &repo, p).await.ok()?; |
| 782 |
let v = crate::web::proposals::verdict(&app, &loaded, row.id).await.ok()?; |
| 783 |
v.blockers.is_empty().then(|| ProposalBrief { |
| 784 |
url: format!("{base}/{}/{}/proposal/{number}", row.owner, row.name), |
| 785 |
repository: format!("{}/{}", row.owner, row.name), |
| 786 |
number, |
| 787 |
title, |
| 788 |
author, |
| 789 |
state: ProposalState::Open, |
| 790 |
conflicted: loaded.conflicted, |
| 791 |
updated_ms, |
| 792 |
}) |
| 793 |
} |
| 794 |
}) |
| 795 |
.buffered(4) |
| 796 |
.collect() |
| 797 |
.await; |
| 798 |
Ok(found.into_iter().flatten().collect()) |
| f4e13830 Andy McCall ↶ |
799 |
} |
| 800 |
|
| 4dfa4599 Andy McCall ↶ |
801 |
|
| 802 |
|
| 803 |
|
| 804 |
|
| 805 |
async fn user_sky(State(app): State<Shared>, headers: HeaderMap) -> Result<Json<hub_api::UserSky>, ApiError> { |
| 806 |
let c = caller(&app, &headers).await?; |
| 807 |
let me = c.require("repo:read")?.clone(); |
| 808 |
let member = db::accounts::visible_repo_ids(&app.db, me.id).await?; |
| 809 |
let mut mine = Vec::new(); |
| 810 |
for r in db::repos::list(&app.db).await? { |
| 811 |
if member.contains(&r.id) && auth::roles::allows(auth::roles::role_for(&app.db, Some(&me), &r).await?, Access::Read) { |
| 812 |
mine.push(r); |
| 813 |
} |
| 814 |
} |
| 815 |
mine.sort_by_key(|r| std::cmp::Reverse(r.updated_ms)); |
| 816 |
let ids: Vec<i64> = mine.iter().map(|r| r.id).collect(); |
| 817 |
let now = db::now_ms(); |
| 818 |
let since = now - crate::web::home::SKY_DAYS * 86_400_000; |
| 819 |
let events = db::activity::sky(&app.db, &ids, since, crate::web::home::SKY_EVENTS).await?; |
| 820 |
let events = events.iter().filter_map(|e| Some([ids.iter().position(|&id| id == e.repo_id)? as i64, e.kind, e.at_ms, e.n])).collect(); |
| 821 |
Ok(Json(hub_api::UserSky { now, repos: mine.iter().map(|r| format!("{}/{}", r.owner, r.name)).collect(), events })) |
| 822 |
} |
| 823 |
|
| 3d086bc3 Andy McCall ↶ |
824 |
|
| 825 |
|
| 826 |
|
| 827 |
async fn user_flow_runs( |
| 828 |
State(app): State<Shared>, |
| 829 |
headers: HeaderMap, |
| 830 |
Query(q): Query<hub_api::UserFlowRunsQuery>, |
| 831 |
) -> Result<Json<Vec<hub_api::UserFlowRun>>, ApiError> { |
| 832 |
let c = caller(&app, &headers).await?; |
| 833 |
let me = c.require("repo:read")?.clone(); |
| 834 |
let member = db::accounts::visible_repo_ids(&app.db, me.id).await?; |
| 835 |
let mut mine = std::collections::HashMap::new(); |
| 836 |
for r in db::repos::list(&app.db).await? { |
| 837 |
if member.contains(&r.id) && auth::roles::allows(auth::roles::role_for(&app.db, Some(&me), &r).await?, Access::Read) { |
| 838 |
mine.insert(r.id, r); |
| 839 |
} |
| 840 |
} |
| 841 |
let ids: Vec<i64> = mine.keys().copied().collect(); |
| 842 |
let limit = q.limit.unwrap_or(30).clamp(1, 100); |
| 843 |
let runs = db::activity::recent_runs(&app.db, &ids, q.before.unwrap_or(i64::MAX), limit).await?; |
| 844 |
let queue = if runs.iter().any(|r| r.live()) { db::flow::queue(&app.db).await? } else { vec![] }; |
| 845 |
let mut out = Vec::with_capacity(runs.len()); |
| 846 |
for run in &runs { |
| 847 |
let Some(row) = mine.get(&run.repo_id) else { continue }; |
| 848 |
let jobs = db::flow::jobs(&app.db, run.id).await?; |
| 849 |
out.push(hub_api::UserFlowRun { |
| 850 |
repository: format!("{}/{}", row.owner, row.name), |
| 851 |
run: flow_run_of(&app, row, run, jobs, &queue), |
| 852 |
}); |
| 853 |
} |
| 854 |
Ok(Json(out)) |
| 855 |
} |
| 856 |
|
| 857 |
#[derive(Deserialize)] |
| 858 |
struct StarterQuery { |
| 859 |
owner: String, |
| 860 |
} |
| 861 |
|
| 862 |
|
| 863 |
|
| 864 |
|
| 865 |
async fn user_starter( |
| 866 |
State(app): State<Shared>, |
| 867 |
headers: HeaderMap, |
| 868 |
Query(q): Query<StarterQuery>, |
| 869 |
) -> Result<Json<hub_api::StarterAssistants>, ApiError> { |
| 870 |
let c = caller(&app, &headers).await?; |
| 871 |
let me = c.require("repo:read")?; |
| 872 |
if !auth::roles::may_create_under(&app.db, me, q.owner.trim()).await? { |
| 873 |
return Ok(Json(hub_api::StarterAssistants { assistants: vec![] })); |
| 874 |
} |
| 875 |
let found = crate::starter::assistants_for(&app.db, q.owner.trim()).await?; |
| 876 |
Ok(Json(hub_api::StarterAssistants { |
| 877 |
assistants: found |
| 878 |
.into_iter() |
| 879 |
.map(|a| hub_api::StarterAssistant { |
| 880 |
name: a.assistant.name, |
| 881 |
model: a.assistant.model, |
| 882 |
from: if a.from.is_empty() { "the site".into() } else { a.from }, |
| 883 |
}) |
| 884 |
.collect(), |
| 885 |
})) |
| 886 |
} |
| 887 |
|
| 888 |
fn starter_status_of(s: Option<crate::starter::State>) -> hub_api::StarterStatus { |
| 889 |
use crate::starter::State; |
| 890 |
let mut out = hub_api::StarterStatus { |
| 891 |
status: "none".into(), |
| 892 |
assistant: String::new(), |
| 893 |
change: String::new(), |
| 894 |
files: vec![], |
| 895 |
error: String::new(), |
| 896 |
}; |
| 897 |
match s { |
| 898 |
None => {} |
| 899 |
Some(State::Running { assistant }) => (out.status, out.assistant) = ("running".into(), assistant), |
| 900 |
Some(State::Done { assistant, change, files }) => { |
| 901 |
(out.status, out.assistant, out.change, out.files) = ("done".into(), assistant, change, files) |
| 902 |
} |
| 903 |
Some(State::Failed { assistant, error }) => (out.status, out.assistant, out.error) = ("failed".into(), assistant, error), |
| 904 |
} |
| 905 |
out |
| 906 |
} |
| 907 |
|
| 908 |
|
| 909 |
async fn starter_status( |
| 910 |
State(app): State<Shared>, |
| 911 |
headers: HeaderMap, |
| 912 |
Path((owner, name)): Path<(String, String)>, |
| 913 |
) -> Result<Json<hub_api::StarterStatus>, ApiError> { |
| 914 |
let c = caller(&app, &headers).await?; |
| 915 |
let (repo, _, _) = reach(&app, &c, &owner, &name, Access::Read).await?; |
| 916 |
Ok(Json(starter_status_of(crate::starter::state(&app, &repo)))) |
| 917 |
} |
| 918 |
|
| 919 |
|
| 920 |
|
| 921 |
|
| 922 |
async fn start_starter( |
| 923 |
State(app): State<Shared>, |
| 924 |
headers: HeaderMap, |
| 925 |
Path((owner, name)): Path<(String, String)>, |
| 926 |
Json(body): Json<hub_api::StarterRequest>, |
| 927 |
) -> Result<(StatusCode, Json<hub_api::StarterStatus>), ApiError> { |
| 928 |
let c = caller(&app, &headers).await?; |
| 929 |
let me = c.require("repo:admin")?.clone(); |
| 930 |
let (repo, row, _) = reach(&app, &c, &owner, &name, Access::Admin).await?; |
| 931 |
let description = body.description.trim(); |
| 932 |
if description.is_empty() { |
| 933 |
return Err(ApiError(StatusCode::UNPROCESSABLE_ENTITY, "say what the repository is for (description)".into())); |
| 934 |
} |
| 935 |
if description.chars().count() > crate::starter::MAX_DESCRIPTION { |
| 936 |
return Err(ApiError( |
| 937 |
StatusCode::UNPROCESSABLE_ENTITY, |
| 938 |
format!("a description is at most {} characters", crate::starter::MAX_DESCRIPTION), |
| 939 |
)); |
| 940 |
} |
| 941 |
if matches!(crate::starter::state(&app, &repo), Some(crate::starter::State::Running { .. })) { |
| 942 |
return Err(ApiError(StatusCode::CONFLICT, "a starter is being drafted for it already".into())); |
| 943 |
} |
| 944 |
if !crate::starter::is_empty(&app, &repo, &row.default_bookmark).await.map_err(|e| ApiError(StatusCode::INTERNAL_SERVER_ERROR, e))? { |
| 945 |
return Err(ApiError(StatusCode::CONFLICT, "the repository has files already; a starter is only for an empty one".into())); |
| 946 |
} |
| 947 |
let available = crate::starter::assistants_for(&app.db, &row.owner).await?; |
| 948 |
let chosen = match body.assistant.as_deref().map(str::trim).filter(|n| !n.is_empty()) { |
| 949 |
Some(n) => available.into_iter().find(|a| a.assistant.name.eq_ignore_ascii_case(n)), |
| 950 |
None => available.into_iter().next(), |
| 951 |
}; |
| 952 |
let Some(a) = chosen else { |
| 953 |
return Err(ApiError( |
| 954 |
StatusCode::UNPROCESSABLE_ENTITY, |
| 955 |
"no assistant is set up for this owner (Admin › Assistants, or the organisation's settings)".into(), |
| 956 |
)); |
| 957 |
}; |
| 958 |
if let Err(why) = crate::web::edit::signer_for(&app, me.id).await { |
| 959 |
return Err(ApiError(StatusCode::UNPROCESSABLE_ENTITY, why)); |
| 960 |
} |
| 961 |
crate::starter::start(app.clone(), row, me, a.assistant, description.to_string()); |
| 962 |
Ok((StatusCode::ACCEPTED, Json(starter_status_of(crate::starter::state(&app, &repo))))) |
| 963 |
} |
| 964 |
|
| ecac6e8d Andy McCall ↶ |
965 |
async fn user_repos( |
| 966 |
State(app): State<Shared>, |
| 967 |
headers: HeaderMap, |
| 968 |
Query(q): Query<UserReposQuery>, |
| 969 |
) -> Result<Json<Vec<Repository>>, ApiError> { |
| 970 |
let c = caller(&app, &headers).await?; |
| 971 |
let me = c.require("repo:read")?.clone(); |
| 972 |
let wanted: Vec<String> = q |
| 973 |
.affiliation |
| 974 |
.as_deref() |
| 975 |
.unwrap_or("owner,organization,collaborator") |
| 976 |
.split(',') |
| 977 |
.map(|s| s.trim().to_ascii_lowercase()) |
| 978 |
.filter(|s| !s.is_empty()) |
| 979 |
.collect(); |
| 980 |
if let Some(bad) = wanted.iter().find(|w| !["owner", "organization", "collaborator"].contains(&w.as_str())) { |
| 981 |
return Err(ApiError(StatusCode::BAD_REQUEST, format!("unknown affiliation {bad:?}: owner, organization or collaborator"))); |
| 982 |
} |
| 983 |
let orgs: Vec<String> = db::accounts::orgs_of(&app.db, me.id).await?.into_iter().map(|(o, _)| o.name).collect(); |
| 984 |
let limit = q.limit.unwrap_or(50).clamp(1, 100); |
| 985 |
let mut rows = db::repos::list(&app.db).await?; |
| 986 |
rows.sort_by(|a, b| (&a.owner, &a.name).cmp(&(&b.owner, &b.name))); |
| 987 |
let mut out = Vec::new(); |
| 988 |
for r in rows { |
| 989 |
if let Some(after) = q.after.as_deref() { |
| 990 |
if format!("{}/{}", r.owner, r.name).as_str() <= after { |
| 991 |
continue; |
| 992 |
} |
| 993 |
} |
| 994 |
let mine = (wanted.iter().any(|w| w == "owner") && r.owner == me.username) |
| 995 |
|| (wanted.iter().any(|w| w == "organization") && orgs.contains(&r.owner)) |
| 996 |
|| (wanted.iter().any(|w| w == "collaborator") && db::accounts::collaborator_role(&app.db, r.id, me.id).await?.is_some()); |
| 997 |
if !mine || !auth::roles::allows(auth::roles::role_for(&app.db, Some(&me), &r).await?, Access::Read) { |
| 998 |
continue; |
| 999 |
} |
| 1000 |
out.push(repository(&app, &r)); |
| 1001 |
if out.len() == limit { |
| 1002 |
break; |
| 1003 |
} |
| 1004 |
} |
| 1005 |
Ok(Json(out)) |
| 1006 |
} |
| 1007 |
|
| 1008 |
|
| 1009 |
async fn user_orgs(State(app): State<Shared>, headers: HeaderMap) -> Result<Json<Vec<hub_api::UserOrg>>, ApiError> { |
| 1010 |
let c = caller(&app, &headers).await?; |
| 1011 |
let me = c.require("user:read")?; |
| 1012 |
let orgs = db::accounts::orgs_of(&app.db, me.id).await?; |
| 1013 |
Ok(Json(orgs.into_iter().map(|(o, role)| hub_api::UserOrg { name: o.name, display_name: o.display_name, role }).collect())) |
| b64e2537 Andy McCall ↶ |
1014 |
} |
| 1015 |
|
| 1016 |
async fn create_repo( |
| 1017 |
State(app): State<Shared>, |
| 1018 |
headers: HeaderMap, |
| 1019 |
Json(body): Json<NewRepository>, |
| 1020 |
) -> Result<(StatusCode, Json<Repository>), ApiError> { |
| 1021 |
let c = caller(&app, &headers).await?; |
| 1022 |
let me = c.require("repo:admin")?; |
| 1023 |
let name = RepoName::new(&body.owner, &body.name).ok_or_else(|| ApiError(StatusCode::BAD_REQUEST, "invalid owner or name".into()))?; |
| 66fd9d6b Andy McCall ↶ |
1024 |
if name.name.ends_with(crate::wiki::SUFFIX) { |
| 1025 |
return Err(ApiError(StatusCode::BAD_REQUEST, "a name cannot end in .wiki: that is the address of a repository's wiki".into())); |
| 1026 |
} |
| b64e2537 Andy McCall ↶ |
1027 |
if !auth::roles::may_create_under(&app.db, me, &name.owner).await? { |
| 1028 |
return Err(forbidden("you cannot create repositories under that owner")); |
| 1029 |
} |
| 1030 |
if db::repos::get(&app.db, &name.owner, &name.name).await?.is_some() || app.repos.exists(&name) { |
| 1031 |
return Err(ApiError(StatusCode::CONFLICT, "that repository exists".into())); |
| 1032 |
} |
| 15d3f6f7 Andy McCall ↶ |
1033 |
app.repos.create_async(&name, None).await?; |
| b64e2537 Andy McCall ↶ |
1034 |
let row = db::repos::create(&app.db, &name.owner, &name.name, &body.description, body.visibility).await?; |
| 1035 |
db::accounts::audit(&app.db, Some(me), "repo.created", &name.to_string(), "api").await.ok(); |
| 1036 |
Ok((StatusCode::CREATED, Json(repository(&app, &row)))) |
| 1037 |
} |
| 1038 |
|
| 1039 |
async fn get_repo( |
| 1040 |
State(app): State<Shared>, |
| 1041 |
headers: HeaderMap, |
| 1042 |
Path((owner, name)): Path<(String, String)>, |
| 1043 |
) -> Result<Json<Repository>, ApiError> { |
| 1044 |
let c = caller(&app, &headers).await?; |
| 1045 |
let (_, row, _) = reach(&app, &c, &owner, &name, Access::Read).await?; |
| 1046 |
Ok(Json(repository(&app, &row))) |
| 1047 |
} |
| 1048 |
|
| 1049 |
async fn bookmarks( |
| 1050 |
State(app): State<Shared>, |
| 1051 |
headers: HeaderMap, |
| 1052 |
Path((owner, name)): Path<(String, String)>, |
| 1053 |
) -> Result<Json<Vec<Bookmark>>, ApiError> { |
| 1054 |
let c = caller(&app, &headers).await?; |
| 1055 |
let (repo, row, _) = reach(&app, &c, &owner, &name, Access::Read).await?; |
| 1056 |
let default = row.default_bookmark.clone(); |
| 1057 |
let list = app.repos.read(&repo, move |r, cache| view::bookmarks(r, cache, &default)).await?; |
| 1058 |
Ok(Json(list.into_iter().map(|b| Bookmark { name: b.name, heads: b.heads, changes: b.changes, default: b.default }).collect())) |
| 1059 |
} |
| 1060 |
|
| e7158350 Andy McCall ↶ |
1061 |
#[derive(serde::Deserialize)] |
| d3b048b2 Andy McCall ↶ |
1062 |
struct BackupSetting { |
| 1063 |
|
| 1064 |
backup: String, |
| 1065 |
} |
| 1066 |
|
| 1067 |
|
| 1068 |
|
| 1069 |
async fn set_backup( |
| 1070 |
State(app): State<Shared>, |
| 1071 |
headers: HeaderMap, |
| 1072 |
Path((owner, name)): Path<(String, String)>, |
| 1073 |
Json(b): Json<BackupSetting>, |
| 1074 |
) -> Result<Json<serde_json::Value>, ApiError> { |
| 1075 |
let c = caller(&app, &headers).await?; |
| 1076 |
let (_, row, _) = reach(&app, &c, &owner, &name, Access::Maintain).await?; |
| 1077 |
let setting = match b.backup.as_str() { |
| 1078 |
"owner" => "", |
| 1079 |
"hourly" | "daily" | "off" => b.backup.as_str(), |
| 1080 |
_ => return Err(ApiError(StatusCode::BAD_REQUEST, "backup is owner, hourly, daily or off".into())), |
| 1081 |
}; |
| 1082 |
db::repos::set_backup(&app.db, row.id, setting).await?; |
| 1083 |
db::accounts::audit(&app.db, c.account.as_ref(), "repo.backup", &format!("{owner}/{name}"), &b.backup).await.ok(); |
| 1084 |
Ok(Json(serde_json::json!({ "backup": b.backup }))) |
| 1085 |
} |
| 1086 |
|
| 1087 |
#[derive(serde::Deserialize)] |
| e7158350 Andy McCall ↶ |
1088 |
struct DiffusionSetting { |
| 1089 |
|
| 1090 |
follow: String, |
| f4d6ef41 Andy McCall ↶ |
1091 |
|
| 1092 |
#[serde(default)] |
| 1093 |
land: Option<String>, |
| e7158350 Andy McCall ↶ |
1094 |
} |
| 1095 |
|
| 1096 |
|
| 1097 |
|
| 1098 |
async fn set_diffusion( |
| 1099 |
State(app): State<Shared>, |
| 1100 |
headers: HeaderMap, |
| 1101 |
Path((owner, name)): Path<(String, String)>, |
| 1102 |
Json(d): Json<DiffusionSetting>, |
| 1103 |
) -> Result<Json<serde_json::Value>, ApiError> { |
| 1104 |
let c = caller(&app, &headers).await?; |
| 1105 |
let (_, row, _) = reach(&app, &c, &owner, &name, Access::Maintain).await?; |
| 1106 |
let setting = match d.follow.as_str() { |
| 1107 |
"off" | "green" | "any" => d.follow.as_str(), |
| 1108 |
"default" => "", |
| 1109 |
_ => return Err(ApiError(StatusCode::BAD_REQUEST, "follow is off, green, any or default".into())), |
| f4d6ef41 Andy McCall ↶ |
1110 |
}; |
| 1111 |
let land = match d.land.as_deref() { |
| 1112 |
Some(l @ ("auto" | "propose")) => Some(l), |
| 1113 |
None => None, |
| 1114 |
Some(_) => return Err(ApiError(StatusCode::BAD_REQUEST, "land is auto or propose".into())), |
| e7158350 Andy McCall ↶ |
1115 |
}; |
| 1116 |
db::repos::set_diffusion(&app.db, row.id, setting).await?; |
| f4d6ef41 Andy McCall ↶ |
1117 |
if let Some(l) = land { |
| 1118 |
db::repos::set_diffusion_land(&app.db, row.id, l).await?; |
| 1119 |
} |
| e7158350 Andy McCall ↶ |
1120 |
db::accounts::audit( |
| 1121 |
&app.db, |
| 1122 |
c.account.as_ref(), |
| 1123 |
"repo.diffusion", |
| 1124 |
&format!("{owner}/{name}"), |
| 1125 |
if setting.is_empty() { "default" } else { setting }, |
| 1126 |
) |
| 1127 |
.await |
| 1128 |
.ok(); |
| 1129 |
let row = db::repos::get_by_id(&app.db, row.id).await?.unwrap_or(row); |
| 1130 |
let rule = crate::diffusion::rule(&app.config.diffusion.follow, &row, None, ""); |
| 3776b70d Andy McCall ↶ |
1131 |
|
| 1132 |
if rule.follow != crate::diffusion::Follow::Off { |
| 1133 |
let (app, row) = (app.clone(), row.clone()); |
| 1134 |
tokio::spawn(async move { crate::diffusion::catch_up(&app, &row).await }); |
| 1135 |
} |
| f4d6ef41 Andy McCall ↶ |
1136 |
if land == Some("auto") { |
| 1137 |
let (app, row) = (app.clone(), row.clone()); |
| 1138 |
tokio::spawn(async move { crate::diffusion::land_ready(&app, &row).await }); |
| 1139 |
} |
| 1140 |
Ok(Json( |
| 1141 |
serde_json::json!({ "follow": rule.follow, "from": rule.from, "land": if row.diffusion_land == "auto" { "auto" } else { "propose" } }), |
| 1142 |
)) |
| e7158350 Andy McCall ↶ |
1143 |
} |
| 1144 |
|
| f677d627 Andy McCall ↶ |
1145 |
|
| 1146 |
|
| 1147 |
|
| 1148 |
async fn consumers( |
| 1149 |
State(app): State<Shared>, |
| 1150 |
headers: HeaderMap, |
| 1151 |
Path((owner, name)): Path<(String, String)>, |
| 1152 |
) -> Result<Json<Vec<crate::diffusion::Consumer>>, ApiError> { |
| 1153 |
let c = caller(&app, &headers).await?; |
| 1154 |
let (_, row, _) = reach(&app, &c, &owner, &name, Access::Read).await?; |
| 1155 |
Ok(Json(crate::diffusion::consumers(&app, &row, c.account.as_ref()).await?)) |
| 1156 |
} |
| 1157 |
|
| eb2a3502 Andy McCall ↶ |
1158 |
|
| 1159 |
|
| 1160 |
async fn diffusion( |
| 1161 |
State(app): State<Shared>, |
| 1162 |
headers: HeaderMap, |
| 1163 |
Path((owner, name)): Path<(String, String)>, |
| 1164 |
) -> Result<Json<hub_api::Diffusion>, ApiError> { |
| 1165 |
let c = caller(&app, &headers).await?; |
| 1166 |
let (_, row, _) = reach(&app, &c, &owner, &name, Access::Read).await?; |
| 1167 |
let slug = format!("{owner}/{name}"); |
| 1168 |
let takes_from = crate::diffusion::follows(&app, &row, c.account.as_ref()) |
| 1169 |
.await |
| 1170 |
.iter() |
| 1171 |
.map(|(up, p)| p.api(&format!("{}/{}", up.owner, up.name))) |
| 1172 |
.collect(); |
| 1173 |
let diffuses_to = crate::diffusion::consumers(&app, &row, c.account.as_ref()).await?.iter().map(|p| p.api(&slug)).collect(); |
| 1174 |
Ok(Json(hub_api::Diffusion { takes_from, diffuses_to })) |
| 1175 |
} |
| 1176 |
|
| b64e2537 Andy McCall ↶ |
1177 |
async fn tags( |
| 1178 |
State(app): State<Shared>, |
| 1179 |
headers: HeaderMap, |
| 1180 |
Path((owner, name)): Path<(String, String)>, |
| 1181 |
) -> Result<Json<Vec<Tag>>, ApiError> { |
| 1182 |
let c = caller(&app, &headers).await?; |
| 1183 |
let (repo, _, _) = reach(&app, &c, &owner, &name, Access::Read).await?; |
| 1184 |
let list = app.repos.read(&repo, |r, _| view::tags(r)).await?; |
| 1185 |
Ok(Json(list.into_iter().map(|t| Tag { name: t.name, heads: t.heads, message: t.message, signer: t.signer }).collect())) |
| 1186 |
} |
| 1187 |
|
| ba0a55bb Andy McCall ↶ |
1188 |
|
| 1189 |
async fn create_tag( |
| 1190 |
State(app): State<Shared>, |
| 1191 |
headers: HeaderMap, |
| 1192 |
Path((owner, name)): Path<(String, String)>, |
| 1193 |
Json(body): Json<NewTag>, |
| 1194 |
) -> Result<(StatusCode, Json<Tag>), ApiError> { |
| 1195 |
let c = caller(&app, &headers).await?; |
| 1196 |
let me = c.require("repo:write")?.clone(); |
| 1197 |
let (repo, row, _) = reach(&app, &c, &owner, &name, Access::Write).await?; |
| 1198 |
let made = crate::tags::create( |
| 1199 |
&app, |
| 1200 |
&row, |
| 1201 |
&repo, |
| 1202 |
&me, |
| 1203 |
&body.name, |
| 1204 |
body.target.as_deref().unwrap_or(""), |
| 1205 |
body.message.as_deref().unwrap_or(""), |
| 1206 |
) |
| 1207 |
.await |
| 1208 |
.map_err(|m| ApiError(StatusCode::BAD_REQUEST, m))?; |
| 1209 |
let t = app |
| 1210 |
.repos |
| 1211 |
.read(&repo, |r, _| view::tags(r)) |
| 1212 |
.await? |
| 1213 |
.into_iter() |
| 1214 |
.find(|t| t.name == made.name) |
| 1215 |
.ok_or_else(|| not_found("no such tag"))?; |
| 1216 |
Ok((StatusCode::CREATED, Json(Tag { name: t.name, heads: t.heads, message: t.message, signer: t.signer }))) |
| 1217 |
} |
| 1218 |
|
| 1219 |
#[derive(Deserialize)] |
| 1220 |
struct WithdrawQuery { |
| 1221 |
#[serde(default)] |
| 1222 |
reason: String, |
| 1223 |
} |
| 1224 |
|
| 1225 |
|
| 1226 |
|
| 1227 |
async fn withdraw_tag( |
| 1228 |
State(app): State<Shared>, |
| 1229 |
headers: HeaderMap, |
| 1230 |
Path((owner, name, tag)): Path<(String, String, String)>, |
| 1231 |
Query(q): Query<WithdrawQuery>, |
| 1232 |
) -> Result<StatusCode, ApiError> { |
| 1233 |
let c = caller(&app, &headers).await?; |
| 1234 |
let me = c.require("repo:write")?.clone(); |
| 1235 |
let (repo, row, _) = reach(&app, &c, &owner, &name, Access::Maintain).await?; |
| 1236 |
if db::releases::get(&app.db, row.id, &tag).await?.is_some() { |
| 1237 |
return Err(ApiError(StatusCode::CONFLICT, format!("a release uses {tag}: delete the release first"))); |
| 1238 |
} |
| 1239 |
crate::tags::withdraw(&app, &row, &repo, &me, &tag, &q.reason).await.map_err(|m| ApiError(StatusCode::BAD_REQUEST, m))?; |
| 1240 |
Ok(StatusCode::NO_CONTENT) |
| 1241 |
} |
| 1242 |
|
| b64e2537 Andy McCall ↶ |
1243 |
#[derive(Deserialize)] |
| 1244 |
struct HistoryQuery { |
| 1245 |
path: Option<String>, |
| 1246 |
offset: Option<usize>, |
| 1247 |
limit: Option<usize>, |
| f28389bd Andy McCall ↶ |
1248 |
|
| 1249 |
|
| 1250 |
r: Option<String>, |
| b64e2537 Andy McCall ↶ |
1251 |
} |
| 1252 |
|
| 1253 |
async fn history( |
| 1254 |
State(app): State<Shared>, |
| 1255 |
headers: HeaderMap, |
| 1256 |
Path((owner, name, r)): Path<(String, String, String)>, |
| 1257 |
Query(q): Query<HistoryQuery>, |
| 1258 |
) -> Result<Json<History>, ApiError> { |
| 1259 |
let c = caller(&app, &headers).await?; |
| 1260 |
let (repo, _, _) = reach(&app, &c, &owner, &name, Access::Read).await?; |
| 1261 |
let (offset, limit) = (q.offset.unwrap_or(0), q.limit.unwrap_or(50).min(500)); |
| f28389bd Andy McCall ↶ |
1262 |
let revset = q.r.clone().filter(|s| !s.trim().is_empty()); |
| 1263 |
let by_revset = revset.is_some(); |
| b64e2537 Andy McCall ↶ |
1264 |
let h = app |
| 1265 |
.repos |
| 1266 |
.read(&repo, move |repo, cache| { |
| 1267 |
let target = view::resolve(repo, cache, &r)?; |
| f28389bd Andy McCall ↶ |
1268 |
match &revset { |
| 1269 |
Some(rs) => view::history_revset(repo, cache, target, rs, offset, limit), |
| 1270 |
None => view::history(repo, cache, target, q.path.as_deref(), offset, limit), |
| 1271 |
} |
| b64e2537 Andy McCall ↶ |
1272 |
}) |
| f28389bd Andy McCall ↶ |
1273 |
.await |
| 1274 |
.map_err(|e| { |
| 1275 |
|
| 1276 |
|
| 1277 |
if by_revset { |
| 1278 |
ApiError(StatusCode::BAD_REQUEST, e.to_string()) |
| 1279 |
} else { |
| 1280 |
e.into() |
| 1281 |
} |
| 1282 |
})?; |
| b64e2537 Andy McCall ↶ |
1283 |
let mut entries = h.entries; |
| 1284 |
crate::web::attribute(&app, &mut entries.iter_mut().collect::<Vec<_>>()).await; |
| 1285 |
Ok(Json(History { |
| 1286 |
reference: h.target.label, |
| 1287 |
heads: h.target.heads.iter().map(|x| x.to_hex()).collect(), |
| 1288 |
total: h.total, |
| 1289 |
offset: h.offset, |
| 1290 |
changes: entries.iter().map(summary).collect(), |
| 1291 |
})) |
| 1292 |
} |
| 1293 |
|
| 1294 |
async fn change( |
| 1295 |
State(app): State<Shared>, |
| 1296 |
headers: HeaderMap, |
| 1297 |
Path((owner, name, hash)): Path<(String, String, String)>, |
| 1298 |
) -> Result<Json<ChangeDetail>, ApiError> { |
| 1299 |
let c = caller(&app, &headers).await?; |
| 1300 |
let (repo, _, _) = reach(&app, &c, &owner, &name, Access::Read).await?; |
| 1301 |
let d = app |
| 1302 |
.repos |
| 1303 |
.read(&repo, move |repo, cache| { |
| 1304 |
let h = view::resolve_change(repo, cache, &hash)?; |
| 1305 |
view::change(repo, cache, &h) |
| 1306 |
}) |
| 1307 |
.await?; |
| 1308 |
let mut v = d.view; |
| 1309 |
crate::web::attribute(&app, &mut [&mut v]).await; |
| d2263e29 Andy McCall ↶ |
1310 |
let files = crate::web::history::render_files(&d.files, &d.bases).into_iter().map(file_change).collect(); |
| b64e2537 Andy McCall ↶ |
1311 |
Ok(Json(ChangeDetail { |
| 1312 |
body: v.body.clone(), |
| 1313 |
change: summary(&v), |
| 1314 |
dependents: d.dependents.iter().map(|x| x.hash.clone()).collect(), |
| 1315 |
in_bookmarks: d.in_bookmarks, |
| 1316 |
in_tags: d.in_tags, |
| 1317 |
files, |
| 1318 |
})) |
| d2263e29 Andy McCall ↶ |
1319 |
} |
| 1320 |
|
| 1321 |
fn file_change(f: crate::web::history::FileRows) -> FileChange { |
| 1322 |
use crate::render::diff::Kind; |
| 1323 |
let truncated = f.lines.len() > hub_api::DIFF_LINES; |
| 1324 |
let lines = f |
| 1325 |
.lines |
| 1326 |
.into_iter() |
| 1327 |
.take(hub_api::DIFF_LINES) |
| 1328 |
.map(|l| DiffLine { |
| 1329 |
kind: match l.kind { |
| 1330 |
Kind::Context => "context", |
| 1331 |
Kind::Add => "add", |
| 1332 |
Kind::Del => "del", |
| 1333 |
Kind::Gap => "gap", |
| 1334 |
} |
| 1335 |
.into(), |
| 1336 |
old: l.old_no, |
| 1337 |
new: l.new_no, |
| 1338 |
text: l.text, |
| 1339 |
}) |
| 1340 |
.collect(); |
| 1341 |
FileChange { path: f.path, kind: f.kind, from: f.from, added: f.added, removed: f.removed, lines, truncated } |
| b64e2537 Andy McCall ↶ |
1342 |
} |
| 1343 |
|
| 1344 |
fn entry(e: &view::Entry) -> TreeEntry { |
| 1345 |
TreeEntry { |
| 1346 |
name: e.name.clone(), |
| 1347 |
path: e.path.clone(), |
| 1348 |
kind: match e.kind { |
| 1349 |
view::EntryKind::Dir => "dir", |
| 1350 |
view::EntryKind::File => "file", |
| 1351 |
view::EntryKind::Symlink => "symlink", |
| 1352 |
view::EntryKind::Subrepo => "subrepo", |
| 1353 |
} |
| 1354 |
.into(), |
| 1355 |
exec: e.exec, |
| 1356 |
size: e.size, |
| 1357 |
conflicted: e.conflicted, |
| 1358 |
} |
| 1359 |
} |
| 1360 |
|
| 1361 |
async fn tree_root( |
| 1362 |
State(app): State<Shared>, |
| 1363 |
headers: HeaderMap, |
| 1364 |
Path((owner, name, r)): Path<(String, String, String)>, |
| 1365 |
) -> Result<Json<Vec<TreeEntry>>, ApiError> { |
| 1366 |
tree(State(app), headers, Path((owner, name, r, String::new()))).await |
| 1367 |
} |
| 1368 |
|
| 1369 |
async fn tree( |
| 1370 |
State(app): State<Shared>, |
| 1371 |
headers: HeaderMap, |
| 1372 |
Path((owner, name, r, path)): Path<(String, String, String, String)>, |
| 1373 |
) -> Result<Json<Vec<TreeEntry>>, ApiError> { |
| 1374 |
let c = caller(&app, &headers).await?; |
| 1375 |
let (repo, _, _) = reach(&app, &c, &owner, &name, Access::Read).await?; |
| 1376 |
let t = app |
| 1377 |
.repos |
| 1378 |
.read(&repo, move |repo, cache| { |
| 1379 |
let target = view::resolve(repo, cache, &r)?; |
| 1380 |
view::tree(repo, cache, target, &path) |
| 1381 |
}) |
| 1382 |
.await?; |
| 1383 |
Ok(Json(t.entries.iter().map(entry).collect())) |
| 1384 |
} |
| 1385 |
|
| 1386 |
async fn file( |
| 1387 |
State(app): State<Shared>, |
| 1388 |
headers: HeaderMap, |
| 1389 |
Path((owner, name, r, path)): Path<(String, String, String, String)>, |
| 1390 |
) -> Result<Response, ApiError> { |
| 1391 |
let c = caller(&app, &headers).await?; |
| 1392 |
let (repo, _, _) = reach(&app, &c, &owner, &name, Access::Read).await?; |
| 1393 |
let limit = app.config.limits.render_limit.0; |
| 1394 |
let f = app |
| 1395 |
.repos |
| 1396 |
.read(&repo, move |repo, cache| { |
| 1397 |
let target = view::resolve(repo, cache, &r)?; |
| 1398 |
view::file(repo, cache, target, &path, limit) |
| 1399 |
}) |
| 1400 |
.await?; |
| 1401 |
Ok(crate::web::raw(f.bytes, &f.name, false)) |
| 1402 |
} |
| 1403 |
|
| 1404 |
async fn blame( |
| 1405 |
State(app): State<Shared>, |
| 1406 |
headers: HeaderMap, |
| 1407 |
Path((owner, name, r, path)): Path<(String, String, String, String)>, |
| 1408 |
) -> Result<Json<Vec<BlameLine>>, ApiError> { |
| 1409 |
let c = caller(&app, &headers).await?; |
| 1410 |
let (repo, _, _) = reach(&app, &c, &owner, &name, Access::Read).await?; |
| 1411 |
let limit = app.config.limits.render_limit.0; |
| 1412 |
let b = app |
| 1413 |
.repos |
| 1414 |
.read(&repo, move |repo, cache| { |
| 1415 |
let target = view::resolve(repo, cache, &r)?; |
| 1416 |
view::blame(repo, cache, target, &path, limit) |
| 1417 |
}) |
| 1418 |
.await?; |
| 1419 |
Ok(Json( |
| 1420 |
b.lines |
| 1421 |
.into_iter() |
| 1422 |
.map(|l| BlameLine { |
| 1423 |
line: l.line, |
| 1424 |
change: l.hash.to_hex(), |
| 1425 |
index: l.index, |
| 1426 |
author: l.author, |
| 1427 |
when_ms: l.when_ms, |
| 1428 |
text: String::from_utf8_lossy(&l.text).into_owned(), |
| 1429 |
}) |
| 1430 |
.collect(), |
| 1431 |
)) |
| 1432 |
} |
| 1433 |
|
| 1434 |
async fn conflicts( |
| 1435 |
State(app): State<Shared>, |
| 1436 |
headers: HeaderMap, |
| 1437 |
Path((owner, name)): Path<(String, String)>, |
| 1438 |
) -> Result<Json<Vec<Conflict>>, ApiError> { |
| 1439 |
let c = caller(&app, &headers).await?; |
| 1440 |
let (repo, _, _) = reach(&app, &c, &owner, &name, Access::Read).await?; |
| 1441 |
let list = app.repos.read(&repo, view::conflicts).await?; |
| 1442 |
Ok(Json( |
| 1443 |
list.into_iter() |
| 1444 |
.map(|c| Conflict { |
| 1445 |
bookmark: c.bookmark, |
| 1446 |
path: c.path, |
| 1447 |
kind: c.kind, |
| 1448 |
contributors: c.contributors.iter().map(|x| x.hash.clone()).collect(), |
| 1449 |
}) |
| 1450 |
.collect(), |
| 1451 |
)) |
| df940d75 Andy McCall ↶ |
1452 |
} |
| 1453 |
|
| 1454 |
|
| 1455 |
|
| 1456 |
async fn release_trust( |
| 1457 |
State(app): State<Shared>, |
| 1458 |
headers: HeaderMap, |
| 1459 |
Path((owner, name, tag)): Path<(String, String, String)>, |
| 1460 |
) -> Result<Json<crate::web::release_trust::ReleaseTrust>, ApiError> { |
| 1461 |
let c = caller(&app, &headers).await?; |
| 1462 |
let (repo, row, _) = reach(&app, &c, &owner, &name, Access::Read).await?; |
| 1463 |
match crate::web::release_trust::report(&app, &repo, &row, &tag).await.map_err(|m| ApiError(StatusCode::INTERNAL_SERVER_ERROR, m))? { |
| 1464 |
Some(t) => Ok(Json(t)), |
| 1465 |
None => Err(ApiError(StatusCode::NOT_FOUND, format!("no release {tag}"))), |
| 1466 |
} |
| b64e2537 Andy McCall ↶ |
1467 |
} |
| 1468 |
|
| 1469 |
async fn trust( |
| 1470 |
State(app): State<Shared>, |
| 1471 |
headers: HeaderMap, |
| 1472 |
Path((owner, name)): Path<(String, String)>, |
| 1473 |
) -> Result<Json<Trust>, ApiError> { |
| 1474 |
let c = caller(&app, &headers).await?; |
| 1475 |
let (repo, _, _) = reach(&app, &c, &owner, &name, Access::Read).await?; |
| 1476 |
let key = app.hub_key.key; |
| 1477 |
let t = app.repos.read(&repo, move |r, cache| view::trust(r, cache, &key)).await?; |
| 1478 |
Ok(Json(Trust { |
| 1479 |
policy: t.policy.map(|p| Policy { |
| 1480 |
serial: p.serial, |
| 1481 |
expires_ms: p.expires_ms, |
| 1482 |
roots: p.roots.iter().map(|k| k.key.clone()).collect(), |
| 1483 |
root_threshold: p.root_threshold, |
| 1484 |
rules: p |
| 1485 |
.rules |
| 1486 |
.iter() |
| 1487 |
.map(|r| Rule { |
| 1488 |
pattern: r.pattern.clone(), |
| 1489 |
keys: r.keys.iter().map(|k| k.key.clone()).collect(), |
| 1490 |
threshold: r.threshold, |
| 1491 |
require: r.require.clone(), |
| 1492 |
allow_conflicts: r.allow_conflicts, |
| 1493 |
}) |
| 1494 |
.collect(), |
| 1495 |
}), |
| 1496 |
signed: t.verification.signed, |
| 1497 |
sealed: t.verification.sealed, |
| 1498 |
unsigned: t.verification.unsigned, |
| 1499 |
invalid: t.verification.invalid.iter().map(|(h, _)| h.clone()).collect(), |
| 1500 |
hub_key: t.hub_key, |
| 1501 |
})) |
| 1502 |
} |
| 1503 |
|
| 1504 |
async fn pushes( |
| 1505 |
State(app): State<Shared>, |
| 1506 |
headers: HeaderMap, |
| 1507 |
Path((owner, name)): Path<(String, String)>, |
| 1508 |
) -> Result<Json<Vec<Push>>, ApiError> { |
| 1509 |
let c = caller(&app, &headers).await?; |
| 1510 |
let (_, row, _) = reach(&app, &c, &owner, &name, Access::Read).await?; |
| 1511 |
let rows = db::repos::pushes(&app.db, row.id, 200).await?; |
| 1512 |
Ok(Json( |
| 1513 |
rows.into_iter() |
| 1514 |
.map(|p| Push { |
| 1515 |
at_ms: p.at_ms, |
| 1516 |
pusher: p.pusher, |
| 1517 |
reference: p.reference, |
| 1518 |
ok: p.ok, |
| 1519 |
reason: p.reason, |
| 1520 |
old_state: p.old_state, |
| 1521 |
new_state: p.new_state, |
| 1522 |
heads: p.heads, |
| 1523 |
changes: p.changes, |
| 1524 |
}) |
| 1525 |
.collect(), |
| 1526 |
)) |
| de505df5 Andy McCall ↶ |
1527 |
} |
| 1528 |
|
| b64e2537 Andy McCall ↶ |
1529 |
|
| 1530 |
|
| d7e2c275 Andy McCall ↶ |
1531 |
|
| 1532 |
|
| 1533 |
|
| de505df5 Andy McCall ↶ |
1534 |
async fn proposals( |
| 1535 |
State(app): State<Shared>, |
| b64e2537 Andy McCall ↶ |
1536 |
headers: HeaderMap, |
| de505df5 Andy McCall ↶ |
1537 |
Path((owner, name)): Path<(String, String)>, |
| d7e2c275 Andy McCall ↶ |
1538 |
Query(q): Query<ProposalsQuery>, |
| b64e2537 Andy McCall ↶ |
1539 |
) -> Result<Json<Vec<Proposal>>, ApiError> { |
| 1540 |
let c = caller(&app, &headers).await?; |
| 1541 |
let (repo, row, _) = reach(&app, &c, &owner, &name, Access::Read).await?; |
| 0b20f1ec Andy McCall ↶ |
1542 |
let states: &[&str] = match q.state.as_deref().unwrap_or("open") { |
| 1543 |
"open" => &["open", "draft"], |
| 1544 |
"draft" => &["draft"], |
| 1545 |
"landed" => &["landed"], |
| 1546 |
"closed" => &["closed"], |
| 1547 |
"all" => &["open", "draft", "landed", "closed"], |
| 1548 |
other => return Err(ApiError(StatusCode::BAD_REQUEST, format!("state is open, draft, landed, closed or all, not {other:?}"))), |
| 1549 |
}; |
| 46b5e2c5 Andy McCall ↶ |
1550 |
|
| 1551 |
|
| 1552 |
|
| d7e2c275 Andy McCall ↶ |
1553 |
|
| 1554 |
|
| 46b5e2c5 Andy McCall ↶ |
1555 |
use futures::StreamExt; |
| d7e2c275 Andy McCall ↶ |
1556 |
let mut rows = db::proposals::list(&app.db, row.id, states).await?; |
| 1557 |
if let Some(limit) = q.limit { |
| 1558 |
rows.truncate(limit); |
| 1559 |
} |
| 46b5e2c5 Andy McCall ↶ |
1560 |
let out: Vec<Result<Proposal, ApiError>> = futures::stream::iter(rows) |
| 1561 |
.map(|p| { |
| 1562 |
let (app, repo, owner, name, id) = (app.clone(), repo.clone(), owner.clone(), name.clone(), row.id); |
| 1563 |
async move { |
| d7e2c275 Andy McCall ↶ |
1564 |
let loaded = crate::web::proposals::load_for_api(&app, &repo, p).await?; |
| 46b5e2c5 Andy McCall ↶ |
1565 |
let v = crate::web::proposals::verdict(&app, &loaded, id).await?; |
| 1566 |
Ok(crate::web::proposals::to_api(&app, &owner, &name, &loaded, &v, None).await) |
| 1567 |
} |
| 1568 |
}) |
| 1569 |
.buffered(4) |
| 1570 |
.collect() |
| 1571 |
.await; |
| 1572 |
Ok(Json(out.into_iter().collect::<Result<Vec<_>, _>>()?)) |
| de505df5 Andy McCall ↶ |
1573 |
} |
| 1574 |
|
| 1575 |
async fn proposal( |
| 1576 |
State(app): State<Shared>, |
| b64e2537 Andy McCall ↶ |
1577 |
headers: HeaderMap, |
| de505df5 Andy McCall ↶ |
1578 |
Path((owner, name, number)): Path<(String, String, i64)>, |
| b64e2537 Andy McCall ↶ |
1579 |
) -> Result<Json<Proposal>, ApiError> { |
| 1580 |
let c = caller(&app, &headers).await?; |
| 1581 |
let (repo, row, _) = reach(&app, &c, &owner, &name, Access::Read).await?; |
| 1582 |
let p = db::proposals::get(&app.db, row.id, number).await?.ok_or_else(|| not_found("no such proposal"))?; |
| de505df5 Andy McCall ↶ |
1583 |
let source_url = match p.source_repo_id { |
| 1584 |
Some(id) => db::repos::get_by_id(&app.db, id).await?.map(|r| format!("{}/{}", app.config.base_url(), r.slug())), |
| 1585 |
None => None, |
| 1586 |
}; |
| d7e2c275 Andy McCall ↶ |
1587 |
let loaded = crate::web::proposals::load_for_api(&app, &repo, p).await?; |
| de505df5 Andy McCall ↶ |
1588 |
let v = crate::web::proposals::verdict(&app, &loaded, row.id).await?; |
| 1589 |
Ok(Json(crate::web::proposals::to_api(&app, &owner, &name, &loaded, &v, source_url).await)) |
| 1f1eb06a Andy McCall ↶ |
1590 |
} |
| 1591 |
|
| 739a763a Andy McCall ↶ |
1592 |
|
| 1593 |
|
| 1594 |
|
| 1595 |
async fn edit_proposal( |
| 1596 |
State(app): State<Shared>, |
| 1597 |
headers: HeaderMap, |
| 1598 |
Path((owner, name, number)): Path<(String, String, i64)>, |
| 1599 |
Json(body): Json<hub_api::ProposalEdit>, |
| 1600 |
) -> Result<Json<Proposal>, ApiError> { |
| 1601 |
let c = caller(&app, &headers).await?; |
| 1602 |
let me = c.require("proposals:write").or_else(|_| c.require("repo:write"))?.clone(); |
| 1603 |
let (repo, row, role) = reach(&app, &c, &owner, &name, Access::Read).await?; |
| 1604 |
let p = db::proposals::get(&app.db, row.id, number).await?.ok_or_else(|| not_found("no such proposal"))?; |
| 2291f8cc Andy McCall ↶ |
1605 |
let text = body.title.is_some() || body.body.is_some(); |
| 1606 |
if text && Some(me.id) != p.author_id && role < Role::Maintain { |
| 739a763a Andy McCall ↶ |
1607 |
return Err(ApiError(StatusCode::FORBIDDEN, "only the proposal's author or a maintainer can edit it".into())); |
| 2291f8cc Andy McCall ↶ |
1608 |
} |
| 1609 |
if body.labels.is_some() && role < Role::Triage { |
| 1610 |
return Err(forbidden("setting labels needs triage access")); |
| 1611 |
} |
| 1612 |
|
| 1613 |
let labels = resolve_triage(&app, row.id, body.labels.as_deref(), None, None).await?.labels; |
| 1614 |
if text { |
| 1615 |
let title = match body.title.as_deref().map(str::trim) { |
| 1616 |
Some("") => return Err(ApiError(StatusCode::BAD_REQUEST, "a proposal needs a title".into())), |
| 1617 |
Some(t) => t, |
| 1618 |
None => p.title.as_str(), |
| 1619 |
}; |
| 1620 |
let text = body.body.as_deref().map(str::trim).unwrap_or(&p.body); |
| 1621 |
db::proposals::edit(&app.db, p.id, title, text, &p.target).await?; |
| 1622 |
db::proposals::add_event(&app.db, p.id, &me.username, "edited", "").await.ok(); |
| 739a763a Andy McCall ↶ |
1623 |
} |
| 2291f8cc Andy McCall ↶ |
1624 |
if let Some(want) = labels { |
| 1625 |
let have = db::issues::proposal_labels(&app.db, p.id).await?; |
| 1626 |
for l in &have { |
| 1627 |
if !want.iter().any(|w| w.id == l.id) { |
| 1628 |
db::issues::set_proposal_label(&app.db, p.id, l.id, false).await?; |
| 1629 |
} |
| 1630 |
} |
| 1631 |
for w in &want { |
| 1632 |
if !have.iter().any(|l| l.id == w.id) { |
| 1633 |
db::issues::set_proposal_label(&app.db, p.id, w.id, true).await?; |
| 1634 |
} |
| 1635 |
} |
| 1636 |
let names: Vec<&str> = want.iter().map(|l| l.name.as_str()).collect(); |
| 1637 |
db::proposals::add_event(&app.db, p.id, &me.username, "set labels", &names.join(", ")).await.ok(); |
| 1638 |
} |
| 09ffa7b6 Andy McCall ↶ |
1639 |
|
| 1640 |
let want = match (body.state.as_deref(), body.draft) { |
| 1641 |
(Some(s), Some(d)) if (s == "draft") != d => { |
| 1642 |
return Err(ApiError(StatusCode::BAD_REQUEST, format!("state {s:?} and draft {d} disagree"))); |
| 1643 |
} |
| 1644 |
(Some(s), _) => Some(s), |
| 1645 |
(None, Some(true)) => Some("draft"), |
| 1646 |
(None, Some(false)) => Some("open"), |
| 1647 |
(None, None) => None, |
| 1648 |
}; |
| 1649 |
if let Some(want) = want { |
| 71e65fcf Andy McCall ↶ |
1650 |
if Some(me.id) != p.author_id && role < Role::Triage { |
| 1651 |
return Err(ApiError( |
| 1652 |
StatusCode::FORBIDDEN, |
| 09ffa7b6 Andy McCall ↶ |
1653 |
"only the proposal's author or someone with triage access can close, reopen or change whether it is a draft".into(), |
| 71e65fcf Andy McCall ↶ |
1654 |
)); |
| 1655 |
} |
| 09ffa7b6 Andy McCall ↶ |
1656 |
|
| 1657 |
|
| 71e65fcf Andy McCall ↶ |
1658 |
let new_state = match (want, p.state.as_str()) { |
| 1659 |
("closed", "open" | "draft") => "closed", |
| 09ffa7b6 Andy McCall ↶ |
1660 |
("open", "closed" | "draft") => "open", |
| 1661 |
("draft", "open") => "draft", |
| 71e65fcf Andy McCall ↶ |
1662 |
(w, now) if w == now => now, |
| 09ffa7b6 Andy McCall ↶ |
1663 |
("closed" | "open" | "draft", now) => { |
| 71e65fcf Andy McCall ↶ |
1664 |
return Err(ApiError(StatusCode::CONFLICT, format!("a proposal that is {now} cannot become {want}"))) |
| 1665 |
} |
| 09ffa7b6 Andy McCall ↶ |
1666 |
_ => return Err(ApiError(StatusCode::BAD_REQUEST, "state is closed, open or draft".into())), |
| 71e65fcf Andy McCall ↶ |
1667 |
}; |
| 1668 |
if new_state != p.state { |
| 1669 |
db::proposals::set_state(&app.db, p.id, new_state, "").await?; |
| 1670 |
db::proposals::add_event(&app.db, p.id, &me.username, new_state, "").await.ok(); |
| 1671 |
crate::hooks::emit(&app, &row, &format!("proposal.{new_state}"), &me.username, serde_json::json!({ "number": number })).await; |
| 1672 |
} |
| 1673 |
} |
| 739a763a Andy McCall ↶ |
1674 |
let p = db::proposals::get(&app.db, row.id, number).await?.ok_or_else(|| not_found("no such proposal"))?; |
| 1675 |
let source_url = match p.source_repo_id { |
| 1676 |
Some(id) => db::repos::get_by_id(&app.db, id).await?.map(|r| format!("{}/{}", app.config.base_url(), r.slug())), |
| 1677 |
None => None, |
| 1678 |
}; |
| d7e2c275 Andy McCall ↶ |
1679 |
let loaded = crate::web::proposals::load_for_api(&app, &repo, p).await?; |
| 739a763a Andy McCall ↶ |
1680 |
let v = crate::web::proposals::verdict(&app, &loaded, row.id).await?; |
| 1681 |
Ok(Json(crate::web::proposals::to_api(&app, &owner, &name, &loaded, &v, source_url).await)) |
| 1682 |
} |
| 1683 |
|
| 1f1eb06a Andy McCall ↶ |
1684 |
|
| 1685 |
|
| 2a8b6216 Andy McCall ↶ |
1686 |
|
| 1687 |
|
| 1f1eb06a Andy McCall ↶ |
1688 |
async fn land_proposal( |
| 1689 |
State(app): State<Shared>, |
| 1690 |
headers: HeaderMap, |
| 1691 |
Path((owner, name, number)): Path<(String, String, i64)>, |
| 2a8b6216 Andy McCall ↶ |
1692 |
body: axum::body::Bytes, |
| 1f1eb06a Andy McCall ↶ |
1693 |
) -> Result<Json<Proposal>, ApiError> { |
| 1694 |
let c = caller(&app, &headers).await?; |
| 1695 |
let me = c.require("repo:write")?.clone(); |
| 2a8b6216 Andy McCall ↶ |
1696 |
let over_checks: Option<String> = if body.iter().all(u8::is_ascii_whitespace) { |
| 1697 |
None |
| 1698 |
} else { |
| 1699 |
serde_json::from_slice::<serde_json::Value>(&body) |
| 1700 |
.map_err(|_| ApiError(StatusCode::BAD_REQUEST, "the body is JSON: {} or {\"over_checks\": \"reason\"}".into()))? |
| 1701 |
.get("over_checks") |
| 1702 |
.and_then(|v| v.as_str()) |
| 1703 |
.map(String::from) |
| 1704 |
}; |
| 1705 |
let need = if over_checks.is_some() { Access::Maintain } else { Access::Write }; |
| 1706 |
let (repo, row, _) = reach(&app, &c, &owner, &name, need).await?; |
| 0b20f1ec Andy McCall ↶ |
1707 |
let via = format!("api (token {})", c.token); |
| 2a8b6216 Andy McCall ↶ |
1708 |
match crate::web::proposals::land_as(&app, &repo, &row, &me, number, &via, false, over_checks.as_deref()).await { |
| 1f1eb06a Andy McCall ↶ |
1709 |
Ok(_) => proposal(State(app), headers, Path((owner, name, number))).await, |
| 1710 |
Err(crate::web::proposals::Landing::NotFound) => Err(not_found("no such proposal")), |
| 1711 |
Err(crate::web::proposals::Landing::Refused(m)) => Err(ApiError(StatusCode::CONFLICT, m)), |
| 1712 |
} |
| d23464c0 Andy McCall ↶ |
1713 |
} |
| 1714 |
|
| 86a69b53 Andy McCall ↶ |
1715 |
|
| 1716 |
|
| 1717 |
async fn auto_land_on( |
| 1718 |
State(app): State<Shared>, |
| 1719 |
headers: HeaderMap, |
| 1720 |
Path((owner, name, number)): Path<(String, String, i64)>, |
| 1721 |
) -> Result<Json<Proposal>, ApiError> { |
| 1722 |
auto_land_set(&app, &headers, &owner, &name, number, true).await?; |
| 1723 |
proposal(State(app), headers, Path((owner, name, number))).await |
| 1724 |
} |
| 1725 |
|
| 1726 |
|
| 1727 |
async fn auto_land_off( |
| 1728 |
State(app): State<Shared>, |
| 1729 |
headers: HeaderMap, |
| 1730 |
Path((owner, name, number)): Path<(String, String, i64)>, |
| 1731 |
) -> Result<Json<Proposal>, ApiError> { |
| 1732 |
auto_land_set(&app, &headers, &owner, &name, number, false).await?; |
| 1733 |
proposal(State(app), headers, Path((owner, name, number))).await |
| 1734 |
} |
| 1735 |
|
| 1736 |
async fn auto_land_set(app: &Shared, headers: &HeaderMap, owner: &str, name: &str, number: i64, on: bool) -> Result<(), ApiError> { |
| 1737 |
let c = caller(app, headers).await?; |
| 1738 |
let me = c.require("repo:write")?.clone(); |
| 1739 |
let (_, row, _) = reach(app, &c, owner, name, Access::Write).await?; |
| 1740 |
let p = db::proposals::get(&app.db, row.id, number).await?.ok_or_else(|| not_found("no such proposal"))?; |
| 1741 |
if !p.is_open() { |
| 1742 |
return Err(ApiError(StatusCode::CONFLICT, format!("the proposal is {}", p.state))); |
| 1743 |
} |
| 1744 |
crate::autoland::set(app, &row, &p, &me, on).await?; |
| 1745 |
Ok(()) |
| 1746 |
} |
| 1747 |
|
| 3f02e5ea Andy McCall ↶ |
1748 |
|
| 1749 |
async fn proposal_files( |
| 1750 |
State(app): State<Shared>, |
| 1751 |
headers: HeaderMap, |
| 1752 |
Path((owner, name, number)): Path<(String, String, i64)>, |
| 1753 |
) -> Result<Json<Vec<hub_api::ProposalFile>>, ApiError> { |
| 1754 |
let c = caller(&app, &headers).await?; |
| 1755 |
let (repo, row, _) = reach(&app, &c, &owner, &name, Access::Read).await?; |
| 1756 |
let p = db::proposals::get(&app.db, row.id, number).await?.ok_or_else(|| not_found("no such proposal"))?; |
| 1757 |
let loaded = crate::web::proposals::load(&app, &repo, p).await?; |
| 1758 |
Ok(Json( |
| 1759 |
loaded |
| 1760 |
.files |
| 1761 |
.iter() |
| 1762 |
.map(|f| hub_api::ProposalFile { |
| 1763 |
path: f.path.clone(), |
| 1764 |
from: f.from.clone(), |
| 1765 |
kind: f.kind.clone(), |
| 1766 |
added: f.added, |
| 1767 |
removed: f.removed, |
| 1768 |
}) |
| 1769 |
.collect(), |
| 1770 |
)) |
| 1771 |
} |
| 1772 |
|
| 1773 |
|
| 1774 |
|
| 1775 |
|
| 1776 |
async fn proposal_content( |
| 1777 |
State(app): State<Shared>, |
| 1778 |
headers: HeaderMap, |
| 1779 |
Path((owner, name, number, side, path)): Path<(String, String, i64, String, String)>, |
| 1780 |
) -> Result<Response, ApiError> { |
| 1781 |
let c = caller(&app, &headers).await?; |
| 1782 |
let (repo, row, _) = reach(&app, &c, &owner, &name, Access::Read).await?; |
| 1783 |
let p = db::proposals::get(&app.db, row.id, number).await?.ok_or_else(|| not_found("no such proposal"))?; |
| 3571c519 Andy McCall ↶ |
1784 |
let loaded = crate::web::proposals::load_summary(&app, &repo, p).await?; |
| 3f02e5ea Andy McCall ↶ |
1785 |
let heads = match side.as_str() { |
| 1786 |
"base" => loaded.target_heads, |
| 1787 |
"head" => loaded.heads, |
| 1788 |
_ => return Err(ApiError(StatusCode::BAD_REQUEST, "the side is base or head".into())), |
| 1789 |
}; |
| 1790 |
let limit = app.config.limits.render_limit.0; |
| 1791 |
let target = view::RefTarget { label: side, kind: view::RefKind::Change, heads }; |
| 1792 |
let f = app.repos.read(&repo, move |repo, cache| view::file(repo, cache, target, &path, limit)).await?; |
| 1793 |
Ok(crate::web::raw(f.bytes, &f.name, false)) |
| 1794 |
} |
| 1795 |
|
| b64e2537 Andy McCall ↶ |
1796 |
async fn create_proposal( |
| 1797 |
State(app): State<Shared>, |
| 1798 |
headers: HeaderMap, |
| 1799 |
Path((owner, name)): Path<(String, String)>, |
| 1800 |
Json(body): Json<NewProposal>, |
| 1801 |
) -> Result<(StatusCode, Json<Proposal>), ApiError> { |
| 1802 |
let c = caller(&app, &headers).await?; |
| 1803 |
let me = c.require("proposals:write").or_else(|_| c.require("repo:write"))?.clone(); |
| 1804 |
let (repo, row, _) = reach(&app, &c, &owner, &name, Access::Read).await?; |
| 1805 |
let created = |
| 1806 |
crate::web::proposals::open_proposal(&app, &repo, &row, &me, &body.title, &body.body, &body.target, &body.source, body.draft) |
| 1807 |
.await |
| 1808 |
.map_err(|e| ApiError(StatusCode::BAD_REQUEST, e))?; |
| 3571c519 Andy McCall ↶ |
1809 |
let loaded = crate::web::proposals::load_summary(&app, &repo, created).await?; |
| b64e2537 Andy McCall ↶ |
1810 |
let v = crate::web::proposals::verdict(&app, &loaded, row.id).await?; |
| 1811 |
Ok((StatusCode::CREATED, Json(crate::web::proposals::to_api(&app, &owner, &name, &loaded, &v, None).await))) |
| 1812 |
} |
| d23464c0 Andy McCall ↶ |
1813 |
|
| b64e2537 Andy McCall ↶ |
1814 |
fn comment_of(c: &db::proposals::CommentRow) -> Comment { |
| 1815 |
Comment { |
| 1816 |
id: c.id, |
| 1817 |
author: c.author.clone(), |
| 1818 |
body: c.body.clone(), |
| 1819 |
created_ms: c.created_ms, |
| 1820 |
path: if c.path.is_empty() { None } else { Some(c.path.clone()) }, |
| 1821 |
anchor: if c.anchor_change.is_empty() { |
| 1822 |
None |
| 1823 |
} else { |
| 1824 |
Some(Atom { change: c.anchor_change.clone(), index: c.anchor_index as u32 }) |
| 1825 |
}, |
| c0fac31d Andy McCall ↶ |
1826 |
line: None, |
| b64e2537 Andy McCall ↶ |
1827 |
resolved: c.resolved, |
| d23464c0 Andy McCall ↶ |
1828 |
} |
| 1829 |
} |
| 1830 |
|
| b64e2537 Andy McCall ↶ |
1831 |
async fn proposal_comments( |
| 1832 |
State(app): State<Shared>, |
| 1833 |
headers: HeaderMap, |
| 1834 |
Path((owner, name, number)): Path<(String, String, i64)>, |
| 1835 |
) -> Result<Json<Vec<Comment>>, ApiError> { |
| 1836 |
let c = caller(&app, &headers).await?; |
| 1837 |
let (_, row, _) = reach(&app, &c, &owner, &name, Access::Read).await?; |
| 1838 |
let p = db::proposals::get(&app.db, row.id, number).await?.ok_or_else(|| not_found("no such proposal"))?; |
| c0fac31d Andy McCall ↶ |
1839 |
let mut out: Vec<Comment> = db::proposals::comments(&app.db, p.id).await?.iter().map(comment_of).collect(); |
| 1840 |
|
| 1841 |
let paths: std::collections::BTreeSet<String> = out.iter().filter(|c| c.anchor.is_some()).filter_map(|c| c.path.clone()).collect(); |
| 1842 |
if !paths.is_empty() { |
| 1843 |
let repo = RepoName::new(&owner, &name).ok_or_else(|| not_found("no such repository"))?; |
| 3571c519 Andy McCall ↶ |
1844 |
let heads = crate::web::proposals::load_summary(&app, &repo, p).await?.heads; |
| c0fac31d Andy McCall ↶ |
1845 |
let lines = app |
| 1846 |
.repos |
| 1847 |
.read(&repo, move |r, _| { |
| 1848 |
let mut at = std::collections::HashMap::new(); |
| 1849 |
for path in paths { |
| 1850 |
|
| 1851 |
for l in r.blame_in(&path, &heads).unwrap_or_default() { |
| 1852 |
at.insert((path.clone(), l.hash.to_hex(), l.index), l.line); |
| 1853 |
} |
| 1854 |
} |
| 1855 |
Ok(at) |
| 1856 |
}) |
| 1857 |
.await?; |
| 1858 |
for c in &mut out { |
| 1859 |
if let (Some(path), Some(a)) = (&c.path, &c.anchor) { |
| 1860 |
c.line = lines.get(&(path.clone(), a.change.clone(), a.index)).copied(); |
| 1861 |
} |
| 1862 |
} |
| 1863 |
} |
| 1864 |
Ok(Json(out)) |
| b64e2537 Andy McCall ↶ |
1865 |
} |
| 1866 |
|
| 1867 |
async fn proposal_comment( |
| 1868 |
State(app): State<Shared>, |
| 1869 |
headers: HeaderMap, |
| 1870 |
Path((owner, name, number)): Path<(String, String, i64)>, |
| 1871 |
Json(body): Json<NewComment>, |
| 1872 |
) -> Result<(StatusCode, Json<Comment>), ApiError> { |
| 1873 |
let c = caller(&app, &headers).await?; |
| 1874 |
let me = c.require("proposals:write").or_else(|_| c.require("repo:write"))?.clone(); |
| 1875 |
let (_, row, _) = reach(&app, &c, &owner, &name, Access::Read).await?; |
| 1876 |
let p = db::proposals::get(&app.db, row.id, number).await?.ok_or_else(|| not_found("no such proposal"))?; |
| 1877 |
if body.body.trim().is_empty() { |
| 1878 |
return Err(ApiError(StatusCode::BAD_REQUEST, "an empty comment says nothing".into())); |
| 1879 |
} |
| 3f4b0ea6 Andy McCall ↶ |
1880 |
let (repo, _) = (RepoName::new(&owner, &name).ok_or_else(|| not_found("no such repository"))?, ()); |
| 1881 |
let anchor = match (body.path.as_deref().map(|x| x.trim_matches('/')), body.line) { |
| 1882 |
(Some(path), Some(line)) if !path.is_empty() => { |
| 1883 |
let loaded = crate::web::proposals::load(&app, &repo, p.clone()).await?; |
| 1884 |
let (heads, file) = (loaded.heads.clone(), path.to_string()); |
| 1885 |
let atom = app |
| 1886 |
.repos |
| 1887 |
.read(&repo, move |r, cache| { |
| 1888 |
let projected = cache.load(r, &heads)?; |
| 1889 |
Ok(crate::repos::proposals::atom_at(&projected, &file, line).map(|(h, i)| (h.to_hex(), i))) |
| 1890 |
}) |
| 1891 |
.await? |
| 1892 |
.ok_or_else(|| ApiError(StatusCode::BAD_REQUEST, format!("{path}:{line} is not a line of the projected state")))?; |
| 1893 |
Some((path.to_string(), atom)) |
| 1894 |
} |
| 1895 |
_ => None, |
| 1896 |
}; |
| 1897 |
let row_c = db::proposals::add_comment( |
| 1898 |
&app.db, |
| 1899 |
p.id, |
| 1900 |
Some(me.id), |
| 1901 |
&me.username, |
| 1902 |
body.body.trim(), |
| 1903 |
anchor.as_ref().map(|(path, _)| path.as_str()).unwrap_or(""), |
| 1904 |
anchor.as_ref().map(|(_, (h, i))| (h.as_str(), *i as i64)), |
| 1905 |
) |
| 1906 |
.await?; |
| b64e2537 Andy McCall ↶ |
1907 |
crate::notify::deliver( |
| 1908 |
&app, |
| 1909 |
crate::notify::Event { |
| 1910 |
kind: "proposal.comment", |
| 1911 |
title: format!("{owner}/{name}#{number}: {}", p.title), |
| 1912 |
url: format!("/{owner}/{name}/proposal/{number}"), |
| 1913 |
actor: &me, |
| 1914 |
repo_id: row.id, |
| 1915 |
thread: Some(("proposal", p.id)), |
| 1916 |
mention_text: &body.body, |
| 1917 |
direct: p.author_id.into_iter().collect(), |
| 1918 |
}, |
| 1919 |
) |
| 1920 |
.await; |
| 1921 |
crate::hooks::emit( |
| 1922 |
&app, |
| 1923 |
&row, |
| 1924 |
"comment.proposal", |
| 1925 |
&me.username, |
| 1926 |
serde_json::json!({ "number": number, "comment": comment_of(&row_c) }), |
| 1927 |
) |
| 1928 |
.await; |
| c0fac31d Andy McCall ↶ |
1929 |
let mut created = comment_of(&row_c); |
| 1930 |
created.line = created.anchor.as_ref().and(body.line); |
| 1931 |
Ok((StatusCode::CREATED, Json(created))) |
| b64e2537 Andy McCall ↶ |
1932 |
} |
| 1933 |
|
| 1934 |
async fn proposal_reviews( |
| 1935 |
State(app): State<Shared>, |
| 1936 |
headers: HeaderMap, |
| 1937 |
Path((owner, name, number)): Path<(String, String, i64)>, |
| 1938 |
) -> Result<Json<Vec<Review>>, ApiError> { |
| 1939 |
let c = caller(&app, &headers).await?; |
| 1940 |
let (repo, row, _) = reach(&app, &c, &owner, &name, Access::Read).await?; |
| 1941 |
let p = db::proposals::get(&app.db, row.id, number).await?.ok_or_else(|| not_found("no such proposal"))?; |
| 3571c519 Andy McCall ↶ |
1942 |
let loaded = crate::web::proposals::load_summary(&app, &repo, p).await?; |
| b64e2537 Andy McCall ↶ |
1943 |
let v = crate::web::proposals::verdict(&app, &loaded, row.id).await?; |
| 1944 |
Ok(Json( |
| 1945 |
v.reviews |
| 1946 |
.into_iter() |
| 1947 |
.map(|r| Review { |
| 1948 |
id: r.row.id, |
| 1949 |
author: r.row.author, |
| 1950 |
verdict: r.row.verdict, |
| 1951 |
body: r.row.body, |
| 1952 |
sealed: r.sealed, |
| 1953 |
created_ms: r.row.created_ms, |
| 7d2eb590 Andy McCall ↶ |
1954 |
via: r.row.via, |
| b64e2537 Andy McCall ↶ |
1955 |
}) |
| 1956 |
.collect(), |
| 1957 |
)) |
| 1958 |
} |
| 1959 |
|
| 1960 |
async fn proposal_review( |
| 1961 |
State(app): State<Shared>, |
| 1962 |
headers: HeaderMap, |
| 1963 |
Path((owner, name, number)): Path<(String, String, i64)>, |
| 1964 |
Json(body): Json<NewReview>, |
| 1965 |
) -> Result<(StatusCode, Json<Review>), ApiError> { |
| 1966 |
let c = caller(&app, &headers).await?; |
| 1967 |
let me = c.require("proposals:write").or_else(|_| c.require("repo:write"))?.clone(); |
| 1968 |
let (_, row, _) = reach(&app, &c, &owner, &name, Access::Read).await?; |
| 1969 |
let p = db::proposals::get(&app.db, row.id, number).await?.ok_or_else(|| not_found("no such proposal"))?; |
| 1970 |
if !matches!(body.verdict.as_str(), "comment" | "changes" | "approve") { |
| 1971 |
return Err(ApiError(StatusCode::BAD_REQUEST, "verdict is comment, changes or approve".into())); |
| 1972 |
} |
| 1973 |
if body.verdict == "approve" && Some(me.id) == p.author_id { |
| 1974 |
return Err(forbidden("you cannot approve your own proposal")); |
| 1975 |
} |
| 1976 |
let r = db::proposals::add_review(&app.db, p.id, me.id, &me.username, &body.verdict, body.body.trim()).await?; |
| 1977 |
db::proposals::add_event(&app.db, p.id, &me.username, &format!("review.{}", body.verdict), "").await.ok(); |
| cc1cd197 Andy McCall ↶ |
1978 |
crate::web::proposals::reviewed(&app, &row, &p, &me, &body.verdict).await; |
| b64e2537 Andy McCall ↶ |
1979 |
crate::hooks::emit(&app, &row, "review", &me.username, serde_json::json!({ "number": number, "verdict": body.verdict })).await; |
| 1980 |
Ok(( |
| 1981 |
StatusCode::CREATED, |
| 7d2eb590 Andy McCall ↶ |
1982 |
Json(Review { id: r.id, author: r.author, verdict: r.verdict, body: r.body, sealed: false, created_ms: r.created_ms, via: r.via }), |
| b64e2537 Andy McCall ↶ |
1983 |
)) |
| 1984 |
} |
| 1985 |
|
| cc1cd197 Andy McCall ↶ |
1986 |
|
| 1987 |
|
| 1988 |
async fn request_reviewers( |
| 1989 |
State(app): State<Shared>, |
| 1990 |
headers: HeaderMap, |
| 1991 |
Path((owner, name, number)): Path<(String, String, i64)>, |
| 1992 |
Json(body): Json<ReviewRequest>, |
| 1993 |
) -> Result<Json<Vec<String>>, ApiError> { |
| 1994 |
let c = caller(&app, &headers).await?; |
| 1995 |
let me = c.require("proposals:write").or_else(|_| c.require("repo:write"))?.clone(); |
| 1996 |
let (_, row, role) = reach(&app, &c, &owner, &name, Access::Read).await?; |
| 1997 |
let p = db::proposals::get(&app.db, row.id, number).await?.ok_or_else(|| not_found("no such proposal"))?; |
| 1998 |
if Some(me.id) != p.author_id && role < Role::Write { |
| 1999 |
return Err(forbidden("only the author or a writer asks for reviews")); |
| 2000 |
} |
| 2001 |
if !p.is_open() { |
| 2002 |
return Err(ApiError(StatusCode::CONFLICT, "the proposal is not open".into())); |
| 2003 |
} |
| 2004 |
crate::web::proposals::request_reviewers(&app, &row, &p, &me, &body.reviewers) |
| 2005 |
.await |
| 2006 |
.map_err(|e| ApiError(StatusCode::UNPROCESSABLE_ENTITY, e))?; |
| 2007 |
Ok(Json(db::proposals::review_requests(&app.db, p.id).await?)) |
| 2008 |
} |
| 2009 |
|
| 2010 |
|
| 2011 |
async fn withdraw_reviewer( |
| 2012 |
State(app): State<Shared>, |
| 2013 |
headers: HeaderMap, |
| 2014 |
Path((owner, name, number, username)): Path<(String, String, i64, String)>, |
| 2015 |
) -> Result<StatusCode, ApiError> { |
| 2016 |
let c = caller(&app, &headers).await?; |
| 2017 |
let me = c.require("proposals:write").or_else(|_| c.require("repo:write"))?.clone(); |
| 2018 |
let (_, row, role) = reach(&app, &c, &owner, &name, Access::Read).await?; |
| 2019 |
let p = db::proposals::get(&app.db, row.id, number).await?.ok_or_else(|| not_found("no such proposal"))?; |
| 2020 |
if Some(me.id) != p.author_id && role < Role::Write { |
| 2021 |
return Err(forbidden("only the author or a writer withdraws review requests")); |
| 2022 |
} |
| 2023 |
let a = db::accounts::account_by_name(&app.db, &username).await?.ok_or_else(|| not_found("no such account"))?; |
| 2024 |
if db::proposals::unrequest_review(&app.db, p.id, a.id).await? { |
| 2025 |
db::proposals::add_event(&app.db, p.id, &me.username, "review request withdrawn", &a.username).await.ok(); |
| 2026 |
} |
| 2027 |
Ok(StatusCode::NO_CONTENT) |
| 2028 |
} |
| 2029 |
|
| b64e2537 Andy McCall ↶ |
2030 |
async fn proposal_checks( |
| 2031 |
State(app): State<Shared>, |
| 2032 |
headers: HeaderMap, |
| 2033 |
Path((owner, name, number)): Path<(String, String, i64)>, |
| 2034 |
) -> Result<Json<Vec<Check>>, ApiError> { |
| 2035 |
let c = caller(&app, &headers).await?; |
| 2036 |
let (repo, row, _) = reach(&app, &c, &owner, &name, Access::Read).await?; |
| 2037 |
let p = db::proposals::get(&app.db, row.id, number).await?.ok_or_else(|| not_found("no such proposal"))?; |
| 3571c519 Andy McCall ↶ |
2038 |
let loaded = crate::web::proposals::load_summary(&app, &repo, p).await?; |
| b64e2537 Andy McCall ↶ |
2039 |
Ok(Json(db::hooks::checks_for_state(&app.db, row.id, &loaded.state).await?.iter().map(check_of).collect())) |
| 2040 |
} |
| 2041 |
|
| 2042 |
|
| 2043 |
|
| 2044 |
async fn issue_of(app: &Shared, row: &db::repos::RepoRow, i: &db::issues::IssueRow) -> Result<Issue, ApiError> { |
| 2045 |
let labels = db::issues::issue_labels(&app.db, i.id) |
| 2046 |
.await? |
| 2047 |
.into_iter() |
| 2048 |
.map(|l| Label { name: l.name, colour: l.colour, description: l.description }) |
| 2049 |
.collect(); |
| 2050 |
let assignees = db::issues::assignees(&app.db, i.id).await?; |
| 2051 |
let milestone = match i.milestone_id { |
| 2052 |
Some(id) => db::issues::milestone(&app.db, id).await?.map(|m| m.title), |
| 2053 |
None => None, |
| 2054 |
}; |
| 5d90e0e0 Andy McCall |
2055 |
let comments: i64 = sqlx::query_scalar("SELECT COUNT(*) FROM issue_comments WHERE issue_id = $1").bind(i.id).fetch_one(&app.db).await?; |
| b64e2537 Andy McCall ↶ |
2056 |
Ok(Issue { |
| 2057 |
number: i.number, |
| 2058 |
title: i.title.clone(), |
| 2059 |
body: i.body.clone(), |
| 2060 |
author: i.author.clone(), |
| 2061 |
state: i.state.clone(), |
| 2062 |
reason: i.reason.clone(), |
| 2063 |
labels, |
| 2064 |
assignees, |
| 2065 |
milestone, |
| 2066 |
comments, |
| 2067 |
locked: i.locked, |
| 2068 |
pinned: i.pinned, |
| 2069 |
created_ms: i.created_ms, |
| 2070 |
updated_ms: i.updated_ms, |
| 2071 |
closed_ms: i.closed_ms, |
| 2072 |
url: format!("{}/{}/issue/{}", app.config.base_url(), row.slug(), i.number), |
| 2073 |
}) |
| 2074 |
} |
| 2075 |
|
| 2076 |
#[derive(Deserialize)] |
| 2077 |
struct IssuesQuery { |
| 2078 |
state: Option<String>, |
| d7e2c275 Andy McCall ↶ |
2079 |
} |
| 2080 |
|
| 2081 |
#[derive(Deserialize)] |
| 2082 |
struct ProposalsQuery { |
| 2083 |
state: Option<String>, |
| 2084 |
limit: Option<usize>, |
| b64e2537 Andy McCall ↶ |
2085 |
} |
| 2086 |
|
| 2087 |
async fn issues( |
| 2088 |
State(app): State<Shared>, |
| 2089 |
headers: HeaderMap, |
| 2090 |
Path((owner, name)): Path<(String, String)>, |
| 2091 |
Query(q): Query<IssuesQuery>, |
| 2092 |
) -> Result<Json<Vec<Issue>>, ApiError> { |
| 2093 |
let c = caller(&app, &headers).await?; |
| 2094 |
let (_, row, _) = reach(&app, &c, &owner, &name, Access::Read).await?; |
| 2095 |
let state = q.state.unwrap_or_else(|| "open".into()); |
| 2096 |
let mut out = Vec::new(); |
| 2097 |
for i in db::issues::list(&app.db, row.id).await? { |
| 2098 |
if state == "all" || i.state == state { |
| 2099 |
out.push(issue_of(&app, &row, &i).await?); |
| d23464c0 Andy McCall ↶ |
2100 |
} |
| 2101 |
} |
| b64e2537 Andy McCall ↶ |
2102 |
Ok(Json(out)) |
| d23464c0 Andy McCall ↶ |
2103 |
} |
| 2104 |
|
| b64e2537 Andy McCall ↶ |
2105 |
async fn create_issue( |
| 2106 |
State(app): State<Shared>, |
| 2107 |
headers: HeaderMap, |
| 2108 |
Path((owner, name)): Path<(String, String)>, |
| 2109 |
Json(body): Json<NewIssue>, |
| 2110 |
) -> Result<(StatusCode, Json<Issue>), ApiError> { |
| 2111 |
let c = caller(&app, &headers).await?; |
| 2112 |
let me = c.require("issues:write").or_else(|_| c.require("repo:write"))?.clone(); |
| 76f262e1 Andy McCall ↶ |
2113 |
let (_, row, role) = reach(&app, &c, &owner, &name, Access::Read).await?; |
| b64e2537 Andy McCall ↶ |
2114 |
if body.title.trim().is_empty() { |
| 2115 |
return Err(ApiError(StatusCode::BAD_REQUEST, "an issue needs a title".into())); |
| d23464c0 Andy McCall ↶ |
2116 |
} |
| 76f262e1 Andy McCall ↶ |
2117 |
let triage = !body.labels.is_empty() || !body.assignees.is_empty() || body.milestone.is_some(); |
| 2118 |
if triage && role < Role::Triage { |
| 2119 |
return Err(forbidden("setting labels, assignees or a milestone needs triage access")); |
| 2120 |
} |
| 2121 |
|
| 2122 |
resolve_triage(&app, row.id, Some(&body.labels), Some(&body.assignees), body.milestone.as_deref()).await?; |
| b64e2537 Andy McCall ↶ |
2123 |
let i = db::issues::create( |
| 2124 |
&app.db, |
| 2125 |
db::issues::NewIssue { |
| 2126 |
repo_id: row.id, |
| 2127 |
title: body.title.trim(), |
| 2128 |
body: body.body.trim(), |
| 2129 |
author_id: Some(me.id), |
| 2130 |
author: &me.username, |
| 2131 |
}, |
| 2132 |
) |
| 2133 |
.await?; |
| 2134 |
db::issues::add_event(&app.db, i.id, &me.username, "opened", "").await.ok(); |
| 76f262e1 Andy McCall ↶ |
2135 |
if triage { |
| 2136 |
let t = resolve_triage(&app, row.id, Some(&body.labels), Some(&body.assignees), body.milestone.as_deref()).await?; |
| 2137 |
apply_triage(&app, &i, &me, t).await?; |
| 2138 |
} |
| 2139 |
let i = db::issues::get(&app.db, row.id, i.number).await?.unwrap_or(i); |
| b64e2537 Andy McCall ↶ |
2140 |
crate::web::issues::reindex(&app, row.id, &i).await; |
| 2141 |
let api = issue_of(&app, &row, &i).await?; |
| 2142 |
crate::notify::deliver( |
| 2143 |
&app, |
| 2144 |
crate::notify::Event { |
| 2145 |
kind: "issue.opened", |
| 2146 |
title: format!("{owner}/{name}#{}: {}", i.number, i.title), |
| 2147 |
url: format!("/{owner}/{name}/issue/{}", i.number), |
| 2148 |
actor: &me, |
| 2149 |
repo_id: row.id, |
| 2150 |
thread: Some(("issue", i.id)), |
| 2151 |
mention_text: &body.body, |
| 2152 |
direct: vec![], |
| 2153 |
}, |
| 2154 |
) |
| 2155 |
.await; |
| 2156 |
crate::hooks::emit(&app, &row, "issue.opened", &me.username, serde_json::json!({ "issue": api })).await; |
| 2157 |
Ok((StatusCode::CREATED, Json(api))) |
| 2158 |
} |
| 2159 |
|
| 2160 |
async fn issue( |
| 2161 |
State(app): State<Shared>, |
| 2162 |
headers: HeaderMap, |
| 2163 |
Path((owner, name, number)): Path<(String, String, i64)>, |
| 2164 |
) -> Result<Json<Issue>, ApiError> { |
| 2165 |
let c = caller(&app, &headers).await?; |
| 2166 |
let (_, row, _) = reach(&app, &c, &owner, &name, Access::Read).await?; |
| 2167 |
let i = db::issues::get(&app.db, row.id, number).await?.ok_or_else(|| not_found("no such issue"))?; |
| 2168 |
Ok(Json(issue_of(&app, &row, &i).await?)) |
| 2169 |
} |
| 2170 |
|
| 2171 |
async fn issue_state( |
| 2172 |
State(app): State<Shared>, |
| 2173 |
headers: HeaderMap, |
| 2174 |
Path((owner, name, number)): Path<(String, String, i64)>, |
| 2175 |
Json(body): Json<IssueStateChange>, |
| 2176 |
) -> Result<Json<Issue>, ApiError> { |
| 2177 |
let c = caller(&app, &headers).await?; |
| 2178 |
let me = c.require("issues:write").or_else(|_| c.require("repo:write"))?.clone(); |
| 2179 |
let (_, row, role) = reach(&app, &c, &owner, &name, Access::Read).await?; |
| 2180 |
let i = db::issues::get(&app.db, row.id, number).await?.ok_or_else(|| not_found("no such issue"))?; |
| 2181 |
if role < Role::Triage && Some(me.id) != i.author_id { |
| 2182 |
return Err(forbidden("only the author or triage may change the state")); |
| 2183 |
} |
| 2184 |
let (state, reason) = match body.state.as_str() { |
| 2185 |
"closed" => ("closed", if body.reason == "not_planned" { "not_planned" } else { "completed" }), |
| 2186 |
"open" => ("open", ""), |
| 2187 |
_ => return Err(ApiError(StatusCode::BAD_REQUEST, "state is open or closed".into())), |
| 2188 |
}; |
| 2189 |
db::issues::set_state(&app.db, i.id, state, reason).await?; |
| 2190 |
db::issues::add_event(&app.db, i.id, &me.username, if state == "closed" { "closed" } else { "reopened" }, "").await.ok(); |
| 2191 |
let fresh = db::issues::get(&app.db, row.id, number).await?.unwrap_or(i); |
| 2192 |
let api = issue_of(&app, &row, &fresh).await?; |
| 2193 |
crate::hooks::emit( |
| 2194 |
&app, |
| 2195 |
&row, |
| 2196 |
if state == "closed" { "issue.closed" } else { "issue.reopened" }, |
| 2197 |
&me.username, |
| 2198 |
serde_json::json!({ "issue": api }), |
| 2199 |
) |
| 2200 |
.await; |
| 2201 |
Ok(Json(api)) |
| 2202 |
} |
| 2203 |
|
| 2204 |
async fn issue_comments( |
| 2205 |
State(app): State<Shared>, |
| 2206 |
headers: HeaderMap, |
| 2207 |
Path((owner, name, number)): Path<(String, String, i64)>, |
| 2208 |
) -> Result<Json<Vec<Comment>>, ApiError> { |
| 2209 |
let c = caller(&app, &headers).await?; |
| 2210 |
let (_, row, _) = reach(&app, &c, &owner, &name, Access::Read).await?; |
| 2211 |
let i = db::issues::get(&app.db, row.id, number).await?.ok_or_else(|| not_found("no such issue"))?; |
| 2212 |
Ok(Json( |
| 2213 |
db::issues::comments(&app.db, i.id) |
| 2214 |
.await? |
| 2215 |
.into_iter() |
| 2216 |
.map(|c| Comment { |
| 2217 |
id: c.id, |
| 2218 |
author: c.author, |
| 2219 |
body: c.body, |
| 2220 |
created_ms: c.created_ms, |
| 2221 |
path: None, |
| 2222 |
anchor: None, |
| c0fac31d Andy McCall ↶ |
2223 |
line: None, |
| b64e2537 Andy McCall ↶ |
2224 |
resolved: false, |
| 2225 |
}) |
| 2226 |
.collect(), |
| 2227 |
)) |
| 2228 |
} |
| 2229 |
|
| 2230 |
async fn issue_comment( |
| 2231 |
State(app): State<Shared>, |
| 2232 |
headers: HeaderMap, |
| 2233 |
Path((owner, name, number)): Path<(String, String, i64)>, |
| 2234 |
Json(body): Json<NewComment>, |
| 2235 |
) -> Result<(StatusCode, Json<Comment>), ApiError> { |
| 2236 |
let c = caller(&app, &headers).await?; |
| 2237 |
let me = c.require("issues:write").or_else(|_| c.require("repo:write"))?.clone(); |
| 2238 |
let (_, row, role) = reach(&app, &c, &owner, &name, Access::Read).await?; |
| 2239 |
let i = db::issues::get(&app.db, row.id, number).await?.ok_or_else(|| not_found("no such issue"))?; |
| 2240 |
if i.locked && role < Role::Triage { |
| 2241 |
return Err(forbidden("this issue is locked")); |
| 2242 |
} |
| 2243 |
if body.body.trim().is_empty() { |
| 2244 |
return Err(ApiError(StatusCode::BAD_REQUEST, "an empty comment says nothing".into())); |
| 2245 |
} |
| 2246 |
let cm = db::issues::add_comment(&app.db, i.id, Some(me.id), &me.username, body.body.trim()).await?; |
| 2247 |
crate::web::issues::reindex(&app, row.id, &i).await; |
| 2248 |
crate::notify::deliver( |
| 2249 |
&app, |
| 2250 |
crate::notify::Event { |
| 2251 |
kind: "issue.comment", |
| 2252 |
title: format!("{owner}/{name}#{number}: {}", i.title), |
| 2253 |
url: format!("/{owner}/{name}/issue/{number}"), |
| 2254 |
actor: &me, |
| 2255 |
repo_id: row.id, |
| 2256 |
thread: Some(("issue", i.id)), |
| 2257 |
mention_text: &body.body, |
| 2258 |
direct: i.author_id.into_iter().collect(), |
| 2259 |
}, |
| 2260 |
) |
| 2261 |
.await; |
| c0fac31d Andy McCall ↶ |
2262 |
let api = Comment { |
| 2263 |
id: cm.id, |
| 2264 |
author: cm.author, |
| 2265 |
body: cm.body, |
| 2266 |
created_ms: cm.created_ms, |
| 2267 |
path: None, |
| 2268 |
anchor: None, |
| 2269 |
line: None, |
| 2270 |
resolved: false, |
| 2271 |
}; |
| b64e2537 Andy McCall ↶ |
2272 |
crate::hooks::emit(&app, &row, "comment.issue", &me.username, serde_json::json!({ "number": number, "comment": api })).await; |
| 2273 |
Ok((StatusCode::CREATED, Json(api))) |
| 76f262e1 Andy McCall ↶ |
2274 |
} |
| 2275 |
|
| 2276 |
|
| 2277 |
struct Triage { |
| 2278 |
labels: Option<Vec<db::issues::Label>>, |
| 2279 |
assignees: Option<Vec<Account>>, |
| 2280 |
|
| 2281 |
milestone: Option<Option<db::issues::Milestone>>, |
| 2282 |
} |
| 2283 |
|
| 2284 |
async fn resolve_triage( |
| 2285 |
app: &Shared, |
| 2286 |
repo_id: i64, |
| 2287 |
labels: Option<&[String]>, |
| 2288 |
assignees: Option<&[String]>, |
| 2289 |
milestone: Option<&str>, |
| 2290 |
) -> Result<Triage, ApiError> { |
| 2291 |
let bad = |m: String| ApiError(StatusCode::BAD_REQUEST, m); |
| 2292 |
let labels = match labels { |
| 2293 |
Some(names) => { |
| 2294 |
let mut out = Vec::new(); |
| 2295 |
for n in names { |
| 2296 |
out.push( |
| 2297 |
db::issues::label_by_name(&app.db, repo_id, n.trim()) |
| 2298 |
.await? |
| 2299 |
.ok_or_else(|| bad(format!("no label {n:?}; create it first")))?, |
| 2300 |
); |
| 2301 |
} |
| 2302 |
Some(out) |
| 2303 |
} |
| 2304 |
None => None, |
| 2305 |
}; |
| 2306 |
let assignees = match assignees { |
| 2307 |
Some(names) => { |
| 2308 |
let mut out = Vec::new(); |
| 2309 |
for n in names { |
| 2310 |
out.push(db::accounts::account_by_name(&app.db, n.trim()).await?.ok_or_else(|| bad(format!("no account {n:?}")))?); |
| 2311 |
} |
| 2312 |
Some(out) |
| 2313 |
} |
| 2314 |
None => None, |
| 2315 |
}; |
| 2316 |
let milestone = match milestone.map(str::trim) { |
| 2317 |
None => None, |
| 2318 |
Some("") => Some(None), |
| 2319 |
Some(title) => Some(Some( |
| 2320 |
db::issues::milestones(&app.db, repo_id) |
| 2321 |
.await? |
| 2322 |
.into_iter() |
| 2323 |
.find(|m| m.title == title) |
| 2324 |
.ok_or_else(|| bad(format!("no milestone {title:?}")))?, |
| 2325 |
)), |
| 2326 |
}; |
| 2327 |
Ok(Triage { labels, assignees, milestone }) |
| 2328 |
} |
| 2329 |
|
| 2330 |
|
| 2331 |
|
| 2332 |
async fn apply_triage(app: &Shared, i: &db::issues::IssueRow, me: &Account, t: Triage) -> Result<(), ApiError> { |
| 2333 |
if let Some(want) = t.labels { |
| 2334 |
let have = db::issues::issue_labels(&app.db, i.id).await?; |
| 2335 |
for l in &have { |
| 2336 |
if !want.iter().any(|w| w.id == l.id) { |
| 2337 |
db::issues::set_issue_label(&app.db, i.id, l.id, false).await?; |
| 2338 |
} |
| 2339 |
} |
| 2340 |
for w in &want { |
| 2341 |
if !have.iter().any(|l| l.id == w.id) { |
| 2342 |
db::issues::set_issue_label(&app.db, i.id, w.id, true).await?; |
| 2343 |
} |
| 2344 |
} |
| 2345 |
let names: Vec<&str> = want.iter().map(|l| l.name.as_str()).collect(); |
| 2346 |
db::issues::add_event(&app.db, i.id, &me.username, "set labels", &names.join(", ")).await.ok(); |
| 2347 |
} |
| 2348 |
if let Some(want) = t.assignees { |
| 2349 |
let have = db::issues::assignees(&app.db, i.id).await?; |
| 2350 |
for name in &have { |
| 2351 |
if !want.iter().any(|a| &a.username == name) { |
| 2352 |
if let Some(a) = db::accounts::account_by_name(&app.db, name).await? { |
| 2353 |
db::issues::set_assignee(&app.db, i.id, a.id, false).await?; |
| 2354 |
db::issues::add_event(&app.db, i.id, &me.username, "unassigned", name).await.ok(); |
| 2355 |
} |
| 2356 |
} |
| 2357 |
} |
| 2358 |
for a in &want { |
| 2359 |
if !have.contains(&a.username) { |
| 2360 |
db::issues::set_assignee(&app.db, i.id, a.id, true).await?; |
| 2361 |
db::issues::add_event(&app.db, i.id, &me.username, "assigned", &a.username).await.ok(); |
| 2362 |
} |
| 2363 |
} |
| 2364 |
} |
| 2365 |
if let Some(m) = t.milestone { |
| 2366 |
db::issues::set_milestone(&app.db, i.id, m.as_ref().map(|m| m.id)).await?; |
| 2367 |
db::issues::add_event(&app.db, i.id, &me.username, "set milestone", m.as_ref().map(|m| m.title.as_str()).unwrap_or("")).await.ok(); |
| 2368 |
} |
| 2369 |
Ok(()) |
| 2370 |
} |
| 2371 |
|
| 2372 |
|
| 2373 |
async fn issue_edit( |
| 2374 |
State(app): State<Shared>, |
| 2375 |
headers: HeaderMap, |
| 2376 |
Path((owner, name, number)): Path<(String, String, i64)>, |
| 2377 |
Json(body): Json<IssueEdit>, |
| 2378 |
) -> Result<Json<Issue>, ApiError> { |
| 2379 |
let c = caller(&app, &headers).await?; |
| 2380 |
let me = c.require("issues:write").or_else(|_| c.require("repo:write"))?.clone(); |
| 2381 |
let (_, row, role) = reach(&app, &c, &owner, &name, Access::Read).await?; |
| 2382 |
let i = db::issues::get(&app.db, row.id, number).await?.ok_or_else(|| not_found("no such issue"))?; |
| 2383 |
let text = body.title.is_some() || body.body.is_some(); |
| 2384 |
let triage = body.labels.is_some() || body.assignees.is_some() || body.milestone.is_some(); |
| 2385 |
if text && role < Role::Triage && Some(me.id) != i.author_id { |
| 2386 |
return Err(forbidden("only the author or triage may edit the title and body")); |
| 2387 |
} |
| 2388 |
if triage && role < Role::Triage { |
| 2389 |
return Err(forbidden("setting labels, assignees or a milestone needs triage access")); |
| 2390 |
} |
| 2391 |
if i.locked && role < Role::Triage { |
| 2392 |
return Err(forbidden("this issue is locked")); |
| 2393 |
} |
| 2394 |
let t = resolve_triage(&app, row.id, body.labels.as_deref(), body.assignees.as_deref(), body.milestone.as_deref()).await?; |
| 2395 |
if text { |
| 2396 |
let title = body.title.as_deref().map(str::trim).unwrap_or(&i.title); |
| 2397 |
if title.is_empty() { |
| 2398 |
return Err(ApiError(StatusCode::BAD_REQUEST, "an issue needs a title".into())); |
| 2399 |
} |
| 2400 |
db::issues::edit(&app.db, i.id, title, body.body.as_deref().unwrap_or(&i.body)).await?; |
| 2401 |
db::issues::add_event(&app.db, i.id, &me.username, "edited", "").await.ok(); |
| 2402 |
} |
| 2403 |
apply_triage(&app, &i, &me, t).await?; |
| 2404 |
db::issues::touch(&app.db, i.id).await.ok(); |
| 2405 |
let fresh = db::issues::get(&app.db, row.id, number).await?.unwrap_or(i); |
| 2406 |
crate::web::issues::reindex(&app, row.id, &fresh).await; |
| 2407 |
let api = issue_of(&app, &row, &fresh).await?; |
| 2408 |
crate::hooks::emit(&app, &row, "issue.edited", &me.username, serde_json::json!({ "issue": api })).await; |
| 2409 |
Ok(Json(api)) |
| 2410 |
} |
| 2411 |
|
| 2412 |
|
| 2413 |
async fn create_label( |
| 2414 |
State(app): State<Shared>, |
| 2415 |
headers: HeaderMap, |
| 2416 |
Path((owner, name)): Path<(String, String)>, |
| 2417 |
Json(body): Json<NewLabel>, |
| 2418 |
) -> Result<(StatusCode, Json<Label>), ApiError> { |
| 2419 |
let c = caller(&app, &headers).await?; |
| 2420 |
c.require("issues:write").or_else(|_| c.require("repo:write"))?; |
| 2421 |
let (_, row, role) = reach(&app, &c, &owner, &name, Access::Read).await?; |
| 2422 |
if role < Role::Triage { |
| 2423 |
return Err(forbidden("labels need triage access")); |
| 2424 |
} |
| 2425 |
let label = body.name.trim(); |
| 2426 |
if label.is_empty() || label.len() > 50 { |
| 2427 |
return Err(ApiError(StatusCode::BAD_REQUEST, "a label has a name of 1 to 50 characters".into())); |
| 2428 |
} |
| 2429 |
let colour = match body.colour.as_deref() { |
| 2430 |
Some(c) if c.len() == 7 && c.starts_with('#') && c[1..].chars().all(|x| x.is_ascii_hexdigit()) => c.to_string(), |
| 2431 |
Some(c) => return Err(ApiError(StatusCode::BAD_REQUEST, format!("colour {c:?} is not #rrggbb"))), |
| 2432 |
None => "#5aa8ff".to_string(), |
| 2433 |
}; |
| 2434 |
let l = db::issues::upsert_label(&app.db, row.id, label, &colour, body.description.trim()).await?; |
| 2435 |
Ok((StatusCode::CREATED, Json(Label { name: l.name, colour: l.colour, description: l.description }))) |
| 2436 |
} |
| 2437 |
|
| 2438 |
|
| 2439 |
async fn delete_label( |
| 2440 |
State(app): State<Shared>, |
| 2441 |
headers: HeaderMap, |
| 2442 |
Path((owner, name, label)): Path<(String, String, String)>, |
| 2443 |
) -> Result<StatusCode, ApiError> { |
| 2444 |
let c = caller(&app, &headers).await?; |
| 2445 |
c.require("issues:write").or_else(|_| c.require("repo:write"))?; |
| 2446 |
let (_, row, role) = reach(&app, &c, &owner, &name, Access::Read).await?; |
| 2447 |
if role < Role::Triage { |
| 2448 |
return Err(forbidden("labels need triage access")); |
| 2449 |
} |
| 2450 |
let l = db::issues::label_by_name(&app.db, row.id, &label).await?.ok_or_else(|| not_found("no such label"))?; |
| 2451 |
db::issues::delete_label(&app.db, l.id).await?; |
| 2452 |
Ok(StatusCode::NO_CONTENT) |
| d23464c0 Andy McCall ↶ |
2453 |
} |
| 2454 |
|
| b64e2537 Andy McCall ↶ |
2455 |
async fn labels( |
| 2456 |
State(app): State<Shared>, |
| 2457 |
headers: HeaderMap, |
| 2458 |
Path((owner, name)): Path<(String, String)>, |
| 2459 |
) -> Result<Json<Vec<Label>>, ApiError> { |
| 2460 |
let c = caller(&app, &headers).await?; |
| 2461 |
let (_, row, _) = reach(&app, &c, &owner, &name, Access::Read).await?; |
| 2462 |
Ok(Json( |
| 2463 |
db::issues::labels(&app.db, row.id) |
| 2464 |
.await? |
| 2465 |
.into_iter() |
| 2466 |
.map(|l| Label { name: l.name, colour: l.colour, description: l.description }) |
| 2467 |
.collect(), |
| 2468 |
)) |
| 2469 |
} |
| 2470 |
|
| 2471 |
async fn milestones( |
| 2472 |
State(app): State<Shared>, |
| 2473 |
headers: HeaderMap, |
| 2474 |
Path((owner, name)): Path<(String, String)>, |
| 2475 |
) -> Result<Json<Vec<Milestone>>, ApiError> { |
| 2476 |
let c = caller(&app, &headers).await?; |
| 2477 |
let (_, row, _) = reach(&app, &c, &owner, &name, Access::Read).await?; |
| 2478 |
let mut out = Vec::new(); |
| 2479 |
for m in db::issues::milestones(&app.db, row.id).await? { |
| 2480 |
let (open, closed) = db::issues::milestone_counts(&app.db, m.id).await?; |
| 2481 |
out.push(Milestone { title: m.title, description: m.description, due_ms: m.due_ms, state: m.state, open, closed }); |
| d23464c0 Andy McCall ↶ |
2482 |
} |
| b64e2537 Andy McCall ↶ |
2483 |
Ok(Json(out)) |
| 2484 |
} |
| 2485 |
|
| 5ea4872f Andy McCall ↶ |
2486 |
fn milestone_of(m: db::issues::Milestone, open: i64, closed: i64) -> Milestone { |
| 2487 |
Milestone { title: m.title, description: m.description, due_ms: m.due_ms, state: m.state, open, closed } |
| 2488 |
} |
| 2489 |
|
| 2490 |
|
| 2491 |
fn due_ms_of(due: &str) -> Result<Option<i64>, ApiError> { |
| 2492 |
let due = due.trim(); |
| 2493 |
if due.is_empty() { |
| 2494 |
return Ok(None); |
| 2495 |
} |
| 2496 |
time::Date::parse(due, &time::macros::format_description!("[year]-[month]-[day]")) |
| 2497 |
.map(|d| Some(d.midnight().assume_utc().unix_timestamp() * 1000)) |
| 2498 |
.map_err(|_| ApiError(StatusCode::BAD_REQUEST, format!("due {due:?} is not YYYY-MM-DD"))) |
| 2499 |
} |
| 2500 |
|
| 2501 |
async fn triage_for_milestones(app: &Shared, headers: &HeaderMap, owner: &str, name: &str) -> Result<db::repos::RepoRow, ApiError> { |
| 2502 |
let c = caller(app, headers).await?; |
| 2503 |
c.require("issues:write").or_else(|_| c.require("repo:write"))?; |
| 2504 |
let (_, row, role) = reach(app, &c, owner, name, Access::Read).await?; |
| 2505 |
if role < Role::Triage { |
| 2506 |
return Err(forbidden("milestones need triage access")); |
| 2507 |
} |
| 2508 |
Ok(row) |
| 2509 |
} |
| 2510 |
|
| 2511 |
|
| 2512 |
|
| 2513 |
|
| 2514 |
async fn create_milestone( |
| 2515 |
State(app): State<Shared>, |
| 2516 |
headers: HeaderMap, |
| 2517 |
Path((owner, name)): Path<(String, String)>, |
| 2518 |
Json(body): Json<NewMilestone>, |
| 2519 |
) -> Result<(StatusCode, Json<Milestone>), ApiError> { |
| 2520 |
let row = triage_for_milestones(&app, &headers, &owner, &name).await?; |
| 2521 |
let title = body.title.trim(); |
| 2522 |
if title.is_empty() || title.len() > 100 { |
| 2523 |
return Err(ApiError(StatusCode::BAD_REQUEST, "a milestone has a title of 1 to 100 characters".into())); |
| 2524 |
} |
| 2525 |
let due_ms = due_ms_of(body.due.as_deref().unwrap_or(""))?; |
| 2526 |
let m = db::issues::upsert_milestone(&app.db, row.id, title, body.description.trim(), due_ms).await?; |
| 2527 |
let (open, closed) = db::issues::milestone_counts(&app.db, m.id).await?; |
| 2528 |
Ok((StatusCode::CREATED, Json(milestone_of(m, open, closed)))) |
| 2529 |
} |
| 2530 |
|
| 2531 |
|
| 2532 |
|
| 2533 |
async fn edit_milestone( |
| 2534 |
State(app): State<Shared>, |
| 2535 |
headers: HeaderMap, |
| 2536 |
Path((owner, name, title)): Path<(String, String, String)>, |
| 2537 |
Json(body): Json<MilestoneEdit>, |
| 2538 |
) -> Result<Json<Milestone>, ApiError> { |
| 2539 |
let row = triage_for_milestones(&app, &headers, &owner, &name).await?; |
| 2540 |
let m = db::issues::milestones(&app.db, row.id) |
| 2541 |
.await? |
| 2542 |
.into_iter() |
| 2543 |
.find(|m| m.title == title) |
| 2544 |
.ok_or_else(|| not_found("no such milestone"))?; |
| 2545 |
let new_title = body.title.as_deref().map(str::trim).unwrap_or(&m.title); |
| 2546 |
if new_title.is_empty() || new_title.len() > 100 { |
| 2547 |
return Err(ApiError(StatusCode::BAD_REQUEST, "a milestone has a title of 1 to 100 characters".into())); |
| 2548 |
} |
| 2549 |
let due_ms = match body.due.as_deref() { |
| 2550 |
Some(d) => due_ms_of(d)?, |
| 2551 |
None => m.due_ms, |
| 2552 |
}; |
| 2553 |
let description = body.description.as_deref().map(str::trim).unwrap_or(&m.description); |
| 2554 |
if body.title.is_some() || body.description.is_some() || body.due.is_some() { |
| 2555 |
db::issues::update_milestone(&app.db, m.id, new_title, description, due_ms).await?; |
| 2556 |
} |
| 2557 |
if let Some(state) = body.state.as_deref() { |
| 2558 |
match state { |
| 2559 |
"open" | "closed" => db::issues::set_milestone_state(&app.db, m.id, state).await?, |
| 2560 |
other => return Err(ApiError(StatusCode::BAD_REQUEST, format!("state {other:?} is open or closed"))), |
| 2561 |
} |
| 2562 |
} |
| 2563 |
let fresh = db::issues::milestone(&app.db, m.id).await?.ok_or_else(|| not_found("no such milestone"))?; |
| 2564 |
let (open, closed) = db::issues::milestone_counts(&app.db, fresh.id).await?; |
| 2565 |
Ok(Json(milestone_of(fresh, open, closed))) |
| 2566 |
} |
| 2567 |
|
| b64e2537 Andy McCall ↶ |
2568 |
|
| 2569 |
|
| 2570 |
fn hook_of(h: &db::hooks::Hook) -> Hook { |
| 2571 |
Hook { id: h.id, url: h.url.clone(), events: h.events.clone(), active: h.active, created_ms: h.created_ms } |
| 2572 |
} |
| 2573 |
|
| 2574 |
async fn hooks( |
| 2575 |
State(app): State<Shared>, |
| 2576 |
headers: HeaderMap, |
| 2577 |
Path((owner, name)): Path<(String, String)>, |
| 2578 |
) -> Result<Json<Vec<Hook>>, ApiError> { |
| 2579 |
let c = caller(&app, &headers).await?; |
| 2580 |
c.require("hooks:admin").or_else(|_| c.require("repo:admin"))?; |
| 2581 |
let (_, row, _) = reach(&app, &c, &owner, &name, Access::Admin).await?; |
| 2582 |
Ok(Json(db::hooks::hooks_for_repo(&app.db, row.id).await?.iter().map(hook_of).collect())) |
| d23464c0 Andy McCall ↶ |
2583 |
} |
| 2584 |
|
| b64e2537 Andy McCall ↶ |
2585 |
async fn create_hook( |
| 2586 |
State(app): State<Shared>, |
| 2587 |
headers: HeaderMap, |
| 2588 |
Path((owner, name)): Path<(String, String)>, |
| 2589 |
Json(body): Json<NewHook>, |
| 2590 |
) -> Result<(StatusCode, Json<Hook>), ApiError> { |
| 2591 |
let c = caller(&app, &headers).await?; |
| 2592 |
let me = c.require("hooks:admin").or_else(|_| c.require("repo:admin"))?.clone(); |
| 2593 |
let (_, row, _) = reach(&app, &c, &owner, &name, Access::Admin).await?; |
| 2594 |
if !(body.url.starts_with("http://") || body.url.starts_with("https://")) { |
| 2595 |
return Err(ApiError(StatusCode::BAD_REQUEST, "the URL must be http or https".into())); |
| 2596 |
} |
| 2597 |
let h = db::hooks::create_hook(&app.db, Some(row.id), None, &body.url, &body.secret, &body.events).await?; |
| 2598 |
db::accounts::audit(&app.db, Some(&me), "hook.created", &row.slug(), &body.url).await.ok(); |
| 2599 |
Ok((StatusCode::CREATED, Json(hook_of(&h)))) |
| d23464c0 Andy McCall ↶ |
2600 |
} |
| 2601 |
|
| b64e2537 Andy McCall ↶ |
2602 |
async fn delete_hook( |
| 2603 |
State(app): State<Shared>, |
| 2604 |
headers: HeaderMap, |
| 2605 |
Path((owner, name, id)): Path<(String, String, i64)>, |
| 2606 |
) -> Result<StatusCode, ApiError> { |
| 2607 |
let c = caller(&app, &headers).await?; |
| 2608 |
c.require("hooks:admin").or_else(|_| c.require("repo:admin"))?; |
| 2609 |
let (_, row, _) = reach(&app, &c, &owner, &name, Access::Admin).await?; |
| 2610 |
if db::hooks::hook(&app.db, id).await?.is_some_and(|h| h.repo_id == Some(row.id)) { |
| 2611 |
db::hooks::delete_hook(&app.db, id).await?; |
| 2612 |
} |
| 2613 |
Ok(StatusCode::NO_CONTENT) |
| d23464c0 Andy McCall ↶ |
2614 |
} |
| 2615 |
|
| b64e2537 Andy McCall ↶ |
2616 |
pub fn check_of(c: &db::hooks::Check) -> Check { |
| 2617 |
Check { |
| 2618 |
state: c.state.clone(), |
| 2619 |
name: c.name.clone(), |
| 2620 |
status: CheckStatus::parse(&c.status).unwrap_or(CheckStatus::Queued), |
| 2621 |
summary: c.summary.clone(), |
| 2622 |
url: c.url.clone(), |
| 2623 |
reporter: c.reporter.clone(), |
| 2624 |
seal: if c.seal.is_empty() { None } else { Some(c.seal.clone()) }, |
| 2625 |
started_ms: c.started_ms, |
| 2626 |
finished_ms: c.finished_ms, |
| 2627 |
} |
| 961c10be Andy McCall ↶ |
2628 |
} |
| 2629 |
|
| 2630 |
|
| 2631 |
async fn required_checks( |
| 2632 |
State(app): State<Shared>, |
| 2633 |
headers: HeaderMap, |
| 2634 |
Path((owner, name)): Path<(String, String)>, |
| 2635 |
) -> Result<Json<RequiredChecks>, ApiError> { |
| 2636 |
let c = caller(&app, &headers).await?; |
| 2637 |
let (_, row, _) = reach(&app, &c, &owner, &name, Access::Read).await?; |
| 2638 |
Ok(Json(RequiredChecks { names: db::hooks::required_checks(&app.db, row.id).await? })) |
| 2639 |
} |
| 2640 |
|
| 2641 |
|
| 2642 |
async fn set_required_checks( |
| 2643 |
State(app): State<Shared>, |
| 2644 |
headers: HeaderMap, |
| 2645 |
Path((owner, name)): Path<(String, String)>, |
| 2646 |
Json(body): Json<RequiredChecks>, |
| 2647 |
) -> Result<Json<RequiredChecks>, ApiError> { |
| 2648 |
let c = caller(&app, &headers).await?; |
| 2649 |
c.require("repo:admin")?; |
| 2650 |
let (_, row, _) = reach(&app, &c, &owner, &name, Access::Admin).await?; |
| 2651 |
let mut names: Vec<String> = body.names.iter().map(|n| n.trim().to_string()).filter(|n| !n.is_empty()).collect(); |
| 2652 |
names.sort(); |
| 2653 |
names.dedup(); |
| 2654 |
if names.len() > 32 || names.iter().any(|n| n.len() > 100 || n.contains(',')) { |
| 2655 |
return Err(ApiError(StatusCode::BAD_REQUEST, "at most 32 check names, each under 100 characters and without commas".into())); |
| 2656 |
} |
| 2657 |
db::hooks::set_required_checks(&app.db, row.id, &names).await?; |
| 2658 |
db::accounts::audit(&app.db, c.account.as_ref(), "repo.required_checks", &format!("{owner}/{name}"), &names.join(", ")).await.ok(); |
| 2659 |
Ok(Json(RequiredChecks { names })) |
| 1edac4b6 Andy McCall ↶ |
2660 |
} |
| 2661 |
|
| bf3d0754 Andy McCall ↶ |
2662 |
fn flow_run_of( |
| 2663 |
app: &Shared, |
| 2664 |
row: &db::repos::RepoRow, |
| 2665 |
r: &db::flow::Run, |
| 2666 |
jobs: Vec<db::flow::Job>, |
| 2667 |
queue: &[db::flow::QueueEntry], |
| 2668 |
) -> FlowRun { |
| 90326c96 Andy McCall ↶ |
2669 |
FlowRun { |
| bf3d0754 Andy McCall ↶ |
2670 |
queue_position: crate::flow::queue_info(queue, row.id, r.id).position.map(|p| p as i64), |
| 90326c96 Andy McCall ↶ |
2671 |
number: r.number, |
| 2672 |
bookmark: r.bookmark.clone(), |
| 2673 |
state: r.state.clone(), |
| 2674 |
heads: r.head_list().into_iter().map(String::from).collect(), |
| 2675 |
status: r.status.clone(), |
| c889911b Andy McCall ↶ |
2676 |
trigger: r.trigger_label(), |
| 90326c96 Andy McCall ↶ |
2677 |
actor: r.actor.clone(), |
| 2678 |
pipeline_hash: r.pipeline_hash.clone(), |
| 2679 |
error: r.error.clone(), |
| 2680 |
created_ms: r.created_ms, |
| 2681 |
finished_ms: r.finished_ms, |
| 2682 |
url: format!("{}/{}/{}/flow/{}", app.config.base_url(), row.owner, row.name, r.number), |
| 2683 |
jobs: jobs |
| 2684 |
.into_iter() |
| 2685 |
.map(|j| FlowJob { |
| fac6853c Andy McCall ↶ |
2686 |
phases: j.phase_list().into_iter().map(|(name, ms)| hub_api::FlowPhase { name, ms }).collect(), |
| 2687 |
queued_ms: j.queued_ms, |
| 2688 |
ready_ms: j.ready_ms, |
| 2689 |
peak_disk_mib: j.peak_disk_mib, |
| 2690 |
peak_memory_mib: j.peak_memory_mib, |
| 90326c96 Andy McCall ↶ |
2691 |
depends_on: j.depends_on(), |
| 2692 |
name: j.name, |
| 2693 |
status: j.status, |
| 2694 |
runner: j.runner, |
| 2695 |
exit_code: j.exit_code, |
| 2696 |
error: j.error, |
| 2697 |
started_ms: j.started_ms, |
| 2698 |
finished_ms: j.finished_ms, |
| 2699 |
log_lines: j.log_count, |
| 4d2e44d7 Andy McCall ↶ |
2700 |
waiting: j.waiting, |
| 501d8b26 Andy McCall ↶ |
2701 |
placed: j.placed, |
| b1860d60 Andy McCall ↶ |
2702 |
approval: j.approval, |
| 90326c96 Andy McCall ↶ |
2703 |
}) |
| 2704 |
.collect(), |
| 2705 |
} |
| 2706 |
} |
| 2707 |
|
| 1edac4b6 Andy McCall ↶ |
2708 |
#[derive(Deserialize)] |
| 90326c96 Andy McCall ↶ |
2709 |
struct RunsPage { |
| 2710 |
|
| 2711 |
before: Option<i64>, |
| 2712 |
limit: Option<i64>, |
| 2713 |
} |
| 2714 |
|
| 2715 |
|
| 2716 |
async fn flow_runs( |
| 2717 |
State(app): State<Shared>, |
| 2718 |
headers: HeaderMap, |
| 2719 |
Path((owner, name)): Path<(String, String)>, |
| 2720 |
Query(q): Query<RunsPage>, |
| 2721 |
) -> Result<Json<Vec<FlowRun>>, ApiError> { |
| 2722 |
let c = caller(&app, &headers).await?; |
| 2723 |
let (_, row, _) = reach(&app, &c, &owner, &name, Access::Read).await?; |
| 2724 |
let limit = q.limit.unwrap_or(30).clamp(1, 100); |
| 2725 |
let runs = db::flow::runs_by_number(&app.db, row.id, limit, q.before).await?; |
| bf3d0754 Andy McCall ↶ |
2726 |
let queue = if runs.iter().any(|r| r.live()) { db::flow::queue(&app.db).await? } else { vec![] }; |
| 2727 |
Ok(Json(runs.iter().map(|r| flow_run_of(&app, &row, r, vec![], &queue)).collect())) |
| 90326c96 Andy McCall ↶ |
2728 |
} |
| 2729 |
|
| 2730 |
|
| 2731 |
async fn flow_run( |
| 2732 |
State(app): State<Shared>, |
| 2733 |
headers: HeaderMap, |
| 2734 |
Path((owner, name, number)): Path<(String, String, i64)>, |
| 2735 |
) -> Result<Json<FlowRun>, ApiError> { |
| 2736 |
let c = caller(&app, &headers).await?; |
| 2737 |
let (_, row, _) = reach(&app, &c, &owner, &name, Access::Read).await?; |
| 2738 |
let run = db::flow::run(&app.db, row.id, number).await?.ok_or_else(|| ApiError(StatusCode::NOT_FOUND, "no such run".into()))?; |
| 2739 |
let jobs = db::flow::jobs(&app.db, run.id).await?; |
| bf3d0754 Andy McCall ↶ |
2740 |
let queue = if run.live() { db::flow::queue(&app.db).await? } else { vec![] }; |
| 2741 |
Ok(Json(flow_run_of(&app, &row, &run, jobs, &queue))) |
| 90326c96 Andy McCall ↶ |
2742 |
} |
| 2743 |
|
| 2744 |
#[derive(Deserialize)] |
| 2745 |
struct LogPage { |
| 2746 |
|
| 2747 |
#[serde(default)] |
| 2748 |
after: i64, |
| 2749 |
limit: Option<i64>, |
| 2750 |
} |
| 2751 |
|
| 2752 |
|
| 2753 |
async fn flow_job_log( |
| 2754 |
State(app): State<Shared>, |
| 2755 |
headers: HeaderMap, |
| 2756 |
Path((owner, name, number, job)): Path<(String, String, i64, String)>, |
| 2757 |
Query(q): Query<LogPage>, |
| 2758 |
) -> Result<Json<Vec<FlowLogLine>>, ApiError> { |
| 2759 |
let c = caller(&app, &headers).await?; |
| 2760 |
let (_, row, _) = reach(&app, &c, &owner, &name, Access::Read).await?; |
| 2761 |
let run = db::flow::run(&app.db, row.id, number).await?.ok_or_else(|| ApiError(StatusCode::NOT_FOUND, "no such run".into()))?; |
| 2762 |
let j = db::flow::jobs(&app.db, run.id) |
| 2763 |
.await? |
| 2764 |
.into_iter() |
| 2765 |
.find(|j| j.name == job) |
| 2766 |
.ok_or_else(|| ApiError(StatusCode::NOT_FOUND, "no such job".into()))?; |
| 2767 |
let lines = db::flow::log(&app.db, j.id, q.after, q.limit.unwrap_or(1000).clamp(1, 5000)).await?; |
| 2768 |
Ok(Json(lines.into_iter().map(|l| FlowLogLine { seq: l.seq, t: l.t, stream: l.stream, text: l.text }).collect())) |
| 2769 |
} |
| 2770 |
|
| 2771 |
#[derive(Deserialize)] |
| 1edac4b6 Andy McCall ↶ |
2772 |
struct StartRun { |
| 2773 |
|
| 2774 |
#[serde(default)] |
| 2775 |
bookmark: Option<String>, |
| 4f692533 Andy McCall ↶ |
2776 |
|
| 2777 |
|
| 2778 |
#[serde(default)] |
| 2779 |
change: Option<String>, |
| 0650d94e Andy McCall ↶ |
2780 |
|
| 2781 |
|
| 2782 |
#[serde(default)] |
| 2783 |
jobs: Vec<String>, |
| 1edac4b6 Andy McCall ↶ |
2784 |
} |
| 2785 |
|
| 2786 |
fn started(app: &Shared, row: &db::repos::RepoRow, number: i64) -> (StatusCode, Json<serde_json::Value>) { |
| 2787 |
let url = format!("{}/{}/{}/flow/{number}", app.config.base_url(), row.owner, row.name); |
| 2788 |
(StatusCode::CREATED, Json(serde_json::json!({ "number": number, "url": url }))) |
| 2789 |
} |
| 2790 |
|
| 2791 |
|
| 4f692533 Andy McCall ↶ |
2792 |
|
| 1edac4b6 Andy McCall ↶ |
2793 |
async fn start_flow_run( |
| 2794 |
State(app): State<Shared>, |
| 2795 |
headers: HeaderMap, |
| 2796 |
Path((owner, name)): Path<(String, String)>, |
| 2797 |
Json(body): Json<StartRun>, |
| 2798 |
) -> Result<(StatusCode, Json<serde_json::Value>), ApiError> { |
| 2799 |
let c = caller(&app, &headers).await?; |
| 2800 |
let me = c.require("repo:write")?.clone(); |
| 2801 |
let (_, row, _) = reach(&app, &c, &owner, &name, Access::Write).await?; |
| 0650d94e Andy McCall ↶ |
2802 |
let (n, what) = match body.change.clone().filter(|c| !c.trim().is_empty()) { |
| 4f692533 Andy McCall ↶ |
2803 |
Some(change) => { |
| 0650d94e Andy McCall ↶ |
2804 |
let n = crate::flow::run_change(&app, &row, &change, &me.username, &body.jobs) |
| 2805 |
.await |
| 2806 |
.map_err(|m| ApiError(StatusCode::CONFLICT, m))?; |
| 4f692533 Andy McCall ↶ |
2807 |
(n, format!("change {}", change.trim())) |
| 2808 |
} |
| 2809 |
None => { |
| 2810 |
let bookmark = body.bookmark.unwrap_or_else(|| row.default_bookmark.clone()); |
| 0650d94e Andy McCall ↶ |
2811 |
( |
| 2812 |
crate::flow::run_bookmark(&app, &row, &bookmark, &me.username, &body.jobs) |
| 2813 |
.await |
| 2814 |
.map_err(|m| ApiError(StatusCode::CONFLICT, m))?, |
| 2815 |
bookmark, |
| 2816 |
) |
| 4f692533 Andy McCall ↶ |
2817 |
} |
| 2818 |
}; |
| 2819 |
db::accounts::audit(&app.db, Some(&me), "flow.run", &format!("{owner}/{name}"), &format!("#{n} {what}")).await.ok(); |
| 1edac4b6 Andy McCall ↶ |
2820 |
Ok(started(&app, &row, n)) |
| 2821 |
} |
| 2822 |
|
| 2823 |
|
| 2824 |
async fn rerun_flow_run( |
| 2825 |
State(app): State<Shared>, |
| 2826 |
headers: HeaderMap, |
| 2827 |
Path((owner, name, number)): Path<(String, String, i64)>, |
| 2828 |
) -> Result<(StatusCode, Json<serde_json::Value>), ApiError> { |
| 2829 |
let c = caller(&app, &headers).await?; |
| 2830 |
let me = c.require("repo:write")?.clone(); |
| 2831 |
let (_, row, _) = reach(&app, &c, &owner, &name, Access::Write).await?; |
| 2832 |
let run = db::flow::run(&app.db, row.id, number).await?.ok_or_else(|| ApiError(StatusCode::NOT_FOUND, "no such run".into()))?; |
| 2833 |
let n = crate::flow::rerun(&app, &row, &run, &me.username).await.map_err(|m| ApiError(StatusCode::CONFLICT, m))?; |
| 2834 |
db::accounts::audit(&app.db, Some(&me), "flow.rerun", &format!("{owner}/{name}"), &format!("#{n} of #{number}")).await.ok(); |
| 2835 |
Ok(started(&app, &row, n)) |
| d23464c0 Andy McCall ↶ |
2836 |
} |
| 2837 |
|
| e8fa5369 Andy McCall ↶ |
2838 |
|
| 2839 |
|
| 2840 |
|
| 2841 |
async fn rerun_flow_job( |
| 2842 |
State(app): State<Shared>, |
| 2843 |
headers: HeaderMap, |
| 2844 |
Path((owner, name, number, job)): Path<(String, String, i64, String)>, |
| 2845 |
) -> Result<Json<serde_json::Value>, ApiError> { |
| 2846 |
let c = caller(&app, &headers).await?; |
| 2847 |
let me = c.require("repo:write")?.clone(); |
| 2848 |
let (_, row, _) = reach(&app, &c, &owner, &name, Access::Write).await?; |
| 2849 |
let run = db::flow::run(&app.db, row.id, number).await?.ok_or_else(|| ApiError(StatusCode::NOT_FOUND, "no such run".into()))?; |
| 2850 |
let n = crate::flow::rerun_job(&app, &row, &run, &job, &me.username).await.map_err(|m| ApiError(StatusCode::CONFLICT, m))?; |
| 2851 |
db::accounts::audit(&app.db, Some(&me), "flow.rerun", &format!("{owner}/{name}"), &format!("{job} of #{number}")).await.ok(); |
| 2852 |
Ok(Json(serde_json::json!({ "run": number, "job": job, "queued": n }))) |
| 2853 |
} |
| 2854 |
|
| 745d225d Andy McCall ↶ |
2855 |
|
| 2856 |
|
| 2857 |
async fn cancel_flow_run( |
| 2858 |
State(app): State<Shared>, |
| 2859 |
headers: HeaderMap, |
| 2860 |
Path((owner, name, number)): Path<(String, String, i64)>, |
| 2861 |
) -> Result<Json<serde_json::Value>, ApiError> { |
| 2862 |
let c = caller(&app, &headers).await?; |
| 2863 |
let me = c.require("repo:write")?.clone(); |
| 2864 |
let (_, row, _) = reach(&app, &c, &owner, &name, Access::Write).await?; |
| 2865 |
let run = db::flow::run(&app.db, row.id, number).await?.ok_or_else(|| ApiError(StatusCode::NOT_FOUND, "no such run".into()))?; |
| 2866 |
crate::flow::cancel(&app, &row, &run, &me.username).await.map_err(|m| ApiError(StatusCode::CONFLICT, m))?; |
| 2867 |
db::accounts::audit(&app.db, Some(&me), "flow.cancel", &format!("{owner}/{name}"), &format!("#{number}")).await.ok(); |
| 2868 |
Ok(Json(serde_json::json!({ "number": number, "status": "cancelled" }))) |
| 2869 |
} |
| 2870 |
|
| b644e175 Andy McCall ↶ |
2871 |
|
| 2872 |
|
| 2873 |
async fn list_deployments( |
| 2874 |
State(app): State<Shared>, |
| 2875 |
headers: HeaderMap, |
| 2876 |
Path((owner, name)): Path<(String, String)>, |
| 2877 |
) -> Result<Json<Vec<serde_json::Value>>, ApiError> { |
| 2878 |
let c = caller(&app, &headers).await?; |
| 2879 |
let (_, row, _) = reach(&app, &c, &owner, &name, Access::Read).await?; |
| 2880 |
let list = db::flow::deployments(&app.db, row.id, 100).await?; |
| 2881 |
Ok(Json( |
| 2882 |
list.into_iter() |
| 2883 |
.map(|d| { |
| 2884 |
serde_json::json!({ "environment": d.environment, "job": d.job, "run": d.run_number, "state": d.state, |
| 2885 |
"bookmark": d.bookmark, "actor": d.actor, "approved_by": d.approved_by, "finished_ms": d.finished_ms }) |
| 2886 |
}) |
| 2887 |
.collect(), |
| 2888 |
)) |
| 2889 |
} |
| 2890 |
|
| b1860d60 Andy McCall ↶ |
2891 |
#[derive(Deserialize)] |
| 2892 |
struct ExpediteBody { |
| 2893 |
reason: String, |
| 2894 |
} |
| 2895 |
|
| 2896 |
|
| 2897 |
|
| 2898 |
|
| 2899 |
async fn expedite_flow_run( |
| 2900 |
State(app): State<Shared>, |
| 2901 |
headers: HeaderMap, |
| 2902 |
Path((owner, name, number)): Path<(String, String, i64)>, |
| 2903 |
Json(body): Json<ExpediteBody>, |
| 2904 |
) -> Result<Json<serde_json::Value>, ApiError> { |
| 2905 |
let c = caller(&app, &headers).await?; |
| 2906 |
let me = c.require("repo:write")?.clone(); |
| 2907 |
let (_, row, _) = reach(&app, &c, &owner, &name, Access::Maintain).await?; |
| 2908 |
let run = db::flow::run(&app.db, row.id, number).await?.ok_or_else(|| not_found("no such run"))?; |
| 2909 |
crate::flow::expedite(&app, &row, &run, &me, &body.reason).await.map_err(|m| ApiError(StatusCode::CONFLICT, m))?; |
| 2910 |
Ok(Json(serde_json::json!({ "number": number, "expedited": true }))) |
| 2911 |
} |
| 2912 |
|
| 417184c7 Andy McCall ↶ |
2913 |
|
| 2914 |
|
| 2915 |
async fn approve_flow_job( |
| 2916 |
State(app): State<Shared>, |
| 2917 |
headers: HeaderMap, |
| 2918 |
Path((owner, name, number, job)): Path<(String, String, i64, String)>, |
| 2919 |
) -> Result<Json<serde_json::Value>, ApiError> { |
| 2920 |
decide_flow_job(&app, &headers, &owner, &name, number, &job, true).await |
| 2921 |
} |
| 2922 |
|
| 2923 |
async fn reject_flow_job( |
| 2924 |
State(app): State<Shared>, |
| 2925 |
headers: HeaderMap, |
| 2926 |
Path((owner, name, number, job)): Path<(String, String, i64, String)>, |
| 2927 |
) -> Result<Json<serde_json::Value>, ApiError> { |
| 2928 |
decide_flow_job(&app, &headers, &owner, &name, number, &job, false).await |
| 2929 |
} |
| 2930 |
|
| 47e37402 Andy McCall ↶ |
2931 |
|
| 2932 |
|
| 2933 |
async fn flow_job_statement( |
| 2934 |
State(app): State<Shared>, |
| 2935 |
headers: HeaderMap, |
| 2936 |
Path((owner, name, number, job)): Path<(String, String, i64, String)>, |
| 2937 |
) -> Result<Json<serde_json::Value>, ApiError> { |
| 2938 |
let c = caller(&app, &headers).await?; |
| 2939 |
let (_, row, _) = reach(&app, &c, &owner, &name, Access::Read).await?; |
| 2940 |
let run = db::flow::run(&app.db, row.id, number).await?.ok_or_else(|| ApiError(StatusCode::NOT_FOUND, "no such run".into()))?; |
| 2941 |
let (s, j) = crate::flow::approval_statement(&app, &row, &run, &job).await.map_err(|m| ApiError(StatusCode::CONFLICT, m))?; |
| 2942 |
Ok(Json(serde_json::json!({ |
| 2943 |
"repo": hex::encode(s.repo), |
| 2944 |
"run": s.run, |
| 2945 |
"job": s.job, |
| 2946 |
"job_hash": s.job_hash.to_hex(), |
| 2947 |
"state": s.state.to_hex(), |
| 2948 |
"inputs": s.inputs.iter().map(|i| i.to_hex()).collect::<Vec<_>>(), |
| 2949 |
"environment": s.environment, |
| 2950 |
"waiting": j.approval == "waiting" && j.status == "queued", |
| 2951 |
}))) |
| 2952 |
} |
| 2953 |
|
| 2954 |
#[derive(Deserialize)] |
| 2955 |
struct SealBody { |
| 2956 |
signed: String, |
| 2957 |
} |
| 2958 |
|
| 2959 |
|
| 2960 |
|
| 2961 |
|
| 2962 |
async fn seal_flow_job( |
| 2963 |
State(app): State<Shared>, |
| 2964 |
headers: HeaderMap, |
| 2965 |
Path((owner, name, number, job)): Path<(String, String, i64, String)>, |
| 2966 |
Json(body): Json<SealBody>, |
| 2967 |
) -> Result<Json<serde_json::Value>, ApiError> { |
| 2968 |
let c = caller(&app, &headers).await?; |
| 2969 |
let (_, row, _) = reach(&app, &c, &owner, &name, Access::Read).await?; |
| 2970 |
let run = db::flow::run(&app.db, row.id, number).await?.ok_or_else(|| ApiError(StatusCode::NOT_FOUND, "no such run".into()))?; |
| 2971 |
let said = crate::flow::decide_sealed(&app, &row, &run, &job, &body.signed).await.map_err(|m| ApiError(StatusCode::CONFLICT, m))?; |
| 2972 |
Ok(Json(serde_json::json!({ "number": number, "job": job, "said": said }))) |
| 2973 |
} |
| 2974 |
|
| 417184c7 Andy McCall ↶ |
2975 |
async fn decide_flow_job( |
| 2976 |
app: &Shared, |
| 2977 |
headers: &HeaderMap, |
| 2978 |
owner: &str, |
| 2979 |
name: &str, |
| 2980 |
number: i64, |
| 2981 |
job: &str, |
| 2982 |
approve: bool, |
| 2983 |
) -> Result<Json<serde_json::Value>, ApiError> { |
| 2984 |
let c = caller(app, headers).await?; |
| 2985 |
let me = c.require("repo:write")?.clone(); |
| 2986 |
let (_, row, _) = reach(app, &c, owner, name, Access::Read).await?; |
| 2987 |
let run = db::flow::run(&app.db, row.id, number).await?.ok_or_else(|| ApiError(StatusCode::NOT_FOUND, "no such run".into()))?; |
| 05f1a85a Andy McCall ↶ |
2988 |
let via = c.agent.then_some(c.token.as_str()); |
| 2989 |
let said = crate::flow::decide(app, &row, &run, job, &me, approve, via).await.map_err(|m| ApiError(StatusCode::CONFLICT, m))?; |
| 417184c7 Andy McCall ↶ |
2990 |
Ok(Json(serde_json::json!({ "number": number, "job": job, "decision": if approve { "approved" } else { "rejected" }, "said": said }))) |
| 2991 |
} |
| 2992 |
|
| b64e2537 Andy McCall ↶ |
2993 |
|
| 2994 |
|
| 2995 |
async fn post_check( |
| 2996 |
State(app): State<Shared>, |
| 2997 |
headers: HeaderMap, |
| 2998 |
Path((owner, name)): Path<(String, String)>, |
| 2999 |
Json(body): Json<NewCheck>, |
| 3000 |
) -> Result<(StatusCode, Json<Check>), ApiError> { |
| 3001 |
let c = caller(&app, &headers).await?; |
| 3002 |
let me = c.require("checks:write").or_else(|_| c.require("repo:write"))?.clone(); |
| 3003 |
let (_, row, _) = reach(&app, &c, &owner, &name, Access::Read).await?; |
| 3004 |
if body.state.len() != 64 || !body.state.chars().all(|ch| ch.is_ascii_hexdigit()) { |
| 3005 |
return Err(ApiError(StatusCode::BAD_REQUEST, "state is a 64-character hex state hash".into())); |
| 3006 |
} |
| 3007 |
if body.name.trim().is_empty() || body.name.len() > 100 { |
| 3008 |
return Err(ApiError(StatusCode::BAD_REQUEST, "a check has a short name".into())); |
| 3009 |
} |
| 3010 |
let ch = db::hooks::upsert_check( |
| 3011 |
&app.db, |
| 3012 |
row.id, |
| 3013 |
&body.state, |
| 3014 |
body.name.trim(), |
| 3015 |
body.status.as_str(), |
| 3016 |
&body.summary, |
| 3017 |
&body.url, |
| 3018 |
Some((me.id, &me.username)), |
| 3019 |
body.seal.as_deref().unwrap_or(""), |
| 3020 |
) |
| 3021 |
.await?; |
| 3022 |
let api = check_of(&ch); |
| 33d98147 Andy McCall |
3023 |
app.bus.proposal(row.id, ProposalEvent { number: 0, kind: "check".into(), check: Some(api.clone()) }); |
| b64e2537 Andy McCall ↶ |
3024 |
crate::hooks::emit(&app, &row, "check", &me.username, serde_json::json!({ "check": api })).await; |
| 3025 |
Ok((StatusCode::CREATED, Json(api))) |
| d23464c0 Andy McCall ↶ |
3026 |
} |
| 3027 |
|
| b64e2537 Andy McCall ↶ |
3028 |
async fn checks_for_state( |
| 3029 |
State(app): State<Shared>, |
| 3030 |
headers: HeaderMap, |
| 3031 |
Path((owner, name, state)): Path<(String, String, String)>, |
| 3032 |
) -> Result<Json<Vec<Check>>, ApiError> { |
| 3033 |
let c = caller(&app, &headers).await?; |
| 90326c96 Andy McCall ↶ |
3034 |
let (repo, row, _) = reach(&app, &c, &owner, &name, Access::Read).await?; |
| 3035 |
let state = state_key(&app, &repo, &state).await?; |
| b64e2537 Andy McCall ↶ |
3036 |
Ok(Json(db::hooks::checks_for_state(&app.db, row.id, &state).await?.iter().map(check_of).collect())) |
| 90326c96 Andy McCall ↶ |
3037 |
} |
| 3038 |
|
| 3039 |
|
| 3040 |
|
| 3041 |
|
| 3042 |
async fn state_key(app: &Shared, repo: &RepoName, s: &str) -> Result<String, ApiError> { |
| 3043 |
use oxy_core::hash::{hash_object, ChangeHash, ObjectType}; |
| 3044 |
let hexes: Vec<&str> = s.split('+').collect(); |
| 3045 |
let all_hashes = hexes.iter().all(|h| h.len() == 64 && h.bytes().all(|b| b.is_ascii_hexdigit())); |
| 3046 |
if all_hashes { |
| 3047 |
let row = db::repos::get(&app.db, &repo.owner, &repo.name).await?.ok_or_else(|| not_found("no such repository"))?; |
| 3048 |
if hexes.len() == 1 && !db::hooks::checks_for_state(&app.db, row.id, s).await?.is_empty() { |
| 3049 |
return Ok(s.to_string()); |
| 3050 |
} |
| 3051 |
let heads: Vec<ChangeHash> = hexes.iter().filter_map(|h| ChangeHash::from_hex(h)).collect(); |
| 3052 |
return Ok(hash_object(ObjectType::State, &oxy_core::objects::StateObject::new(heads).encode()).to_hex()); |
| 3053 |
} |
| 3054 |
let b = s.to_string(); |
| 3055 |
let found = app.repos.read(repo, move |r, _| Ok(r.view()?.bookmarks.get(&b).copied())).await?; |
| 3056 |
found.map(|st| st.to_hex()).ok_or_else(|| ApiError(StatusCode::NOT_FOUND, format!("{s:?} is not a state hash, heads or a bookmark"))) |
| d23464c0 Andy McCall ↶ |
3057 |
} |
| b66e70b7 Andy McCall ↶ |
3058 |
|
| 3059 |
|
| 3060 |
|
| 3061 |
|
| 3062 |
fn require_site_admin(c: &Caller) -> Result<&Account, ApiError> { |
| 3063 |
match c.account.as_ref() { |
| 3064 |
Some(a) if a.is_admin => Ok(a), |
| 3065 |
_ => Err(not_found("no such API route")), |
| 3066 |
} |
| 3067 |
} |
| 3068 |
|
| 9bbca80f Andy McCall ↶ |
3069 |
|
| 3070 |
async fn runner_updates(State(app): State<Shared>, headers: HeaderMap) -> Result<Json<RunnerUpdates>, ApiError> { |
| 3071 |
let c = caller(&app, &headers).await?; |
| 3072 |
require_site_admin(&c)?; |
| 3073 |
use crate::web::runner_updates::{views, Reach}; |
| 3074 |
let v = views(&app, &Reach::Site).await?; |
| 3075 |
let setting = |p: &crate::web::runner_updates::PolicyView| UpdateSetting { |
| 3076 |
scope: p.scope.clone(), |
| 3077 |
key: p.key.clone(), |
| 3078 |
updates: match p.updates { |
| 3079 |
"on" => Some(true), |
| 3080 |
"off" => Some(false), |
| 3081 |
_ => None, |
| 3082 |
}, |
| 3083 |
channel: Some(p.channel.clone()).filter(|c| !c.is_empty()), |
| 3084 |
window: Some(p.window.clone()).filter(|w| !w.is_empty()), |
| 3085 |
dry_run: match p.dry_run { |
| 3086 |
"on" => Some(true), |
| 3087 |
"off" => Some(false), |
| 3088 |
_ => None, |
| 3089 |
}, |
| 3090 |
}; |
| 3091 |
let mut settings = vec![setting(&v.site)]; |
| 3092 |
settings.extend(v.owners.iter().map(setting)); |
| 3093 |
settings.extend(v.groups.iter().map(|g| setting(&g.policy))); |
| 3094 |
settings.extend(v.runners.iter().map(|r| setting(&r.policy))); |
| 3095 |
settings.retain(|s| s.scope == "site" || s.updates.is_some() || s.channel.is_some() || s.window.is_some() || s.dry_run.is_some()); |
| 3096 |
Ok(Json(RunnerUpdates { |
| 3097 |
repo: db::accounts::setting(&app.db, crate::runner_updates::SETTING_REPO).await?.unwrap_or_default(), |
| 3098 |
settings, |
| 3099 |
groups: v |
| 3100 |
.groups |
| 3101 |
.iter() |
| 3102 |
.map(|g| RunnerGroup { |
| 3103 |
id: g.g.id, |
| 3104 |
owner: g.g.owner.clone(), |
| 3105 |
name: g.g.name.clone(), |
| 3106 |
percent: g.g.percent, |
| 3107 |
members: g.members.clone(), |
| 1ec29691 Andy McCall ↶ |
3108 |
wave: g.g.wave, |
| 9bbca80f Andy McCall ↶ |
3109 |
}) |
| 3110 |
.collect(), |
| 3111 |
runners: v |
| 3112 |
.runners |
| 3113 |
.iter() |
| 3114 |
.map(|r| RunnerUpdate { |
| 3115 |
id: r.r.id, |
| 3116 |
name: r.r.name.clone(), |
| 3117 |
owner: r.r.scope_owner.clone(), |
| 3118 |
version: r.r.version.clone(), |
| 3119 |
groups: r.groups.clone(), |
| 3120 |
updates: r.effective.updates, |
| 3121 |
channel: r.effective.channel.clone(), |
| 3122 |
window: r.effective.window.map(|(a, b)| format!("{a:02}-{b:02}")), |
| 3123 |
dry_run: r.effective.dry_run, |
| 3124 |
from: r.effective.from.clone(), |
| 3125 |
now: r.offer.clone(), |
| 3126 |
said: r.r.update_note.clone(), |
| 3127 |
}) |
| 3128 |
.collect(), |
| 3129 |
holds: db::runner_updates::holds(&app.db) |
| 3130 |
.await? |
| 3131 |
.into_iter() |
| 3132 |
.map(|h| HeldBuild { version: h.version, runner: h.runner, why: h.why, at_ms: h.at_ms }) |
| 3133 |
.collect(), |
| 3134 |
})) |
| 3135 |
} |
| 3136 |
|
| 3137 |
|
| 3138 |
|
| 3139 |
async fn runner_update_setting( |
| 3140 |
State(app): State<Shared>, |
| 3141 |
headers: HeaderMap, |
| 3142 |
Json(u): Json<UpdateSetting>, |
| 3143 |
) -> Result<Json<serde_json::Value>, ApiError> { |
| 3144 |
let c = caller(&app, &headers).await?; |
| 3145 |
let me = require_site_admin(&c)?.clone(); |
| 3146 |
use crate::web::runner_updates::{apply_policy, PolicyForm, Reach}; |
| 3147 |
match apply_policy(&app, &me, &Reach::Site, &PolicyForm::of(&u)).await? { |
| 3148 |
Ok(notice) => Ok(Json(serde_json::json!({ "notice": notice }))), |
| 3149 |
Err(why) => Err(ApiError(StatusCode::UNPROCESSABLE_ENTITY, why)), |
| 3150 |
} |
| 3151 |
} |
| 3152 |
|
| 3153 |
|
| 3154 |
async fn runner_update_lift(State(app): State<Shared>, headers: HeaderMap, Path(version): Path<String>) -> Result<StatusCode, ApiError> { |
| 3155 |
let c = caller(&app, &headers).await?; |
| 3156 |
let me = require_site_admin(&c)?.clone(); |
| 3157 |
if !db::runner_updates::lift(&app.db, &version).await? { |
| 3158 |
return Err(not_found("that build is not held")); |
| 3159 |
} |
| 3160 |
db::accounts::audit(&app.db, Some(&me), "runner.update.lifted", &version, "offered again").await.ok(); |
| 3161 |
Ok(StatusCode::NO_CONTENT) |
| 3162 |
} |
| 3163 |
|
| b66e70b7 Andy McCall ↶ |
3164 |
async fn runner_of(app: &Shared, r: db::runners::Runner, running: i64) -> hub_api::Runner { |
| 3165 |
let serves = match r.scope_repo_id { |
| 3166 |
Some(id) => db::repos::get_by_id(&app.db, id).await.ok().flatten().map(|p| p.slug()).unwrap_or_default(), |
| 3167 |
None => r.scope_owner.clone(), |
| 3168 |
}; |
| 3169 |
hub_api::Runner { |
| 3170 |
id: r.id, |
| 3171 |
status: r.status().to_string(), |
| 3172 |
serves, |
| 3173 |
labels: r.label_list().into_iter().map(String::from).collect(), |
| 3174 |
name: r.name, |
| 3175 |
arch: r.arch, |
| 3176 |
os: r.os, |
| 3177 |
version: r.version, |
| 3178 |
max_jobs: r.max_jobs, |
| 3179 |
memory_mib: r.memory_mib, |
| 3180 |
cpus: r.cpus, |
| 3181 |
key: r.key, |
| 3182 |
source: r.source, |
| 3183 |
last_seen_ms: r.last_seen_ms, |
| 3184 |
running, |
| 2fb70d01 Andy McCall ↶ |
3185 |
free_disk_mib: r.free_disk_mib, |
| 3186 |
load_x100: r.load_x100, |
| 3187 |
speed: r.speed, |
| 3188 |
speed_class: r.speed_class, |
| 3189 |
kernel: r.kernel, |
| b66e70b7 Andy McCall ↶ |
3190 |
} |
| 3191 |
} |
| 3192 |
|
| 3193 |
|
| 3194 |
async fn runners(State(app): State<Shared>, headers: HeaderMap) -> Result<Json<Vec<hub_api::Runner>>, ApiError> { |
| 3195 |
let c = caller(&app, &headers).await?; |
| 3196 |
require_site_admin(&c)?; |
| 3197 |
let running: std::collections::HashMap<i64, i64> = db::runners::running(&app.db).await?.into_iter().collect(); |
| 3198 |
let mut out = Vec::new(); |
| 3199 |
for r in db::runners::list(&app.db).await? { |
| 3200 |
let n = running.get(&r.id).copied().unwrap_or(0); |
| 3201 |
out.push(runner_of(&app, r, n).await); |
| 3202 |
} |
| 3203 |
Ok(Json(out)) |
| 3204 |
} |
| 3205 |
|
| 3206 |
#[derive(Deserialize)] |
| 3207 |
struct BeforeQuery { |
| 3208 |
#[serde(default)] |
| 3209 |
before: Option<i64>, |
| 3210 |
#[serde(default)] |
| 3211 |
limit: Option<i64>, |
| 3212 |
} |
| 3213 |
|
| 3214 |
|
| 3215 |
async fn runner_jobs( |
| 3216 |
State(app): State<Shared>, |
| 3217 |
headers: HeaderMap, |
| 3218 |
Path(id): Path<i64>, |
| 3219 |
Query(q): Query<BeforeQuery>, |
| 3220 |
) -> Result<Json<Vec<hub_api::RunnerJob>>, ApiError> { |
| 3221 |
let c = caller(&app, &headers).await?; |
| 3222 |
require_site_admin(&c)?; |
| 3223 |
db::runners::get(&app.db, id).await?.ok_or_else(|| not_found("no such runner"))?; |
| 3224 |
let jobs = db::runners::history(&app.db, id, q.limit.unwrap_or(50).clamp(1, 200), q.before).await?; |
| 3225 |
Ok(Json( |
| 3226 |
jobs.into_iter() |
| 3227 |
.map(|j| hub_api::RunnerJob { |
| 3228 |
repo: format!("{}/{}", j.owner, j.repo), |
| 3229 |
run: j.run_number, |
| 3230 |
job: j.job, |
| 3231 |
status: j.status, |
| 3232 |
started_ms: j.started_ms, |
| 3233 |
finished_ms: j.finished_ms, |
| 3234 |
}) |
| 3235 |
.collect(), |
| 3236 |
)) |
| 3237 |
} |
| 3238 |
|
| 3239 |
|
| 3240 |
async fn runner_queue(State(app): State<Shared>, headers: HeaderMap) -> Result<Json<Vec<hub_api::QueueItem>>, ApiError> { |
| 3241 |
let c = caller(&app, &headers).await?; |
| 3242 |
require_site_admin(&c)?; |
| 3243 |
Ok(Json( |
| 3244 |
db::flow::queue(&app.db) |
| 3245 |
.await? |
| 3246 |
.into_iter() |
| 3247 |
.map(|e| hub_api::QueueItem { |
| 3248 |
repo: format!("{}/{}", e.owner, e.name), |
| 3249 |
run: e.run_number, |
| 3250 |
job: e.job, |
| 3251 |
status: e.status, |
| 3252 |
runner: e.runner, |
| 3253 |
}) |
| 3254 |
.collect(), |
| 3255 |
)) |
| 3256 |
} |
| 7d2eb590 Andy McCall ↶ |
3257 |
|
| 3258 |
|
| 3259 |
|
| 3260 |
|
| 3261 |
async fn request_assistant( |
| 3262 |
State(app): State<Shared>, |
| 3263 |
headers: HeaderMap, |
| 3264 |
Path((owner, name, number)): Path<(String, String, i64)>, |
| 3265 |
Json(body): Json<hub_api::AssistantRequest>, |
| 3266 |
) -> Result<(StatusCode, Json<hub_api::AssistantRequest>), ApiError> { |
| 3267 |
let c = caller(&app, &headers).await?; |
| 3268 |
let me = c.require("proposals:write").or_else(|_| c.require("repo:write"))?.clone(); |
| 3269 |
let (_, row, role) = reach(&app, &c, &owner, &name, Access::Read).await?; |
| 3270 |
let p = db::proposals::get(&app.db, row.id, number).await?.ok_or_else(|| not_found("no such proposal"))?; |
| 3271 |
if Some(me.id) != p.author_id && role < Role::Write { |
| 3272 |
return Err(forbidden("only the author or a writer asks for reviews")); |
| 3273 |
} |
| 3274 |
if !p.is_open() { |
| 3275 |
return Err(ApiError(StatusCode::CONFLICT, "the proposal is not open".into())); |
| 3276 |
} |
| 3277 |
let a = crate::assistants::enabled_for_repo(&app.db, &row) |
| 3278 |
.await? |
| 3279 |
.into_iter() |
| 3280 |
.find(|a| a.name.eq_ignore_ascii_case(body.assistant.trim())) |
| 3281 |
.ok_or_else(|| ApiError(StatusCode::UNPROCESSABLE_ENTITY, format!("no assistant called {} here", body.assistant.trim())))?; |
| 3282 |
let asked = hub_api::AssistantRequest { assistant: a.name.clone() }; |
| 3283 |
crate::assistants::request_review(&app, &row, &p, &me, a).await.map_err(|e| ApiError(StatusCode::CONFLICT, e))?; |
| 3284 |
Ok((StatusCode::ACCEPTED, Json(asked))) |
| 3285 |
} |
| 62ceb2ee Andy McCall ↶ |
3286 |
|
| 3287 |
|
| 3288 |
|
| 3289 |
use crate::levels::At; |
| 3290 |
use crate::web::assistants as aa; |
| 3291 |
|
| 3292 |
|
| 3293 |
async fn repo_level(app: &Shared, c: &Caller, owner: &str, name: &str) -> Result<(Account, At), ApiError> { |
| 3294 |
let me = c.require("repo:admin")?.clone(); |
| 3295 |
let (_, row, _) = reach(app, c, owner, name, Access::Admin).await?; |
| 3296 |
Ok((me, At::repo(&row))) |
| 3297 |
} |
| 3298 |
|
| 3299 |
|
| 3300 |
async fn org_level(app: &Shared, c: &Caller, org: &str) -> Result<(Account, At), ApiError> { |
| 3301 |
let me = c.require("repo:admin")?.clone(); |
| 3302 |
let o = db::accounts::org_by_name(&app.db, org).await?.ok_or_else(|| not_found("no such organisation"))?; |
| 3303 |
if !auth::roles::is_org_owner(&app.db, &me, o.id).await? { |
| 3304 |
return Err(not_found("no such organisation")); |
| 3305 |
} |
| 3306 |
Ok((me, At::org(&o))) |
| 3307 |
} |
| 3308 |
|
| 3309 |
|
| 3310 |
fn site_level(c: &Caller) -> Result<(Account, At), ApiError> { |
| 3311 |
Ok((require_site_admin(c)?.clone(), At::site())) |
| 3312 |
} |
| 3313 |
|
| 3314 |
fn put_outcome(r: Result<String, String>) -> Result<(StatusCode, Json<serde_json::Value>), ApiError> { |
| 3315 |
match r { |
| 3316 |
Ok(msg) => Ok((StatusCode::OK, Json(serde_json::json!({ "ok": msg })))), |
| 3317 |
Err(e) => Err(ApiError(StatusCode::UNPROCESSABLE_ENTITY, e)), |
| 3318 |
} |
| 3319 |
} |
| 3320 |
|
| 3321 |
macro_rules! assistant_routes { |
| 3322 |
($list:ident, $put:ident, $del:ident, $prompt:ident, $prompt_put:ident, ($($p:ident: $t:ty),*), $level:expr) => { |
| 3323 |
async fn $list(State(app): State<Shared>, headers: HeaderMap, Path(($($p),*)): Path<($($t),*)>) -> Result<Json<Vec<Assistant>>, ApiError> { |
| 3324 |
let c = caller(&app, &headers).await?; |
| 3325 |
let (_, at) = $level(&app, &c, $(&$p),*).await?; |
| 3326 |
Ok(Json(aa::api_list(&app, &at).await?)) |
| 3327 |
} |
| 3328 |
async fn $put( |
| 3329 |
State(app): State<Shared>, |
| 3330 |
headers: HeaderMap, |
| 3331 |
Path(($($p),*)): Path<($($t),*)>, |
| 3332 |
Json(body): Json<NewAssistant>, |
| 3333 |
) -> Result<(StatusCode, Json<serde_json::Value>), ApiError> { |
| 3334 |
let c = caller(&app, &headers).await?; |
| 3335 |
let (me, at) = $level(&app, &c, $(&$p),*).await?; |
| 3336 |
put_outcome(aa::api_put(&app, &me, &at, body).await?) |
| 3337 |
} |
| 3338 |
async fn $prompt(State(app): State<Shared>, headers: HeaderMap, Path(($($p),*)): Path<($($t),*)>) -> Result<Json<AssistantPrompt>, ApiError> { |
| 3339 |
let c = caller(&app, &headers).await?; |
| 3340 |
let (_, at) = $level(&app, &c, $(&$p),*).await?; |
| 3341 |
Ok(Json(aa::api_prompt(&app, &at).await?)) |
| 3342 |
} |
| 3343 |
async fn $prompt_put( |
| 3344 |
State(app): State<Shared>, |
| 3345 |
headers: HeaderMap, |
| 3346 |
Path(($($p),*)): Path<($($t),*)>, |
| 3347 |
Json(body): Json<AssistantPrompt>, |
| 3348 |
) -> Result<Json<AssistantPrompt>, ApiError> { |
| 3349 |
let c = caller(&app, &headers).await?; |
| 3350 |
let (me, at) = $level(&app, &c, $(&$p),*).await?; |
| 3351 |
aa::api_set_prompt(&app, &me, &at, &body.prompt).await?.map_err(|e| ApiError(StatusCode::UNPROCESSABLE_ENTITY, e))?; |
| 3352 |
Ok(Json(aa::api_prompt(&app, &at).await?)) |
| 3353 |
} |
| 3354 |
}; |
| 3355 |
} |
| 3356 |
|
| 3357 |
assistant_routes!(repo_assistants, repo_assistant_put, _rd, repo_prompt, repo_prompt_put, (owner: String, name: String), repo_level); |
| 3358 |
|
| 3359 |
async fn repo_assistant_delete( |
| 3360 |
State(app): State<Shared>, |
| 3361 |
headers: HeaderMap, |
| 3362 |
Path((owner, name, assistant)): Path<(String, String, String)>, |
| 3363 |
) -> Result<StatusCode, ApiError> { |
| 3364 |
let c = caller(&app, &headers).await?; |
| 3365 |
let (me, at) = repo_level(&app, &c, &owner, &name).await?; |
| 3366 |
if aa::api_delete(&app, &me, &at, &assistant).await? { |
| 3367 |
Ok(StatusCode::NO_CONTENT) |
| 3368 |
} else { |
| 3369 |
Err(not_found("no such assistant at this level")) |
| 3370 |
} |
| 3371 |
} |
| 3372 |
|
| 3373 |
async fn org_level_one(app: &Shared, c: &Caller, org: &str) -> Result<(Account, At), ApiError> { |
| 3374 |
org_level(app, c, org).await |
| 3375 |
} |
| 3376 |
|
| 3377 |
async fn org_assistants(State(app): State<Shared>, headers: HeaderMap, Path(org): Path<String>) -> Result<Json<Vec<Assistant>>, ApiError> { |
| 3378 |
let c = caller(&app, &headers).await?; |
| 3379 |
let (_, at) = org_level_one(&app, &c, &org).await?; |
| 3380 |
Ok(Json(aa::api_list(&app, &at).await?)) |
| 3381 |
} |
| 3382 |
|
| 3383 |
async fn org_assistant_put( |
| 3384 |
State(app): State<Shared>, |
| 3385 |
headers: HeaderMap, |
| 3386 |
Path(org): Path<String>, |
| 3387 |
Json(body): Json<NewAssistant>, |
| 3388 |
) -> Result<(StatusCode, Json<serde_json::Value>), ApiError> { |
| 3389 |
let c = caller(&app, &headers).await?; |
| 3390 |
let (me, at) = org_level_one(&app, &c, &org).await?; |
| 3391 |
put_outcome(aa::api_put(&app, &me, &at, body).await?) |
| 3392 |
} |
| 3393 |
|
| 3394 |
async fn org_assistant_delete( |
| 3395 |
State(app): State<Shared>, |
| 3396 |
headers: HeaderMap, |
| 3397 |
Path((org, assistant)): Path<(String, String)>, |
| 3398 |
) -> Result<StatusCode, ApiError> { |
| 3399 |
let c = caller(&app, &headers).await?; |
| 3400 |
let (me, at) = org_level_one(&app, &c, &org).await?; |
| 3401 |
if aa::api_delete(&app, &me, &at, &assistant).await? { |
| 3402 |
Ok(StatusCode::NO_CONTENT) |
| 3403 |
} else { |
| 3404 |
Err(not_found("no such assistant at this level")) |
| 3405 |
} |
| 3406 |
} |
| 3407 |
|
| 3408 |
async fn org_prompt(State(app): State<Shared>, headers: HeaderMap, Path(org): Path<String>) -> Result<Json<AssistantPrompt>, ApiError> { |
| 3409 |
let c = caller(&app, &headers).await?; |
| 3410 |
let (_, at) = org_level_one(&app, &c, &org).await?; |
| 3411 |
Ok(Json(aa::api_prompt(&app, &at).await?)) |
| 3412 |
} |
| 3413 |
|
| 3414 |
async fn org_prompt_put( |
| 3415 |
State(app): State<Shared>, |
| 3416 |
headers: HeaderMap, |
| 3417 |
Path(org): Path<String>, |
| 3418 |
Json(body): Json<AssistantPrompt>, |
| 3419 |
) -> Result<Json<AssistantPrompt>, ApiError> { |
| 3420 |
let c = caller(&app, &headers).await?; |
| 3421 |
let (me, at) = org_level_one(&app, &c, &org).await?; |
| 3422 |
aa::api_set_prompt(&app, &me, &at, &body.prompt).await?.map_err(|e| ApiError(StatusCode::UNPROCESSABLE_ENTITY, e))?; |
| 3423 |
Ok(Json(aa::api_prompt(&app, &at).await?)) |
| 3424 |
} |
| 3425 |
|
| 3426 |
async fn site_assistants(State(app): State<Shared>, headers: HeaderMap) -> Result<Json<Vec<Assistant>>, ApiError> { |
| 3427 |
let c = caller(&app, &headers).await?; |
| 3428 |
let (_, at) = site_level(&c)?; |
| 3429 |
Ok(Json(aa::api_list(&app, &at).await?)) |
| 3430 |
} |
| 3431 |
|
| 3432 |
async fn site_assistant_put( |
| 3433 |
State(app): State<Shared>, |
| 3434 |
headers: HeaderMap, |
| 3435 |
Json(body): Json<NewAssistant>, |
| 3436 |
) -> Result<(StatusCode, Json<serde_json::Value>), ApiError> { |
| 3437 |
let c = caller(&app, &headers).await?; |
| 3438 |
let (me, at) = site_level(&c)?; |
| 3439 |
put_outcome(aa::api_put(&app, &me, &at, body).await?) |
| 3440 |
} |
| 3441 |
|
| 3442 |
async fn site_assistant_delete( |
| 3443 |
State(app): State<Shared>, |
| 3444 |
headers: HeaderMap, |
| 3445 |
Path(assistant): Path<String>, |
| 3446 |
) -> Result<StatusCode, ApiError> { |
| 3447 |
let c = caller(&app, &headers).await?; |
| 3448 |
let (me, at) = site_level(&c)?; |
| 3449 |
if aa::api_delete(&app, &me, &at, &assistant).await? { |
| 3450 |
Ok(StatusCode::NO_CONTENT) |
| 3451 |
} else { |
| 3452 |
Err(not_found("no such assistant at this level")) |
| 3453 |
} |
| 3454 |
} |
| 3455 |
|
| 3456 |
async fn site_prompt(State(app): State<Shared>, headers: HeaderMap) -> Result<Json<AssistantPrompt>, ApiError> { |
| 3457 |
let c = caller(&app, &headers).await?; |
| 3458 |
let (_, at) = site_level(&c)?; |
| 3459 |
Ok(Json(aa::api_prompt(&app, &at).await?)) |
| 3460 |
} |
| 3461 |
|
| 3462 |
async fn site_prompt_put( |
| 3463 |
State(app): State<Shared>, |
| 3464 |
headers: HeaderMap, |
| 3465 |
Json(body): Json<AssistantPrompt>, |
| 3466 |
) -> Result<Json<AssistantPrompt>, ApiError> { |
| 3467 |
let c = caller(&app, &headers).await?; |
| 3468 |
let (me, at) = site_level(&c)?; |
| 3469 |
aa::api_set_prompt(&app, &me, &at, &body.prompt).await?.map_err(|e| ApiError(StatusCode::UNPROCESSABLE_ENTITY, e))?; |
| 3470 |
Ok(Json(aa::api_prompt(&app, &at).await?)) |
| 3471 |
} |