1use std::net::Ipv4Addr;
8use std::sync::Arc;
9
10use axum::extract::{Query, Request, State};
11use axum::http::{header, StatusCode, Uri};
12use axum::middleware::{self, Next};
13use axum::response::{IntoResponse, Json, Response};
14use axum::routing::{get, post};
15use axum::Router;
16use forgetop_core::cache::CacheStore;
17use forgetop_core::provider::{ItemRef, PrDecoration};
18use forgetop_core::secret::SecretStore;
19use forgetop_core::service::{ConfigService, ConnectionHealthService, SectionService};
20use rust_embed::RustEmbed;
21use serde::Deserialize;
22
23use crate::actions::ActionError;
24
25pub mod cached;
26
27mod actions;
28mod connections;
29mod dto;
30
31#[derive(RustEmbed)]
33#[folder = "web/dist"]
34struct Assets;
35
36pub const DEFAULT_PORT: u16 = 8177;
38
39#[derive(Clone)]
42pub struct Deps {
43 pub sections: Arc<SectionService>,
44 pub health: Arc<ConnectionHealthService>,
45 pub config: Arc<ConfigService>,
46 pub secrets: Arc<dyn SecretStore>,
47 pub cache: Arc<CacheStore>,
51}
52
53pub struct Server {
55 pub port: u16,
56 pub token: String,
57 pub url: String,
59}
60
61#[derive(Default)]
66struct DecorationCache {
67 entries: std::sync::Mutex<std::collections::HashMap<String, PrDecoration>>,
68}
69
70impl DecorationCache {
71 const MAX: usize = 500;
74
75 fn key(conn: &str, item: &ItemRef, updated_at: Option<&str>) -> String {
76 format!("{conn}\u{1}{}\u{1}{}\u{1}{}", item.repo.as_deref().unwrap_or(""), item.id, updated_at.unwrap_or(""))
77 }
78
79 fn get(&self, key: &str) -> Option<PrDecoration> {
80 self.entries.lock().unwrap().get(key).cloned()
81 }
82
83 fn put(&self, key: String, value: PrDecoration) {
84 let mut entries = self.entries.lock().unwrap();
85 if entries.len() >= Self::MAX {
86 entries.clear();
87 }
88 entries.insert(key, value);
89 }
90}
91
92#[derive(Clone)]
93struct AppState {
94 deps: Deps,
95 token: Arc<str>,
96 decorations: Arc<DecorationCache>,
97 inflight: Arc<std::sync::Mutex<std::collections::HashSet<String>>>,
100 flusher: Arc<cached::Flusher>,
101}
102
103async fn bind(deps: Deps, port: u16) -> std::io::Result<(tokio::net::TcpListener, Server, AppState)> {
104 let token = uuid::Uuid::new_v4().to_string();
105 let listener = tokio::net::TcpListener::bind((Ipv4Addr::LOCALHOST, port)).await?;
106 let bound = listener.local_addr()?.port();
107 let url = format!("http://127.0.0.1:{bound}/?t={token}");
108 let flusher = Arc::new(cached::Flusher::new(deps.cache.clone()));
109 let state = AppState {
110 deps,
111 token: Arc::from(token.as_str()),
112 decorations: Arc::new(DecorationCache::default()),
113 inflight: Arc::new(std::sync::Mutex::new(std::collections::HashSet::new())),
114 flusher,
115 };
116 Ok((listener, Server { port: bound, token, url }, state))
117}
118
119pub async fn spawn(deps: Deps, port: u16) -> std::io::Result<Server> {
122 let (listener, server, state) = bind(deps, port).await?;
123 tokio::spawn(async move {
124 let _ = axum::serve(listener, router(state)).await;
125 });
126 Ok(server)
127}
128
129pub async fn serve_blocking(deps: Deps, port: u16, on_ready: impl FnOnce(&str)) -> std::io::Result<()> {
132 let (listener, server, state) = bind(deps, port).await?;
133 on_ready(&server.url);
134 axum::serve(listener, router(state)).await
135}
136
137fn router(state: AppState) -> Router {
138 let api = Router::new()
142 .route("/api/health", get(health))
143 .route("/api/pull-requests", get(pull_requests))
144 .route("/api/work-items", get(work_items))
145 .route("/api/pipelines", get(pipelines))
146 .route("/api/notifications", get(notifications))
147 .route("/api/launchpad", get(launchpad))
148 .route("/api/pr/detail", get(pr_detail))
149 .route("/api/pr/decoration", get(pr_decoration))
150 .route("/api/pr/commit-changes", get(pr_commit_changes))
151 .route("/api/pr/file-text", get(pr_file_text))
152 .route("/api/pr/vote", post(pr_vote))
153 .route("/api/pr/merge", post(pr_merge))
154 .route("/api/pr/revert", post(pr_revert))
155 .route("/api/pr/comment", post(pr_comment))
156 .route("/api/pr/reply", post(pr_reply))
157 .route("/api/pr/review", post(pr_review))
158 .route("/api/pr/resolve-thread", post(pr_resolve_thread))
159 .route("/api/pr/draft", post(pr_draft))
160 .route("/api/pr/closed", post(pr_closed))
161 .route("/api/pr/reviewers", get(pr_reviewers))
162 .route("/api/pr/request-reviewer", post(pr_request_reviewer))
163 .route("/api/wi/detail", get(wi_detail))
164 .route("/api/wi/states", get(wi_states))
165 .route("/api/wi/state", post(wi_state))
166 .route("/api/wi/comment", post(wi_comment))
167 .route("/api/wi/assignees", get(wi_assignees))
168 .route("/api/wi/assignee", post(wi_assignee))
169 .route("/api/wi/update", post(wi_update))
170 .route("/api/pipeline/detail", get(pipeline_detail))
171 .route("/api/pipeline/logs", get(pipeline_logs))
172 .route("/api/pipeline/annotations", get(pipeline_annotations))
173 .route("/api/pipeline/artifacts", get(pipeline_artifacts))
174 .route("/api/pipeline/approval", post(pipeline_approval))
175 .route("/api/pipeline/trigger", post(pipeline_trigger))
176 .route("/api/pipeline/cancel", post(pipeline_cancel))
177 .route("/api/pipeline/rerun", post(pipeline_rerun))
178 .route("/api/notification/read", post(notification_read))
179 .route("/api/providers", get(providers))
180 .route("/api/connections", get(list_connections).post(save_connection))
181 .route("/api/connections/delete", post(delete_connection))
182 .route("/api/connections/test", post(test_connection))
183 .route("/api/connections/repositories", get(connection_repositories))
184 .route("/api/connections/scope", post(set_connection_scope))
185 .route("/api/pipelines/definitions", get(pipeline_definitions))
186 .route("/api/pipelines/selection", post(set_pipeline_selection))
187 .layer(middleware::from_fn_with_state(state.clone(), auth))
188 .with_state(state);
189
190 Router::new().merge(api).fallback(static_asset)
191}
192
193async fn static_asset(uri: Uri) -> Response {
196 let path = uri.path().trim_start_matches('/');
197 let path = if path.is_empty() { "index.html" } else { path };
198 serve(path)
199 .or_else(|| serve("index.html"))
200 .unwrap_or_else(|| (StatusCode::NOT_FOUND, "not found").into_response())
201}
202
203fn serve(path: &str) -> Option<Response> {
204 let file = Assets::get(path)?;
205 let mime = mime_guess::from_path(path).first_or_octet_stream();
206 Some(([(header::CONTENT_TYPE, mime.as_ref().to_string())], file.data).into_response())
207}
208
209async fn auth(State(state): State<AppState>, req: Request, next: Next) -> Response {
213 if token_from(&req).as_deref() == Some(&state.token) {
214 next.run(req).await
215 } else {
216 (StatusCode::UNAUTHORIZED, "unauthorized").into_response()
217 }
218}
219
220fn token_from(req: &Request) -> Option<String> {
221 if let Some(header) = req.headers().get("x-forgetop-token").and_then(|v| v.to_str().ok()) {
222 return Some(header.to_string());
223 }
224 req.uri()
225 .query()
226 .and_then(|q| q.split('&').find_map(|pair| pair.strip_prefix("t=").map(str::to_string)))
227}
228
229async fn health(State(s): State<AppState>) -> Json<Vec<dto::HealthRow>> {
230 Json(dto::health(&s.deps.health).await)
231}
232pub const FETCHED_AT_HEADER: &str = "x-forgetop-fetched-at";
234
235const STALE_WAIT: std::time::Duration = std::time::Duration::from_millis(1500);
240
241fn stale_wait() -> std::time::Duration {
242 std::env::var("FORGETOP_CACHE_WAIT_MS")
243 .ok()
244 .and_then(|v| v.parse().ok())
245 .map(std::time::Duration::from_millis)
246 .unwrap_or(STALE_WAIT)
247}
248
249async fn serve_cached<T, F, Fut>(s: &AppState, key: &str, cached: Option<cached::Cached<T>>, fetch: F) -> Response
255where
256 T: serde::Serialize + Send + 'static,
257 F: FnOnce(AppState) -> Fut + Send + 'static,
258 Fut: std::future::Future<Output = T> + Send + 'static,
259{
260 let claim = |s: &AppState| s.inflight.lock().unwrap_or_else(|p| p.into_inner()).insert(key.to_string());
261 let from_cache = |hit: cached::Cached<T>| {
262 let mut res = Json(hit.value).into_response();
263 if let Ok(v) = hit.fetched_at.to_rfc3339().parse() {
264 res.headers_mut().insert(FETCHED_AT_HEADER, v);
265 }
266 res
267 };
268 if !claim(s) {
269 return match cached {
271 Some(hit) => from_cache(hit),
272 None => Json(fetch(s.clone()).await).into_response(),
273 };
274 }
275 let live = {
276 let s2 = s.clone();
277 let key = key.to_string();
278 tokio::spawn(async move {
279 let value = fetch(s2.clone()).await;
280 s2.inflight.lock().unwrap_or_else(|p| p.into_inner()).remove(&key);
281 s2.flusher.schedule();
282 value
283 })
284 };
285 let Some(hit) = cached else {
286 return match live.await {
287 Ok(value) => Json(value).into_response(),
288 Err(_) => (StatusCode::BAD_GATEWAY, "the fetch behind this list failed").into_response(),
289 };
290 };
291 match tokio::time::timeout(stale_wait(), live).await {
292 Ok(Ok(value)) => Json(value).into_response(),
293 _ => from_cache(hit),
295 }
296}
297
298async fn pull_requests(State(s): State<AppState>, Query(q): Query<PrListQuery>) -> Response {
299 let view = dto::PrView::parse(q.view.as_deref());
300 let hit = cached::pull_requests(&s.deps.cache, view);
301 serve_cached(&s, &format!("prs.{view:?}"), hit, move |s: AppState| async move { dto::pull_requests(&s.deps.sections, &s.deps.cache, view).await }).await
302}
303async fn work_items(State(s): State<AppState>) -> Response {
304 let hit = cached::work_items(&s.deps.cache);
305 serve_cached(&s, "work_items", hit, |s: AppState| async move { dto::work_items(&s.deps.sections, &s.deps.cache).await }).await
306}
307async fn pipelines(State(s): State<AppState>) -> Response {
308 let hit = cached::pipelines(&s.deps.cache);
311 serve_cached(&s, "pipelines", hit, |s: AppState| async move { dto::pipelines(&s.deps.sections).await }).await
312}
313async fn notifications(State(s): State<AppState>) -> Response {
314 let hit = cached::notifications(&s.deps.cache);
315 serve_cached(&s, "notifications", hit, |s: AppState| async move { dto::notifications(&s.deps.sections, &s.deps.cache).await }).await
316}
317async fn launchpad(State(s): State<AppState>) -> Response {
318 let hit = cached::launchpad(&s.deps.cache);
319 serve_cached(&s, "launchpad", hit, |s: AppState| async move { dto::launchpad(&s.deps.sections, &s.deps.cache).await }).await
320}
321
322#[derive(Deserialize)]
328struct ItemQuery {
329 conn: String,
330 id: String,
331 #[serde(default)]
332 repo: Option<String>,
333}
334
335impl ItemQuery {
336 fn item(self) -> (String, ItemRef) {
337 (self.conn, ItemRef::maybe(self.repo, self.id))
338 }
339}
340
341#[derive(Deserialize)]
343struct CommitQuery {
344 conn: String,
345 id: String,
346 sha: String,
347 #[serde(default)]
348 repo: Option<String>,
349}
350
351#[derive(Deserialize)]
354struct FileTextQuery {
355 conn: String,
356 id: String,
357 path: String,
358 #[serde(default)]
359 sha: Option<String>,
360 #[serde(default)]
361 repo: Option<String>,
362}
363
364#[derive(Deserialize)]
366struct PrListQuery {
367 #[serde(default)]
368 view: Option<String>,
369}
370
371#[derive(Deserialize)]
373struct RunQuery {
374 conn: String,
375 run_id: String,
376 #[serde(default)]
377 repo: Option<String>,
378}
379
380#[derive(Deserialize)]
382struct PipelineLogsQuery {
383 conn: String,
384 run_id: String,
385 #[serde(default)]
386 repo: Option<String>,
387 #[serde(default)]
388 job: Option<String>,
389}
390
391fn action_response(operation: &'static str, result: Result<(), ActionError>) -> Response {
394 action_response_with(operation, result.map(|()| serde_json::json!({ "ok": true })))
395}
396
397fn action_response_with(operation: &'static str, result: Result<serde_json::Value, ActionError>) -> Response {
399 match result {
400 Ok(body) => Json(body).into_response(),
401 Err(ActionError::NotFound) => (StatusCode::NOT_FOUND, "connection or capability not found").into_response(),
402 Err(ActionError::Failed(msg)) => {
403 forgetop_core::diag::log(operation, "provider action failed");
404 (StatusCode::BAD_GATEWAY, msg).into_response()
405 }
406 }
407}
408
409async fn pr_commit_changes(State(s): State<AppState>, Query(q): Query<CommitQuery>) -> Response {
410 match dto::pr_commit_changes(&s.deps.sections, &q.conn, &ItemRef::maybe(q.repo, q.id), &q.sha).await {
411 Some(changes) => Json(changes).into_response(),
412 None => (StatusCode::NOT_FOUND, "pull request not found").into_response(),
413 }
414}
415
416async fn pr_file_text(State(s): State<AppState>, Query(q): Query<FileTextQuery>) -> Response {
420 match dto::pr_file_text(&s.deps.sections, &q.conn, &ItemRef::maybe(q.repo, q.id), &q.path, q.sha.as_deref()).await {
421 Some(text) => ([(header::CONTENT_TYPE, "text/plain; charset=utf-8")], text).into_response(),
422 None => (StatusCode::NOT_FOUND, "file text not available").into_response(),
423 }
424}
425
426async fn pr_detail(State(s): State<AppState>, Query(q): Query<ItemQuery>) -> Response {
427 let (conn, item) = q.item();
428 match dto::pr_detail(&s.deps.sections, &conn, &item).await {
429 Some(detail) => Json(detail).into_response(),
430 None => (StatusCode::NOT_FOUND, "pull request not found").into_response(),
431 }
432}
433
434#[derive(Deserialize)]
437struct DecorationQuery {
438 conn: String,
439 id: String,
440 #[serde(default)]
441 repo: Option<String>,
442 #[serde(default)]
443 updated_at: Option<String>,
444}
445
446async fn pr_decoration(State(s): State<AppState>, Query(q): Query<DecorationQuery>) -> Response {
447 let item = ItemRef::maybe(q.repo, q.id);
448 let key = DecorationCache::key(&q.conn, &item, q.updated_at.as_deref());
449 if let Some(hit) = s.decorations.get(&key) {
450 return Json(hit).into_response();
451 }
452 match dto::pr_decoration(&s.deps.sections, &q.conn, &item).await {
453 Some(decoration) => {
454 s.decorations.put(key, decoration.clone());
455 Json(decoration).into_response()
456 }
457 None => (StatusCode::NOT_FOUND, "pull request not found").into_response(),
458 }
459}
460
461async fn pr_vote(State(s): State<AppState>, Json(req): Json<actions::PrVoteReq>) -> Response {
462 action_response("dashboard.pr_vote", actions::pr_vote(&s.deps.sections, req).await)
463}
464async fn pr_merge(State(s): State<AppState>, Json(req): Json<actions::PrMergeReq>) -> Response {
465 action_response("dashboard.pr_merge", actions::pr_merge(&s.deps.sections, req).await)
466}
467async fn pr_revert(State(s): State<AppState>, Json(req): Json<actions::PrRevertReq>) -> Response {
468 action_response("dashboard.pr_revert", actions::pr_revert(&s.deps.sections, req).await)
469}
470async fn pr_comment(State(s): State<AppState>, Json(req): Json<actions::PrCommentReq>) -> Response {
471 action_response("dashboard.pr_comment", actions::pr_comment(&s.deps.sections, req).await)
472}
473async fn pr_reply(State(s): State<AppState>, Json(req): Json<actions::PrReplyReq>) -> Response {
474 action_response("dashboard.pr_reply", actions::pr_reply(&s.deps.sections, req).await)
475}
476async fn pr_review(State(s): State<AppState>, Json(req): Json<actions::PrReviewReq>) -> Response {
477 action_response("dashboard.pr_review", actions::pr_review(&s.deps.sections, req).await)
478}
479async fn pr_resolve_thread(State(s): State<AppState>, Json(req): Json<actions::PrResolveThreadReq>) -> Response {
480 action_response("dashboard.pr_resolve_thread", actions::pr_resolve_thread(&s.deps.sections, req).await)
481}
482async fn pr_draft(State(s): State<AppState>, Json(req): Json<actions::PrDraftReq>) -> Response {
483 action_response("dashboard.pr_draft", actions::pr_set_draft(&s.deps.sections, req).await)
484}
485async fn pr_closed(State(s): State<AppState>, Json(req): Json<actions::PrClosedReq>) -> Response {
486 action_response("dashboard.pr_closed", actions::pr_set_closed(&s.deps.sections, req).await)
487}
488async fn pr_reviewers(State(s): State<AppState>, Query(q): Query<ItemQuery>) -> Response {
489 let (conn, item) = q.item();
490 match actions::pr_reviewers(&s.deps.sections, &conn, &item).await {
491 Some(users) => Json(users).into_response(),
492 None => (StatusCode::NOT_FOUND, "pull request connection not found").into_response(),
493 }
494}
495async fn pr_request_reviewer(State(s): State<AppState>, Json(req): Json<actions::PrRequestReviewerReq>) -> Response {
496 action_response("dashboard.pr_request_reviewer", actions::pr_request_reviewer(&s.deps.sections, req).await)
497}
498
499async fn wi_detail(State(s): State<AppState>, Query(q): Query<ItemQuery>) -> Response {
500 let (conn, item) = q.item();
501 match dto::wi_detail(&s.deps.sections, &conn, &item).await {
502 Some(detail) => Json(detail).into_response(),
503 None => (StatusCode::NOT_FOUND, "work item not found").into_response(),
504 }
505}
506async fn wi_states(State(s): State<AppState>, Query(q): Query<ItemQuery>) -> Response {
507 let (conn, item) = q.item();
508 match actions::wi_states(&s.deps.sections, &conn, &item).await {
509 Some(states) => Json(states).into_response(),
510 None => (StatusCode::NOT_FOUND, "work item connection not found").into_response(),
511 }
512}
513async fn wi_state(State(s): State<AppState>, Json(req): Json<actions::WiStateReq>) -> Response {
514 action_response("dashboard.wi_state", actions::wi_set_state(&s.deps.sections, req).await)
515}
516async fn wi_comment(State(s): State<AppState>, Json(req): Json<actions::WiCommentReq>) -> Response {
517 action_response("dashboard.wi_comment", actions::wi_comment(&s.deps.sections, req).await)
518}
519async fn wi_assignees(State(s): State<AppState>, Query(q): Query<ItemQuery>) -> Response {
520 let (conn, item) = q.item();
521 match actions::wi_assignees(&s.deps.sections, &conn, &item).await {
522 Some(users) => Json(users).into_response(),
523 None => (StatusCode::NOT_FOUND, "work item connection not found").into_response(),
524 }
525}
526async fn wi_assignee(State(s): State<AppState>, Json(req): Json<actions::WiAssigneeReq>) -> Response {
527 action_response("dashboard.wi_assignee", actions::wi_set_assignee(&s.deps.sections, req).await)
528}
529async fn wi_update(State(s): State<AppState>, Json(req): Json<actions::WiUpdateReq>) -> Response {
530 action_response("dashboard.wi_update", actions::wi_update(&s.deps.sections, req).await)
531}
532
533async fn pipeline_detail(State(s): State<AppState>, Query(q): Query<RunQuery>) -> Response {
534 match dto::pipeline_detail(&s.deps.sections, &q.conn, &ItemRef::maybe(q.repo, q.run_id)).await {
535 Some(detail) => Json(detail).into_response(),
536 None => (StatusCode::NOT_FOUND, "pipeline run not found").into_response(),
537 }
538}
539async fn pipeline_logs(State(s): State<AppState>, Query(q): Query<PipelineLogsQuery>) -> Response {
540 match dto::pipeline_logs(&s.deps.sections, &q.conn, &ItemRef::maybe(q.repo, q.run_id), q.job.as_deref()).await {
541 Some(text) => ([(header::CONTENT_TYPE, "text/plain; charset=utf-8")], text).into_response(),
542 None => (StatusCode::NOT_FOUND, "logs not available").into_response(),
543 }
544}
545
546async fn pipeline_annotations(State(s): State<AppState>, Query(q): Query<RunQuery>) -> Response {
547 match dto::pipeline_annotations(&s.deps.sections, &q.conn, &ItemRef::maybe(q.repo, q.run_id)).await {
548 Some(annotations) => Json(annotations).into_response(),
549 None => (StatusCode::NOT_FOUND, "annotations not available").into_response(),
550 }
551}
552async fn pipeline_artifacts(State(s): State<AppState>, Query(q): Query<RunQuery>) -> Response {
553 match dto::pipeline_artifacts(&s.deps.sections, &q.conn, &ItemRef::maybe(q.repo, q.run_id)).await {
554 Some(artifacts) => Json(artifacts).into_response(),
555 None => (StatusCode::NOT_FOUND, "artifacts not available").into_response(),
556 }
557}
558
559async fn pipeline_approval(State(s): State<AppState>, Json(req): Json<actions::PipelineApprovalReq>) -> Response {
560 action_response("dashboard.pipeline_approval", actions::pipeline_approval(&s.deps.sections, req).await)
561}
562async fn pipeline_trigger(State(s): State<AppState>, Json(req): Json<actions::PipelineTriggerReq>) -> Response {
563 action_response("dashboard.pipeline_trigger", actions::pipeline_trigger(&s.deps.sections, req).await)
564}
565async fn pipeline_cancel(State(s): State<AppState>, Json(req): Json<actions::PipelineCancelReq>) -> Response {
566 action_response("dashboard.pipeline_cancel", actions::pipeline_cancel(&s.deps.sections, req).await)
567}
568async fn pipeline_rerun(State(s): State<AppState>, Json(req): Json<actions::PipelineRerunReq>) -> Response {
569 let result = actions::pipeline_rerun(&s.deps.sections, req).await;
570 action_response_with("dashboard.pipeline_rerun", result.map(|new_run_id| serde_json::json!({ "ok": true, "new_run_id": new_run_id })))
571}
572
573async fn notification_read(State(s): State<AppState>, Json(req): Json<actions::NotifReadReq>) -> Response {
574 action_response("dashboard.notification_read", actions::notif_read(&s.deps.sections, req).await)
575}
576
577#[derive(Deserialize)]
580struct IdReq {
581 id: String,
582}
583
584async fn providers() -> Json<Vec<connections::ProviderInfo>> {
585 Json(connections::providers())
586}
587async fn list_connections(State(s): State<AppState>) -> Json<Vec<connections::ConnectionRow>> {
588 Json(connections::list(&s.deps.config, s.deps.secrets.as_ref()))
589}
590async fn save_connection(State(s): State<AppState>, Json(req): Json<connections::SaveConnectionReq>) -> Response {
591 match connections::save(&s.deps.config, &s.deps.sections, req).await {
592 Ok(id) => Json(serde_json::json!({ "ok": true, "id": id })).into_response(),
593 Err(msg) => (StatusCode::BAD_GATEWAY, msg).into_response(),
594 }
595}
596async fn delete_connection(State(s): State<AppState>, Json(req): Json<IdReq>) -> Response {
597 match connections::remove(&s.deps.config, &req.id).await {
598 Ok(()) => Json(serde_json::json!({ "ok": true })).into_response(),
599 Err(msg) => (StatusCode::BAD_GATEWAY, msg).into_response(),
600 }
601}
602async fn test_connection(State(s): State<AppState>, Json(req): Json<IdReq>) -> Response {
603 match connections::test(&s.deps.health, &req.id).await {
604 Some(healthy) => Json(serde_json::json!({ "healthy": healthy })).into_response(),
605 None => (StatusCode::NOT_FOUND, "connection not found").into_response(),
606 }
607}
608
609async fn connection_repositories(State(s): State<AppState>, Query(q): Query<IdQuery>) -> Response {
613 match s.deps.sections.discover_repositories(&q.id).await {
614 Ok(page) => Json(page).into_response(),
615 Err(e) => (StatusCode::BAD_GATEWAY, e.to_string()).into_response(),
616 }
617}
618
619#[derive(Deserialize)]
620struct IdQuery {
621 id: String,
622}
623
624#[derive(Deserialize)]
625struct ScopeReq {
626 id: String,
627 scope: Vec<String>,
630}
631
632async fn set_connection_scope(State(s): State<AppState>, Json(req): Json<ScopeReq>) -> Response {
633 match s.deps.config.set_repo_scope(&req.id, Some(req.scope)).await {
634 Ok(()) => Json(serde_json::json!({ "ok": true })).into_response(),
635 Err(e) => (StatusCode::BAD_GATEWAY, e.to_string()).into_response(),
636 }
637}
638
639#[derive(serde::Serialize)]
643struct PipelineDefinitionsResp {
644 definitions: Vec<forgetop_core::domain::PipelineDefinition>,
645 all: bool,
646 selected: Vec<String>,
647}
648
649async fn pipeline_definitions(State(s): State<AppState>, Query(q): Query<IdQuery>) -> Response {
650 let source = match s.deps.sections.pipeline_source_for(&q.id).await {
651 Ok(Some(source)) => source,
652 Ok(None) => return (StatusCode::NOT_FOUND, "that connection doesn't support pipelines").into_response(),
653 Err(e) => return (StatusCode::BAD_GATEWAY, e.to_string()).into_response(),
654 };
655 let definitions = match source.discover().await {
656 Ok(defs) => defs,
657 Err(e) => return (StatusCode::BAD_GATEWAY, e.to_string()).into_response(),
658 };
659 let cfg = s.deps.config.snapshot();
660 let sub = cfg.pipelines.as_ref().and_then(|p| p.subscriptions.iter().find(|s| s.connection_id == q.id));
661 Json(PipelineDefinitionsResp {
662 definitions,
663 all: sub.is_some_and(|s| s.auto_discover_all),
664 selected: sub.map(|s| s.definition_ids.clone()).unwrap_or_default(),
665 })
666 .into_response()
667}
668
669#[derive(Deserialize)]
670struct PipelineSelectionReq {
671 id: String,
672 #[serde(default)]
674 all: bool,
675 #[serde(default)]
677 ids: Vec<String>,
678}
679
680async fn set_pipeline_selection(State(s): State<AppState>, Json(req): Json<PipelineSelectionReq>) -> Response {
681 let saved = if req.all {
682 s.deps.config.set_pipeline_auto_discover(&req.id, true).await
683 } else {
684 s.deps.config.set_pipeline_definitions(&req.id, req.ids).await
685 };
686 match saved {
687 Ok(()) => Json(serde_json::json!({ "ok": true })).into_response(),
688 Err(e) => (StatusCode::BAD_GATEWAY, e.to_string()).into_response(),
689 }
690}
691
692#[cfg(test)]
693mod tests {
694 use super::*;
699 use forgetop_core::config::{ConfigStore, ForgetopConfig, InMemoryConfigStore};
700 use forgetop_core::domain::ProviderType;
701 use forgetop_core::provider::{Connection, ProviderRegistry};
702 use forgetop_core::secret::InMemorySecretStore;
703 use forgetop_core::service::ConnectionResolver;
704 use forgetop_providers::demo::demo_factories;
705
706 async fn demo_deps() -> Deps {
708 deps_with(Arc::new(CacheStore::disabled())).await
709 }
710
711 async fn deps_with(cache: Arc<CacheStore>) -> Deps {
712 let registry = Arc::new(ProviderRegistry::new(demo_factories()));
713 let store: Arc<dyn ConfigStore> = Arc::new(InMemoryConfigStore::new(ForgetopConfig::default()));
714 let secrets: Arc<dyn SecretStore> = Arc::new(InMemorySecretStore::default());
715 let config = Arc::new(ConfigService::new(store, secrets.clone(), registry.clone()));
716 config.load().await.unwrap();
717 let conn = Connection {
718 id: "github".into(),
719 provider_type: ProviderType::GitHub,
720 display_name: "github".into(),
721 base_url: None,
722 organization: None,
723 project: None,
724 repository: None,
725 username: None,
726 credential_ref: None,
727 repo_scope: None,
728 };
729 config.add_or_update_connection(conn, None).await.unwrap();
730 config.bind_pull_requests("github").await.unwrap();
731 config.bind_work_items("github").await.unwrap();
732 config.set_pipeline_auto_discover("github", true).await.unwrap();
733 let resolver = Arc::new(ConnectionResolver::new(config.clone(), registry, secrets.clone()));
734 let sections = Arc::new(SectionService::new(config.clone(), resolver.clone()));
735 let health = Arc::new(ConnectionHealthService::new(config.clone(), resolver));
736 Deps { sections, health, config, secrets, cache }
737 }
738
739 struct Api {
740 base: String,
741 token: String,
742 client: reqwest::Client,
743 }
744
745 impl Api {
746 async fn start() -> Api {
747 let server = spawn(demo_deps().await, 0).await.expect("server binds a free port");
748 Api { base: format!("http://127.0.0.1:{}", server.port), token: server.token, client: reqwest::Client::new() }
749 }
750
751 async fn start_with(deps: Deps) -> Api {
752 let server = spawn(deps, 0).await.expect("server binds a free port");
753 Api { base: format!("http://127.0.0.1:{}", server.port), token: server.token, client: reqwest::Client::new() }
754 }
755
756 async fn get_raw(&self, path: &str) -> reqwest::Response {
757 self.client.get(format!("{}{path}", self.base)).header("x-forgetop-token", &self.token).send().await.expect("request")
758 }
759 async fn get(&self, path: &str) -> serde_json::Value {
760 let r = self.client.get(format!("{}{path}", self.base)).header("x-forgetop-token", &self.token).send().await.unwrap();
761 assert_eq!(r.status(), 200, "GET {path}");
762 r.json().await.unwrap()
763 }
764 async fn post(&self, path: &str, body: serde_json::Value) -> u16 {
765 let r = self.client.post(format!("{}{path}", self.base)).header("x-forgetop-token", &self.token).json(&body).send().await.unwrap();
766 r.status().as_u16()
767 }
768 async fn open_prs(&self) -> Vec<(String, String)> {
770 let rows = self.get("/api/pull-requests").await;
771 rows.as_array()
772 .unwrap()
773 .iter()
774 .map(|r| (r["pull_request"]["id"].as_str().unwrap().to_string(), r["pull_request"]["status"].as_str().unwrap().to_string()))
775 .collect()
776 }
777 async fn detail(&self, id: &str) -> serde_json::Value {
778 self.get(&format!("/api/pr/detail?conn=github&id={id}")).await
779 }
780 }
781
782 static DEMO_PRS: tokio::sync::Mutex<()> = tokio::sync::Mutex::const_new(());
787
788 async fn open_pr(api: &Api, nth: usize) -> String {
789 let open: Vec<_> = api.open_prs().await.into_iter().filter(|(_, s)| s == "Open").collect();
790 open.get(nth).unwrap_or_else(|| panic!("demo has at least {} open PRs", nth + 1)).0.clone()
791 }
792
793 #[tokio::test]
794 async fn pr_detail_advertises_the_demo_writes() {
795 let _one_at_a_time = DEMO_PRS.lock().await;
796 let api = Api::start().await;
797 let id = open_pr(&api, 0).await;
798 let writes = &api.detail(&id).await["writes"];
799 for k in ["resolve_threads", "draft", "close", "reopen", "request_reviewer"] {
800 assert_eq!(writes[k], true, "demo supports {k}: {writes}");
801 }
802 }
803
804 #[tokio::test]
805 async fn resolving_a_thread_flips_it_on_the_next_detail() {
806 let _one_at_a_time = DEMO_PRS.lock().await;
807 let api = Api::start().await;
808 let id = open_pr(&api, 1).await;
809 let thread = |d: &serde_json::Value, t: &str| d["threads"].as_array().unwrap().iter().find(|x| x["id"] == t).cloned().unwrap();
810 assert_eq!(thread(&api.detail(&id).await, "t1")["is_resolved"], false, "t1 starts open");
811
812 let body = |resolved: bool| serde_json::json!({ "conn": "github", "id": id, "thread_id": "t1", "resolved": resolved });
813 assert_eq!(api.post("/api/pr/resolve-thread", body(true)).await, 200);
814 assert_eq!(thread(&api.detail(&id).await, "t1")["is_resolved"], true, "resolve persists");
815 assert_eq!(api.post("/api/pr/resolve-thread", body(false)).await, 200);
816 assert_eq!(thread(&api.detail(&id).await, "t1")["is_resolved"], false, "reopen persists");
817 }
818
819 #[tokio::test]
820 async fn draft_and_close_change_the_pr_status() {
821 let _one_at_a_time = DEMO_PRS.lock().await;
822 let api = Api::start().await;
823 let id = open_pr(&api, 2).await;
824 let status = |d: serde_json::Value| d["pull_request"]["status"].as_str().unwrap().to_string();
825
826 assert_eq!(api.post("/api/pr/draft", serde_json::json!({ "conn": "github", "id": id, "draft": true })).await, 200);
827 assert_eq!(status(api.detail(&id).await), "Draft", "converted to a draft");
828 assert_eq!(api.post("/api/pr/draft", serde_json::json!({ "conn": "github", "id": id, "draft": false })).await, 200);
829 assert_eq!(status(api.detail(&id).await), "Open", "ready for review again");
830
831 assert_eq!(api.post("/api/pr/closed", serde_json::json!({ "conn": "github", "id": id, "closed": true })).await, 200);
832 assert_eq!(status(api.detail(&id).await), "Closed");
833 assert!(!api.open_prs().await.iter().any(|(p, _)| *p == id), "a closed PR leaves the open list");
834 assert_eq!(api.post("/api/pr/closed", serde_json::json!({ "conn": "github", "id": id, "closed": false })).await, 200);
835 assert_eq!(status(api.detail(&id).await), "Open", "reopened");
836 assert!(api.open_prs().await.iter().any(|(p, _)| *p == id), "and back on the open list");
837
838 assert_eq!(api.post("/api/pr/draft", serde_json::json!({ "conn": "nope", "id": id, "draft": true })).await, 404);
840 }
841
842 #[tokio::test]
843 async fn requesting_a_reviewer_adds_them_to_the_pr() {
844 let _one_at_a_time = DEMO_PRS.lock().await;
845 let api = Api::start().await;
846 let id = open_pr(&api, 3).await;
847 let users = api.get(&format!("/api/pr/reviewers?conn=github&id={id}")).await;
848 let users = users.as_array().expect("reviewers is a JSON array of users");
849 assert!(!users.is_empty(), "the demo has someone to ask");
850
851 let reviewer_ids = |d: &serde_json::Value| -> Vec<String> {
852 d["pull_request"]["reviewers"].as_array().unwrap().iter().map(|r| r["user"]["id"].as_str().unwrap().to_string()).collect()
853 };
854 let before = reviewer_ids(&api.detail(&id).await);
855 let pick = users.iter().map(|u| u["id"].as_str().unwrap().to_string()).find(|u| !before.contains(u)).expect("someone not yet reviewing");
856
857 assert_eq!(api.post("/api/pr/request-reviewer", serde_json::json!({ "conn": "github", "id": id, "user_id": pick })).await, 200);
858 let after = api.detail(&id).await;
859 let added = after["pull_request"]["reviewers"].as_array().unwrap().iter().find(|r| r["user"]["id"] == pick.as_str()).cloned();
860 let added = added.expect("the requested reviewer is on the PR");
861 assert_eq!(added["vote"], "NoVote", "requested, not yet voted");
862
863 let missing = api.client.get(format!("{}/api/pr/reviewers?conn=nope&id={id}", api.base)).header("x-forgetop-token", &api.token).send().await.unwrap();
864 assert_eq!(missing.status(), 404, "a bad connection is a 404");
865 }
866
867 fn scratch_cache() -> (Arc<CacheStore>, std::path::PathBuf) {
868 let path = std::env::temp_dir().join(format!("forgetop-api-cache-{}.json", uuid::Uuid::new_v4()));
869 (Arc::new(CacheStore::new(&path)), path)
870 }
871
872 #[tokio::test]
875 async fn lists_answer_from_the_shared_cache_then_refresh_behind_it() {
876 std::env::set_var("FORGETOP_CACHE_WAIT_MS", "0");
878 let (cache, path) = scratch_cache();
879 let api = Api::start_with(deps_with(cache.clone()).await).await;
880
881 let cold = api.get_raw("/api/work-items").await;
883 assert!(cold.headers().get(FETCHED_AT_HEADER).is_none(), "a live answer carries no cache date");
884 let live: Vec<serde_json::Value> = cold.json().await.unwrap();
885 assert!(!live.is_empty());
886 assert!(cache.get::<Vec<cached::TuiWiRow>>(cached::KEY_WORK_ITEMS).is_some(), "the live fetch wrote the TUI's key");
887
888 assert!(cache.rewrite::<Vec<cached::TuiWiRow>>(cached::KEY_WORK_ITEMS, |mut rows| {
890 rows[0].wi.title = "Left here by the terminal".into();
891 rows
892 }));
893 let warm = api.get_raw("/api/work-items").await;
894 let fetched_at = warm.headers().get(FETCHED_AT_HEADER).expect("a cached answer says when it was fetched").clone();
895 assert!(chrono::DateTime::parse_from_rfc3339(fetched_at.to_str().unwrap()).is_ok());
896 let rows: Vec<serde_json::Value> = warm.json().await.unwrap();
897 assert_eq!(rows[0]["work_item"]["title"], "Left here by the terminal");
898
899 let mut fresh = Vec::new();
901 for _ in 0..50 {
902 tokio::time::sleep(std::time::Duration::from_millis(50)).await;
903 fresh = api.get_raw("/api/work-items").await.json::<Vec<serde_json::Value>>().await.unwrap();
904 if fresh[0]["work_item"]["title"] != "Left here by the terminal" {
905 break;
906 }
907 }
908 assert_ne!(fresh[0]["work_item"]["title"], "Left here by the terminal", "the live fetch wrote back");
909 std::env::remove_var("FORGETOP_CACHE_WAIT_MS");
910 tokio::time::sleep(std::time::Duration::from_millis(1500)).await;
912 assert!(path.exists(), "the cache was flushed to {}", path.display());
913 let _ = std::fs::remove_file(path);
914 }
915
916 #[tokio::test]
918 async fn live_fetches_write_the_terminal_ui_keys() {
919 let (cache, path) = scratch_cache();
920 let api = Api::start_with(deps_with(cache.clone()).await).await;
921 let _ = api.get_raw("/api/pull-requests?view=all").await;
922 let _ = api.get_raw("/api/pull-requests?view=review_requested").await;
923 let _ = api.get_raw("/api/launchpad").await;
924 let _ = api.get_raw("/api/notifications").await;
925 let all = cache.get::<Vec<cached::TuiPrRow>>(&cached::prs_key(forgetop_core::provider::PullRequestFilter::All, false)).expect("All view");
926 assert!(!all.value.is_empty());
927 assert!(cache.get::<Vec<cached::TuiPrRow>>(&cached::prs_key(forgetop_core::provider::PullRequestFilter::ReviewRequested, false)).is_some());
928 assert!(cache.get::<Vec<cached::TuiPrRow>>(cached::KEY_LAUNCHPAD_MINE).is_some());
929 assert!(cache.get::<Vec<cached::TuiPrRow>>(cached::KEY_LAUNCHPAD_REVIEW).is_some());
930 assert!(cache.get::<Vec<cached::TuiWiRow>>(cached::KEY_WORK_ITEMS).is_some());
931 assert!(cache.get::<Vec<cached::TuiPipeRow>>(cached::KEY_PIPELINES).is_some());
932 assert!(cache.get::<Vec<dto::NotifRow>>(cached::KEY_INBOX).is_some());
933 let live: serde_json::Value = api.get_raw("/api/launchpad").await.json().await.unwrap();
935 let from_cache = cached::launchpad(&cache).expect("launchpad from cache");
936 assert_eq!(serde_json::to_value(&from_cache.value).unwrap(), live);
937 let _ = std::fs::remove_file(path);
938 }
939}