OXYGENHUB
◆ main oxygenhub / crates / hub / src / web / home.rs
22.9 KiB · Rust · last changed New repository page with board and starting files; assetlinks.json; hung tests stopped; changelog on the WASM tier (closes #360, closes #365, closes #370) 1 day ago source blame history raw
d23464c0 Andy McCall ↶ 1
//! The front page, explore, owner pages and small endpoints.
2
3
use super::{filters, Error, Page, Shell};
19bb31ff Andy McCall ↶ 4
use crate::auth::Viewer;
d23464c0 Andy McCall ↶ 5
use crate::{db, Shared};
6
use askama::Template;
1553bfc9 Andy McCall ↶ 7
use axum::extract::{Path, Query, State};
d23464c0 Andy McCall ↶ 8
use axum::http::header;
9
use axum::response::{IntoResponse, Response};
10
use hub_api::Visibility;
1553bfc9 Andy McCall ↶ 11
use serde::Deserialize;
d23464c0 Andy McCall ↶ 12
13
#[derive(Template)]
14
#[template(path = "home.html")]
15
pub struct HomePage {
16
    shell: Shell,
17
    description: String,
18
    repos: Vec<db::repos::RepoRow>,
19
    owner: Option<String>,
1553bfc9 Andy McCall ↶ 20
    /// Explore's controls: the filter text, the sort, the topic.
21
    q: String,
22
    sort: String,
23
    topic: String,
24
    stars: std::collections::HashMap<i64, i64>,
0a3b244b Andy McCall ↶ 25
    /// The hub's sky (docs/backgrounds.md §2, #165) on Explore and the
26
    /// signed-out home: the public repositories listed; empty elsewhere.
27
    backdrop: String,
1553bfc9 Andy McCall ↶ 28
}
29
30
impl HomePage {
31
    fn star_count(&self, id: &i64) -> i64 {
32
        self.stars.get(id).copied().unwrap_or(0)
33
    }
34
}
35
36
/// `/explore?q=&sort=activity|stars|name&topic=`.
37
#[derive(Deserialize, Default)]
38
pub struct ExploreQuery {
39
    #[serde(default)]
40
    q: String,
41
    #[serde(default)]
42
    sort: String,
43
    #[serde(default)]
44
    topic: String,
d23464c0 Andy McCall ↶ 45
}
46
25ab8c73 Andy McCall ↶ 47
/// The signed-in dashboard (hub spec §6): the review queue, the
48
/// viewer's own proposals and assigned issues, their repositories and
49
/// recent activity across everything they can see.
50
#[derive(Template)]
51
#[template(path = "dashboard.html")]
52
pub struct Dashboard {
53
    shell: Shell,
54
    mine: Vec<db::repos::RepoRow>,
55
    reviews: Vec<db::activity::ProposalLine>,
56
    authored: Vec<db::activity::ProposalLine>,
57
    assigned: Vec<db::activity::IssueLine>,
58
    feed: Vec<db::activity::Activity>,
17ca6cdd Andy McCall ↶ 59
    /// Your sky's data (docs/backgrounds.md §5), JSON safe inside a script.
60
    backdrop: String,
8a48dd83 Andy McCall ↶ 61
    /// What the cards and the feed listen on (docs/live.md L4): the
62
    /// viewer's topic and their repositories'.
63
    live: String,
25ab8c73 Andy McCall ↶ 64
}
65
66
/// How many activity lines the dashboard shows.
67
const FEED_LIMIT: i64 = 40;
df5c69cb Andy McCall ↶ 68
/// The most events Your sky reads, and how far back (docs/backgrounds.md §5).
4dfa4599 Andy McCall ↶ 69
pub(crate) const SKY_EVENTS: i64 = 1500;
0a3b244b Andy McCall ↶ 70
/// The most repositories the hub's sky draws, the most recently active.
71
const SKY_REPOS: usize = 40;
4dfa4599 Andy McCall ↶ 72
pub(crate) const SKY_DAYS: i64 = 30;
25ab8c73 Andy McCall ↶ 73
17ca6cdd Andy McCall ↶ 74
/// Your sky's data (docs/backgrounds.md §5): the viewer's repositories and
75
/// their events of the last 30 days, newest first, as
df5c69cb Andy McCall ↶ 76
/// `{now, repos: [slug], events: [[repo, kind, at_ms, n]]}` with kinds 0 a
77
/// push of `n` changes, 1 a proposal event, 2 an issue event, 3 a release,
78
/// 4 a Flow run. Only the database is read, never a repository's store;
79
/// `<` is escaped so the JSON is safe in a script.
da8f7826 Andy McCall ↶ 80
fn sky_json(mine: &[db::repos::RepoRow], events: &[db::activity::SkyEvent], now: i64, live: &str) -> String {
17ca6cdd Andy McCall ↶ 81
    let slugs: Vec<String> = mine.iter().map(|r| format!("{}/{}", r.owner, r.name)).collect();
82
    let evs: Vec<serde_json::Value> = events
83
        .iter()
84
        .filter_map(|e| {
df5c69cb Andy McCall ↶ 85
            let repo = mine.iter().position(|r| r.id == e.repo_id)?;
86
            Some(serde_json::json!([repo, e.kind, e.at_ms, e.n]))
17ca6cdd Andy McCall ↶ 87
        })
88
        .collect();
da8f7826 Andy McCall ↶ 89
    serde_json::json!({ "now": now, "repos": slugs, "events": evs, "live": live }).to_string().replace('<', "\\u003c")
17ca6cdd Andy McCall ↶ 90
}
91
ffb67a81 Andy McCall 92
/// One repository's sky (#196): the backdrop of its own pages, from the
93
/// database only, with no live polling. Empty when it cannot be read.
94
pub(crate) async fn repo_sky(app: &Shared, row: &db::repos::RepoRow) -> String {
95
    let now = db::now_ms();
96
    match db::activity::sky(&app.db, &[row.id], now - SKY_DAYS * 86_400_000, SKY_EVENTS).await {
97
        Ok(events) => sky_json(std::slice::from_ref(row), &events, now, ""),
98
        Err(_) => String::new(),
99
    }
100
}
101
da8f7826 Andy McCall ↶ 102
/// The repositories a sky draws: `mine`, the viewer's own (member) ones,
103
/// as the dashboard's; `hub`, the public ones the viewer may see, as
104
/// Explore's. Never a private repository in the hub's sky.
105
async fn sky_repos(app: &Shared, shell: &Shell, viewer: &Viewer, scene: &str) -> Result<Vec<db::repos::RepoRow>, Error> {
106
    let db_err = |e| Error::from_db(shell.clone(), e);
107
    let seen = visible(app, shell, viewer, db::repos::list(&app.db).await.map_err(db_err)?).await?;
108
    match (scene, viewer.account()) {
109
        ("mine", Some(account)) => {
110
            let member: Vec<i64> = db::accounts::visible_repo_ids(&app.db, account.id).await.map_err(db_err)?;
111
            Ok(seen.into_iter().filter(|r| member.contains(&r.id)).collect())
112
        }
113
        ("hub", _) => {
114
            let mut public: Vec<db::repos::RepoRow> = seen.into_iter().filter(|r| r.visibility == "public").collect();
115
            public.sort_by_key(|r| std::cmp::Reverse(r.updated_ms));
116
            public.truncate(SKY_REPOS);
117
            Ok(public)
118
        }
119
        _ => Ok(Vec::new()),
120
    }
121
}
122
123
#[derive(Deserialize)]
124
pub struct ArrivalsQuery {
125
    #[serde(default)]
126
    scene: String,
127
    #[serde(default)]
128
    since: i64,
129
}
130
131
/// `GET /sky/arrivals?scene=mine|hub&since=MS` (docs/backgrounds.md §4,
132
/// "Arrivals"): what happened in a sky's repositories since `since`, by
133
/// repository name, for the page to add without reloading. The same
134
/// repositories as the sky it feeds, never more.
135
pub async fn arrivals(State(app): State<Shared>, viewer: Viewer, Query(q): Query<ArrivalsQuery>) -> Result<Response, Error> {
136
    let shell = Shell::new(&app, "/sky/arrivals", &viewer);
137
    let repos = sky_repos(&app, &shell, &viewer, &q.scene).await?;
138
    let now = db::now_ms();
139
    // At most a day back: a page left open longer starts again.
140
    let since = q.since.clamp(now - 86_400_000, now);
141
    let ids: Vec<i64> = repos.iter().map(|r| r.id).collect();
142
    let events = if ids.is_empty() {
143
        Vec::new()
144
    } else {
145
        db::activity::sky(&app.db, &ids, since + 1, 200).await.map_err(|e| Error::from_db(shell.clone(), e))?
146
    };
147
    let evs: Vec<serde_json::Value> = events
148
        .iter()
149
        .filter_map(|e| {
150
            let r = repos.iter().find(|r| r.id == e.repo_id)?;
151
            Some(serde_json::json!([format!("{}/{}", r.owner, r.name), e.kind, e.at_ms, e.n]))
152
        })
153
        .collect();
154
    let body = serde_json::json!({ "now": now, "events": evs });
155
    Ok(([(axum::http::header::CACHE_CONTROL, "private, no-store")], axum::Json(body)).into_response())
156
}
157
25ab8c73 Andy McCall ↶ 158
/// `/`: the dashboard when signed in, every visible repository otherwise.
159
pub async fn index(State(app): State<Shared>, viewer: Viewer) -> Result<Response, Error> {
160
    let Some(account) = viewer.account().cloned() else {
1553bfc9 Andy McCall ↶ 161
        return Ok(explore(State(app), viewer, Query(ExploreQuery::default())).await?.into_response());
25ab8c73 Andy McCall ↶ 162
    };
19bb31ff Andy McCall ↶ 163
    let shell = Shell::new(&app, "/", &viewer);
25ab8c73 Andy McCall ↶ 164
    let db_err = |e| Error::from_db(shell.clone(), e);
165
    let all = db::repos::list(&app.db).await.map_err(db_err)?;
166
    let member: Vec<i64> = db::accounts::visible_repo_ids(&app.db, account.id).await.map_err(db_err)?;
167
    let seen = visible(&app, &shell, &viewer, all).await?;
168
    let seen_ids: Vec<i64> = seen.iter().map(|r| r.id).collect();
169
    let mut mine: Vec<db::repos::RepoRow> = seen.into_iter().filter(|r| member.contains(&r.id)).collect();
170
    mine.sort_by_key(|r| std::cmp::Reverse(r.updated_ms));
171
    let reviews = db::activity::awaiting_review(&app.db, account.id, &member).await.map_err(db_err)?;
172
    let authored = db::activity::authored(&app.db, account.id, &seen_ids).await.map_err(db_err)?;
173
    let assigned = db::activity::assigned(&app.db, account.id, &seen_ids).await.map_err(db_err)?;
174
    let feed = db::activity::feed(&app.db, &seen_ids, FEED_LIMIT).await.map_err(db_err)?;
17ca6cdd Andy McCall ↶ 175
    let mine_ids: Vec<i64> = mine.iter().map(|r| r.id).collect();
df5c69cb Andy McCall ↶ 176
    let now = db::now_ms();
177
    let sky = db::activity::sky(&app.db, &mine_ids, now - SKY_DAYS * 86_400_000, SKY_EVENTS).await.map_err(db_err)?;
da8f7826 Andy McCall ↶ 178
    let backdrop = sky_json(&mine, &sky, now, "mine");
8a48dd83 Andy McCall ↶ 179
    let live = std::iter::once(shell.live_user.clone())
180
        .chain(mine.iter().take(15).map(|r| crate::events::topic::repo(r.id)))
181
        .filter(|t| !t.is_empty())
182
        .collect::<Vec<_>>()
183
        .join(" ");
184
    Ok(Page(Dashboard { shell, mine, reviews, authored, assigned, feed, backdrop, live }).into_response())
d23464c0 Andy McCall ↶ 185
}
186
1553bfc9 Andy McCall ↶ 187
/// `/explore`: every repository the viewer may see, filtered by text and
188
/// topic, sorted by recent activity (the default), stars or name.
189
pub async fn explore(State(app): State<Shared>, viewer: Viewer, Query(q): Query<ExploreQuery>) -> Result<Page<HomePage>, Error> {
25ab8c73 Andy McCall ↶ 190
    let shell = Shell::new(&app, "/explore", &viewer);
1553bfc9 Andy McCall ↶ 191
    let db_err = |e| Error::from_db(shell.clone(), e);
192
    let mut repos = visible(&app, &shell, &viewer, db::repos::list(&app.db).await.map_err(db_err)?).await?;
193
    let stars = db::repos::star_counts(&app.db).await.map_err(db_err)?;
194
    let needle = q.q.trim().to_lowercase();
195
    if !needle.is_empty() {
196
        repos.retain(|r| {
197
            r.slug().to_lowercase().contains(&needle)
198
                || r.description.to_lowercase().contains(&needle)
199
                || r.topic_list().iter().any(|t| t.contains(&needle))
200
        });
201
    }
202
    let topic = q.topic.trim().to_lowercase();
203
    if !topic.is_empty() {
204
        repos.retain(|r| r.topic_list().contains(&topic.as_str()));
205
    }
206
    let sort = match q.sort.as_str() {
207
        "stars" | "name" => q.sort.clone(),
208
        _ => "activity".to_string(),
209
    };
210
    match sort.as_str() {
211
        "stars" => repos.sort_by_key(|r| (std::cmp::Reverse(stars.get(&r.id).copied().unwrap_or(0)), std::cmp::Reverse(r.updated_ms))),
212
        "name" => repos.sort_by_key(|r| (r.name.to_lowercase(), r.owner.to_lowercase())),
213
        _ => repos.sort_by_key(|r| std::cmp::Reverse(r.updated_ms)),
214
    }
0a3b244b Andy McCall ↶ 215
    // The hub's sky: the public repositories listed (a filter narrows it),
216
    // the most recently active first; never a private one, whoever looks.
217
    let public: Vec<db::repos::RepoRow> = repos.iter().filter(|r| r.visibility == "public").take(SKY_REPOS).cloned().collect();
218
    let ids: Vec<i64> = public.iter().map(|r| r.id).collect();
219
    let now = db::now_ms();
220
    let sky = db::activity::sky(&app.db, &ids, now - SKY_DAYS * 86_400_000, SKY_EVENTS).await.map_err(db_err)?;
da8f7826 Andy McCall ↶ 221
    let backdrop = sky_json(&public, &sky, now, "hub");
0a3b244b Andy McCall ↶ 222
    Ok(Page(HomePage { description: app.config.site.description.clone(), shell, repos, owner: None, q: q.q, sort, topic, stars, backdrop }))
d23464c0 Andy McCall ↶ 223
}
224
10174045 Andy McCall ↶ 225
/// A person's page (hub spec §6): avatar, names, bio, linked signing
226
/// keys, organisations, repositories and what they did lately.
227
#[derive(Template)]
228
#[template(path = "profile.html")]
229
pub struct ProfilePage {
230
    shell: Shell,
231
    account: db::accounts::Account,
232
    keys: Vec<db::accounts::LinkedIdentity>,
233
    orgs: Vec<(db::accounts::Organisation, String)>,
234
    repos: Vec<db::repos::RepoRow>,
235
    feed: Vec<db::activity::Activity>,
236
    is_me: bool,
2a0c09c0 Andy McCall ↶ 237
    /// The year's pulse as JSON for the page's script (#217); `<` escaped.
238
    pulse: String,
239
    /// Changes pushed in the last year, shown beside the pulse.
240
    pulse_total: i64,
10174045 Andy McCall ↶ 241
}
242
243
impl ProfilePage {
244
    /// The website as a link only when it is http(s).
245
    fn website_href(&self) -> Option<&str> {
246
        let w = self.account.website.trim();
247
        (w.starts_with("https://") || w.starts_with("http://")).then_some(w)
248
    }
249
}
250
251
/// An organisation's page: description, members with their roles, teams,
252
/// repositories and recent activity in them.
253
#[derive(Template)]
254
#[template(path = "org.html")]
255
pub struct OrgPage {
256
    shell: Shell,
257
    org: db::accounts::Organisation,
258
    members: Vec<(db::accounts::Account, String)>,
259
    teams: Vec<(db::accounts::Team, usize)>,
260
    repos: Vec<db::repos::RepoRow>,
261
    feed: Vec<db::activity::Activity>,
262
    can_admin: bool,
263
}
264
2a0c09c0 Andy McCall ↶ 265
const DAY_MS: i64 = 86_400_000;
266
267
/// The profile's pulse (#217): changes this account pushed each day of the
268
/// last year, in repositories the viewer may see, with the share pushed
269
/// through agent tokens, per repository, and its releases to label peaks.
270
/// `{"start": MS, "repos": [NAME], "days": [[TOTAL, VIA, [[REPO, N]..]]..],
c0095389 Andy McCall ↶ 271
/// "peaks": [[DAY, LABEL]..], "months": M}`: the last 3, 6, 9 or 12
272
/// months, the shortest that holds their first push of the year, ending
273
/// today (UTC).
2a0c09c0 Andy McCall ↶ 274
async fn pulse_json(app: &Shared, account: &db::accounts::Account, seen: &[db::repos::RepoRow]) -> sqlx::Result<(String, i64)> {
275
    let today = db::now_ms() / DAY_MS;
c0095389 Andy McCall ↶ 276
    let ids: Vec<i64> = seen.iter().map(|r| r.id).collect();
277
    let rows = db::activity::pulse(&app.db, account.id, &ids, (today - 364) * DAY_MS).await?;
278
    // Snap to 3, 6, 9 or 12 months: no point drawing a year for a month's work.
279
    let used = rows.first().map(|r| today - r.1 / DAY_MS + 1).unwrap_or(0);
280
    let (months, span) = [(3, 91), (6, 182), (9, 273), (12, 365)].into_iter().find(|(_, d)| used <= *d).unwrap_or((12, 365));
a2fbad48 Andy McCall ↶ 281
    let first = today - span + 1;
282
    let (pulse, total) = pulse_of(&rows, seen, first, span as usize);
2a0c09c0 Andy McCall ↶ 283
    let mut value = pulse;
284
    let mut peaks = Vec::new();
285
    for (repo_id, tag, at) in db::activity::releases_by(&app.db, account.id, &ids, first * DAY_MS).await? {
286
        let name = seen.iter().find(|r| r.id == repo_id).map(|r| r.name.as_str()).unwrap_or("");
287
        peaks.push(serde_json::json!([at / DAY_MS - first, format!("{name} {tag}")]));
288
    }
289
    value["peaks"] = serde_json::Value::Array(peaks);
c0095389 Andy McCall ↶ 290
    value["months"] = months.into();
2a0c09c0 Andy McCall ↶ 291
    Ok((value.to_string().replace('<', "\\u003c"), total))
292
}
293
294
/// The days of a pulse from push rows `(repo_id, at_ms, changes, via)`:
295
/// repositories ordered by how much went to them, most first.
a2fbad48 Andy McCall ↶ 296
fn pulse_of(rows: &[(i64, i64, i64, String)], seen: &[db::repos::RepoRow], first: i64, span: usize) -> (serde_json::Value, i64) {
2a0c09c0 Andy McCall ↶ 297
    let mut per_repo: std::collections::BTreeMap<i64, i64> = std::collections::BTreeMap::new();
298
    for (repo, _, n, _) in rows {
299
        *per_repo.entry(*repo).or_default() += n;
300
    }
301
    let mut order: Vec<(i64, i64)> = per_repo.into_iter().collect();
302
    order.sort_by(|a, b| b.1.cmp(&a.1).then(a.0.cmp(&b.0)));
303
    let names: Vec<String> = order
304
        .iter()
305
        .map(|(id, _)| seen.iter().find(|r| r.id == *id).map(|r| format!("{}/{}", r.owner, r.name)).unwrap_or_default())
306
        .collect();
307
    let slot = |id: i64| order.iter().position(|(r, _)| *r == id).unwrap_or(0);
a2fbad48 Andy McCall ↶ 308
    let mut days: Vec<(i64, i64, std::collections::BTreeMap<usize, i64>)> = vec![(0, 0, Default::default()); span];
2a0c09c0 Andy McCall ↶ 309
    let mut total = 0;
310
    for (repo, at, n, via) in rows {
311
        let d = at / DAY_MS - first;
a2fbad48 Andy McCall ↶ 312
        if d < 0 || d as usize >= span {
2a0c09c0 Andy McCall ↶ 313
            continue;
314
        }
315
        let day = &mut days[d as usize];
316
        day.0 += n;
317
        if !via.is_empty() {
318
            day.1 += n;
319
        }
320
        *day.2.entry(slot(*repo)).or_default() += n;
321
        total += n;
322
    }
323
    let days: Vec<serde_json::Value> = days
324
        .into_iter()
325
        .map(|(t, v, by)| serde_json::json!([t, v, by.into_iter().map(|(r, n)| serde_json::json!([r, n])).collect::<Vec<_>>()]))
326
        .collect();
327
    (serde_json::json!({ "start": first * DAY_MS, "repos": names, "days": days }), total)
328
}
329
10174045 Andy McCall ↶ 330
/// How many activity lines an owner page shows.
331
const OWNER_FEED: i64 = 20;
332
333
/// `/{owner}`: a person's profile, an organisation's page, or (for an
334
/// owner that is neither, such as repositories an administrator created
335
/// for a name nobody holds) the list of its repositories.
336
pub async fn owner(State(app): State<Shared>, viewer: Viewer, Path(owner): Path<String>) -> Result<Response, Error> {
19bb31ff Andy McCall ↶ 337
    let shell = Shell::new(&app, &format!("/{owner}"), &viewer);
d23464c0 Andy McCall ↶ 338
    if !crate::repos::names::valid_owner(&owner) {
339
        return Err(Error::not_found(shell));
340
    }
10174045 Andy McCall ↶ 341
    let db_err = |e| Error::from_db(shell.clone(), e);
342
    let mut repos = visible(&app, &shell, &viewer, db::repos::list_by_owner(&app.db, &owner).await.map_err(db_err)?).await?;
343
    repos.sort_by_key(|r| std::cmp::Reverse(r.updated_ms));
344
    if let Some(account) = db::accounts::account_by_name(&app.db, &owner).await.map_err(db_err)? {
345
        // What they did anywhere the viewer can see, not only in their own repositories.
346
        let all = visible(&app, &shell, &viewer, db::repos::list(&app.db).await.map_err(db_err)?).await?;
347
        let ids: Vec<i64> = all.iter().map(|r| r.id).collect();
348
        let feed = db::activity::feed_by(&app.db, &ids, Some(&account.username), OWNER_FEED).await.map_err(db_err)?;
349
        let keys = db::accounts::identities_of(&app.db, account.id).await.map_err(db_err)?;
350
        let orgs = db::accounts::orgs_of(&app.db, account.id).await.map_err(db_err)?;
351
        let is_me = viewer.account().is_some_and(|a| a.id == account.id);
2a0c09c0 Andy McCall ↶ 352
        let (pulse, pulse_total) = pulse_json(&app, &account, &all).await.map_err(db_err)?;
353
        return Ok(Page(ProfilePage { shell, account, keys, orgs, repos, feed, is_me, pulse, pulse_total }).into_response());
10174045 Andy McCall ↶ 354
    }
355
    if let Some(org) = db::accounts::org_by_name(&app.db, &owner).await.map_err(db_err)? {
356
        let members = db::accounts::org_members(&app.db, org.id).await.map_err(db_err)?;
357
        let mut teams = Vec::new();
358
        for t in db::accounts::teams(&app.db, org.id).await.map_err(db_err)? {
359
            let n = db::accounts::team_members(&app.db, t.id).await.map_err(db_err)?.len();
360
            teams.push((t, n));
361
        }
362
        let ids: Vec<i64> = repos.iter().map(|r| r.id).collect();
363
        let feed = db::activity::feed(&app.db, &ids, OWNER_FEED).await.map_err(db_err)?;
364
        let can_admin =
365
            viewer.is_admin() || viewer.account().is_some_and(|a| members.iter().any(|(m, role)| m.id == a.id && role == "owner"));
366
        return Ok(Page(OrgPage { shell, org, members, teams, repos, feed, can_admin }).into_response());
367
    }
368
    if repos.is_empty() {
d23464c0 Andy McCall ↶ 369
        return Err(Error::not_found(shell));
370
    }
1553bfc9 Andy McCall ↶ 371
    let stars = db::repos::star_counts(&app.db).await.unwrap_or_default();
372
    Ok(Page(HomePage {
373
        description: String::new(),
374
        shell,
375
        repos,
376
        owner: Some(owner),
377
        q: String::new(),
378
        sort: "activity".into(),
379
        topic: String::new(),
380
        stars,
0a3b244b Andy McCall ↶ 381
        backdrop: String::new(),
1553bfc9 Andy McCall ↶ 382
    })
383
    .into_response())
d23464c0 Andy McCall ↶ 384
}
385
19bb31ff Andy McCall ↶ 386
/// The repositories among `rows` the viewer may see: public ones, internal
387
/// ones when signed in, and those the viewer owns or collaborates on.
07b1a5bb Andy McCall ↶ 388
pub(crate) async fn visible(
389
    app: &Shared,
390
    shell: &Shell,
391
    viewer: &Viewer,
392
    rows: Vec<db::repos::RepoRow>,
393
) -> Result<Vec<db::repos::RepoRow>, Error> {
19bb31ff Andy McCall ↶ 394
    let mine: Vec<i64> = match viewer.account() {
395
        Some(a) if a.is_admin => rows.iter().map(|r| r.id).collect(),
396
        Some(a) => db::accounts::visible_repo_ids(&app.db, a.id).await.map_err(|e| Error::from_db(shell.clone(), e))?,
397
        None => vec![],
398
    };
399
    let signed_in = viewer.signed_in();
400
    Ok(rows
401
        .into_iter()
402
        .filter(|r| match r.visibility() {
403
            Visibility::Public => true,
404
            Visibility::Internal => signed_in,
405
            Visibility::Private => mine.contains(&r.id),
406
        })
407
        .collect())
408
}
409
d23464c0 Andy McCall ↶ 410
pub async fn health(State(app): State<Shared>) -> Response {
b2107275 Andy McCall ↶ 411
    let (states, weight, summaries) = app.repos.cache().stats();
ed3a36b6 Andy McCall ↶ 412
    let strata = oxy_strata::stats();
d23464c0 Andy McCall ↶ 413
    let body = serde_json::json!({
414
        "ok": true,
415
        "version": env!("CARGO_PKG_VERSION"),
e9bfea8e Andy McCall ↶ 416
        "build": env!("OXY_BUILD_ID"),
d23464c0 Andy McCall ↶ 417
        "uptime_s": app.started.elapsed().as_secs(),
e57765de Andy McCall ↶ 418
        // What this process does, and the singleton tasks it leads (#272).
419
        "roles": app.roles.names(),
420
        "leading": app.leader.leading(),
b2107275 Andy McCall ↶ 421
        // What the state cache holds, beside the process's size (#117).
422
        "state_cache": {
423
            "states": states,
424
            "estimated_mb": weight >> 20,
425
            "budget_mb": crate::repos::cache::budget() >> 20,
426
            "summaries": summaries,
427
        },
ed3a36b6 Andy McCall ↶ 428
        // Repositories kept in buckets (#234): clients opened, requests
a268d4df Andy McCall ↶ 429
        // made (in all and by kind) and the time spent in them since the
430
        // hub started.
ed3a36b6 Andy McCall ↶ 431
        "cloud_stores": {
432
            "opened": strata.opens,
433
            "requests": strata.calls,
434
            "request_ms": strata.millis,
a268d4df Andy McCall ↶ 435
            "by_kind": strata
436
                .ops()
437
                .map(|(k, n)| (k.to_string(), n.into()))
438
                .collect::<serde_json::Map<_, _>>(),
ed3a36b6 Andy McCall ↶ 439
        },
d23464c0 Andy McCall ↶ 440
    });
441
    axum::Json(body).into_response()
442
}
443
444
/// The hub delegate identity object (hub spec §15.5), as `oxy identity
445
/// export` writes one, so policy holders can admit it.
446
pub async fn hub_key(State(app): State<Shared>) -> Response {
447
    (
448
        [(header::CONTENT_TYPE, "application/oxy-identity"), (header::CONTENT_DISPOSITION, "attachment; filename=\"hub.identity\"")],
449
        app.hub_key.bytes.clone(),
450
    )
451
        .into_response()
452
}
8f3d2ccf Andy McCall ↶ 453
40a43921 Andy McCall ↶ 454
/// `/.well-known/assetlinks.json` (#370): the Android apps whose App Links
455
/// this hub vouches for, so its links open them rather than the browser.
456
pub async fn assetlinks(State(app): State<Shared>) -> Response {
457
    let apps: Vec<serde_json::Value> = app
458
        .config
459
        .push
460
        .android_apps
461
        .iter()
462
        .filter_map(|a| {
463
            let (package, fp) = a.split_once(':')?;
464
            Some(serde_json::json!({
465
                "relation": ["delegate_permission/common.handle_all_urls"],
466
                "target": { "namespace": "android_app", "package_name": package, "sha256_cert_fingerprints": [fp.to_ascii_uppercase()] }
467
            }))
468
        })
469
        .collect();
470
    ([(header::CONTENT_TYPE, "application/json")], serde_json::Value::Array(apps).to_string()).into_response()
471
}
472
8f3d2ccf Andy McCall ↶ 473
/// The hub's TLS certificate (hub spec §15.5), for clients of a
474
/// developer edition with a self-signed certificate: save it and point
475
/// `oxy` at it with `OXY_CA` or `oxy config remote.<name>.ca`.
476
pub async fn hub_ca(State(app): State<Shared>) -> Response {
477
    if !app.config.tls.self_signed {
478
        return (axum::http::StatusCode::NOT_FOUND, "this hub does not use a self-signed certificate").into_response();
479
    }
480
    match tokio::fs::read(app.config.tls_cert()).await {
481
        Ok(pem) => (
482
            [(header::CONTENT_TYPE, "application/x-pem-file"), (header::CONTENT_DISPOSITION, "attachment; filename=\"oxyhub-ca.pem\"")],
483
            pem,
484
        )
485
            .into_response(),
486
        Err(_) => (axum::http::StatusCode::NOT_FOUND, "no certificate").into_response(),
487
    }
e9bfea8e Andy McCall ↶ 488
}
489
490
/// What this hub is built from (hub spec §15): its version and build, and
491
/// the versions of the Oxygen and OxygenFlow libraries it links.
492
pub fn versions() -> serde_json::Value {
493
    serde_json::json!({
494
        "oxygenhub": { "version": env!("CARGO_PKG_VERSION"), "build": env!("OXY_BUILD_ID") },
495
        "oxy_core": oxy_core::VERSION,
496
        "flow_core": flow_core::VERSION,
497
    })
498
}
499
500
#[derive(askama::Template)]
501
#[template(path = "about.html")]
502
pub struct AboutPage {
503
    shell: Shell,
504
    oxy_core: &'static str,
505
    flow_core: &'static str,
506
    /// Runners and the versions they report, for administrators.
507
    runners: Vec<crate::db::runners::Runner>,
508
}
509
510
/// `GET /about`: the hub's version and what it is built on; runners too, for
511
/// administrators.
512
pub async fn about(State(app): State<Shared>, viewer: Viewer) -> Result<Page<AboutPage>, Error> {
513
    let shell = Shell::new(&app, "/about", &viewer);
514
    let runners = if viewer.is_admin() { crate::db::runners::list(&app.db).await.unwrap_or_default() } else { vec![] };
515
    Ok(Page(AboutPage { shell, oxy_core: oxy_core::VERSION, flow_core: flow_core::VERSION, runners }))
8f3d2ccf Andy McCall ↶ 516
}