steid

@jamesgill /

Rust7.8 KBCode·Blame·History·Raw
1//! Request-scoped helpers.
2//!
3//! Functions taking `cx: &Cx`, not middleware or extractors — Topcoat's guidance, and
4//! the safer shape: a page that forgets to call `current_actor` gets no actor, whereas
5//! a route added without its middleware silently gets someone else's.
6
7use std::time::SystemTime;
8
9use sqlx::SqlitePool;
10use topcoat::{
11 Result,
12 context::{Cx, app_context},
13 router::{
14 HeaderName, HeaderValue,
15 error::internal_server_error,
16 header::{HOST, LOCATION},
17 headers,
18 },
19 session,
20};
21
22use crate::{
23 application::{AppConfig, Error, Identity, describe_identity, is_claimed, resolve_actor},
24 domain::{Actor, SessionTokenHash},
25 infrastructure::{
26 git::{DiskGitArchive, DiskGitStorage, GitHttpBackend},
27 git_query::DiskGitQuery,
28 repository::{
29 SqliteIssueRepo, SqliteMembershipRepo, SqliteOrgRepo, SqlitePushEventRepo,
30 SqliteRepoRepo, SqliteSessionRepo, SqliteTokenRepo, SqliteUserRepo,
31 SqliteWebhookDeliveryRepo, SqliteWebhookRepo,
32 },
33 webhook::UreqWebhookSender,
34 },
35};
36
37/// The one-time token that authorises claiming an unclaimed instance.
38///
39/// Present in app context only while the installation is unclaimed.
40pub struct SetupState(pub crate::domain::SetupToken);
41
42pub fn pool(cx: &Cx) -> &SqlitePool {
43 app_context::<SqlitePool>(cx)
44}
45
46/// Anything below the web layer failing is a 500 — the visitor can't act on it, and
47/// the detail belongs in the log rather than the page.
48pub fn server_error<E>(error: E) -> topcoat::Error
49where
50 E: std::error::Error + Send + Sync + 'static,
51{
52 eprintln!("steid: {error}");
53 internal_server_error(error).into()
54}
55
56/// Whether a use case failed because git was too slow rather than because git broke.
57///
58/// A timeout is the one read failure that is not a fault: the repository is fine and the
59/// request asked more of it than one page's budget allows. A page that can say so
60/// renders a state of its own — in its own words, offering whatever costs less — rather
61/// than a 500 that claims the instance is broken.
62///
63/// Four pages wanted this within one wave (`refs`, `commit`, `blame`, and `search`
64/// before it moved), which is what it took to earn a home here. `search_repo` is the
65/// exception and stays as it is: it answers `Searched::TimedOut` in the application
66/// layer, because there the timeout is one of several results the same form re-renders
67/// rather than an error to be caught.
68pub fn timed_out(error: &Error) -> bool {
69 matches!(error, Error::GitQuery(query) if query.is_timeout())
70}
71
72pub fn orgs(cx: &Cx) -> SqliteOrgRepo {
73 SqliteOrgRepo::new(pool(cx).clone())
74}
75
76pub fn memberships(cx: &Cx) -> SqliteMembershipRepo {
77 SqliteMembershipRepo::new(pool(cx).clone())
78}
79
80pub fn repos(cx: &Cx) -> SqliteRepoRepo {
81 SqliteRepoRepo::new(pool(cx).clone())
82}
83
84/// Bare repositories on disk, rooted at the configured data directory.
85pub fn storage(cx: &Cx) -> DiskGitStorage {
86 DiskGitStorage::new(app_context::<AppConfig>(cx).data_dir.clone())
87}
88
89pub fn users(cx: &Cx) -> SqliteUserRepo {
90 SqliteUserRepo::new(pool(cx).clone())
91}
92
93pub fn tokens(cx: &Cx) -> SqliteTokenRepo {
94 SqliteTokenRepo::new(pool(cx).clone())
95}
96
97pub fn issues(cx: &Cx) -> SqliteIssueRepo {
98 SqliteIssueRepo::new(pool(cx).clone())
99}
100
101/// Push events — one row per ref an authorized push moved.
102pub fn push_events(cx: &Cx) -> SqlitePushEventRepo {
103 SqlitePushEventRepo::new(pool(cx).clone())
104}
105
106pub fn webhooks(cx: &Cx) -> SqliteWebhookRepo {
107 SqliteWebhookRepo::new(pool(cx).clone())
108}
109
110pub fn deliveries(cx: &Cx) -> SqliteWebhookDeliveryRepo {
111 SqliteWebhookDeliveryRepo::new(pool(cx).clone())
112}
113
114/// Outbound webhook delivery.
115///
116/// Stateless — it holds no connection pool of its own, so it is constructed per request
117/// like every repository here rather than living in app context.
118pub fn webhook_sender(_cx: &Cx) -> UreqWebhookSender {
119 UreqWebhookSender::new()
120}
121
122/// Repository contents, read from the same data directory as [`storage`].
123pub fn queries(cx: &Cx) -> DiskGitQuery {
124 DiskGitQuery::new(app_context::<AppConfig>(cx).data_dir.clone())
125}
126
127/// `git archive`, rooted at the same data directory as [`storage`].
128pub fn archives(cx: &Cx) -> DiskGitArchive {
129 DiskGitArchive::new(app_context::<AppConfig>(cx).data_dir.clone())
130}
131
132/// The git smart-HTTP protocol, rooted at the same data directory as [`storage`].
133pub fn protocol(cx: &Cx) -> GitHttpBackend {
134 GitHttpBackend::new(app_context::<AppConfig>(cx).data_dir.clone())
135}
136
137/// Who is making this request.
138///
139/// Resolves to [`Actor::Anonymous`] when there is no session, the session is unknown,
140/// or it has expired.
141pub async fn current_actor(cx: &Cx) -> Result<Actor> {
142 let presented = session::token_hash(cx)
143 .await?
144 .map(|hash| SessionTokenHash::from_trusted(hex(&hash)));
145
146 let sessions = SqliteSessionRepo::new(pool(cx).clone());
147
148 resolve_actor(presented.as_ref(), SystemTime::now(), &sessions)
149 .await
150 .map_err(server_error)
151}
152
153/// Who the current actor actually is, resolved for display.
154///
155/// `None` when anonymous, or when the session outlived the user it names.
156pub async fn identity(cx: &Cx) -> Result<Option<Identity>> {
157 let actor = current_actor(cx).await?;
158 let pool = pool(cx).clone();
159
160 describe_identity(
161 &actor,
162 &SqliteUserRepo::new(pool.clone()),
163 &SqliteOrgRepo::new(pool),
164 )
165 .await
166 .map_err(server_error)
167}
168
169/// Whether this installation has an owner yet.
170pub async fn claimed(cx: &Cx) -> Result<bool> {
171 let users = SqliteUserRepo::new(pool(cx).clone());
172
173 is_claimed(&users).await.map_err(server_error)
174}
175
176/// The setup token, when the instance is still unclaimed.
177pub fn setup_token(cx: &Cx) -> Option<&crate::domain::SetupToken> {
178 topcoat::context::try_app_context::<SetupState>(cx).map(|state| &state.0)
179}
180
181/// The `Location` header for a post-redirect-get reply.
182///
183/// Pair it with `StatusCode::SEE_OTHER` inside a `view!` to redirect from a page that
184/// otherwise renders a view:
185///
186/// ```ignore
187/// view! { (StatusCode::SEE_OTHER) (location("/somewhere")?) }
188/// ```
189///
190/// The awkward-looking route to a 303: `redirect()` is a **307**, which preserves the
191/// method, so a browser re-POSTs the form to its target instead of fetching it.
192/// `see_other()` is the right status but is a response type, and `#[page]` handlers
193/// must return a view so the layout can wrap the failure re-render. Setting the status
194/// and header inside `view!` is the documented way to get both from one handler.
195pub fn location(uri: &str) -> Result<(HeaderName, HeaderValue)> {
196 Ok((LOCATION, HeaderValue::try_from(uri).map_err(server_error)?))
197}
198
199/// The origin this instance is being reached on, e.g. `https://steid.example`.
200///
201/// Derived from the request rather than configured, so an instance is deployable
202/// anywhere without being told its own address — behind a proxy, on a platform
203/// subdomain, or on localhost, all with no configuration.
204///
205/// The scheme comes from `X-Forwarded-Proto` when a proxy sets it, since TLS is
206/// terminated in front of us and the request that arrives here is plain HTTP. Falling
207/// back to `http` is right for local development and wrong nowhere that matters: a
208/// deployment without a terminating proxy has no TLS to advertise anyway.
209pub fn public_origin(cx: &Cx) -> String {
210 let headers = headers(cx);
211 let value = |name: &str| headers.get(name).and_then(|value| value.to_str().ok());
212
213 let scheme = value("x-forwarded-proto").unwrap_or("http");
214 let host = headers
215 .get(HOST)
216 .and_then(|value| value.to_str().ok())
217 .unwrap_or("localhost");
218
219 format!("{scheme}://{host}")
220}
221
222/// Renders a `TokenHash` as lowercase hex for storage.
223pub fn hex(hash: &session::TokenHash) -> String {
224 hash.iter().map(|byte| format!("{byte:02x}")).collect()
225}